flm-core 0.6.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
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
# Extending FLM: features and packages

This chapter is for the author of a feature or of a backend: a Rust programmer who wants
FLM to read a new construct, compute new data about a document, or write a new output
format.

Everything FLM can do comes from **features**. A
[registry](crate::core::registry) is the frozen record of everything the language and
the pipeline consult for a set of features: the elements, stages, tables, capabilities,
lowering rules, backends, outputs, workflows, option types and services the features
declared, built once and shared by every document, plan and run. A feature
([`FlmFeature`](crate::core::registry::FlmFeature)) is a Rust value that contributes a
related bundle of things to a registry (elements, stages, tables, lowering rules,
backends, services, settings) through the feature builder
([`FeatureBuilder`](crate::core::registry::FeatureBuilder)). A program decides what FLM can
do by choosing the features its registry is built from, usually grouped in
[packages](#bundling-features-as-a-package).

The standard features in [`stdlib`](crate::stdlib) register through the same interface
as a feature of yours. The library has no built-in set of elements that features add to,
and a standard feature uses no method of the feature builder that your feature cannot
call. For that reason this chapter uses the standard features as its examples: each
extension point is used by at least one of them, in code you can read.

A feature is written in Rust and compiled into the host that uses it (a host is any
program that embeds the library), or it comes from an *extension*: a set of files that a
host finds by name while it processes a document, written as data (settings only), in
JavaScript, or in Rust, compiled to WebAssembly or into the program (features with
behavior), and read through
the crate `flm-ext` (see
[Extensions](#extensions)). The library offers no way today to load a compiled feature
into a host that was not built with it.

The chapter covers, in order: a complete feature in one example; writing a feature;
declaring elements and their syntax; aspects; tables and stages; capabilities,
collections, ordering and workflows; lowering rules and output formats; options, settings
and services; the two build hooks; bundling features as a package; choosing packages at
run time; extensions, written as data, in JavaScript, or in Rust compiled to WebAssembly or into the program; a table of the standard features to read for each extension point, with
recipes that extend the numbering, headings, xnotes and cells features; and an extension
of this repository written in Rust, `phfpack`, end to end.

## A feature, end to end

The following example is a whole feature: a `\shout{…}` command that renders as bold
text. The example writes the feature, registers it beside the standard features, and
renders a document that uses it:

```rust
use std::sync::Arc;

use flm_core::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use flm_core::model::element::ElementSpec;
use flm_core::core::lowering::{
    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use flm_core::model::names::ElementName;
use flm_core::core::registry::{
    BuildError, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry, RegistryBuilder, RegistryInputs,
};
use flm_core::lang::Flm;
use flm_core::lang::mint::{ArgDef, ElementDef, SyntaxDef};
use flm_core::stdlib::backends::pres::{self, SpanPayload, SpanStyle};
use flm_core::techy::core::node::NodeRef;

/// The element `\shout` produces, and the rule that lowers it. Both names
/// begin with the feature's own name, so that they cannot collide with the
/// names of another feature.
const SHOUT: &str = "shout.shout";
const SHOUT_RULE: &str = "shout.shout.lower.default";

/// The lowering rule: a `\shout{…}` node becomes a bold `flm.pres.span` around
/// its argument, which is lowered by the rules of the elements it holds.
struct ShoutRule;

impl Lower for ShoutRule {
    fn lower(
        &self,
        node: NodeRef<'_, Flm>,
        cx: &mut LowerCx<'_>,
        lw: &mut dyn Lowerer,
    ) -> Result<Lowering, LowerError> {
        let body = lw.lower_arg_named(cx, &node, "text")?;
        let payload = SpanPayload { style: Some(SpanStyle::Bold), ..SpanPayload::default() };
        let span = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?;
        Ok(Lowering::Emit(vec![span]))
    }
}

/// The feature itself: one element and one lowering rule.
struct Shout;

impl FlmFeature for Shout {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new("shout", "Shouting").docs("The `\\shout` command.")
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        let owner = b.feature().clone();

        // The element value: what a `\shout` node *means*. Its block role says
        // it is ordinary inline content.
        let element = Arc::new(
            ElementSpec::new(SHOUT)
                .docs("Loud inline content.")
                .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT))),
        );

        // The syntax: a macro `\shout` with one mandatory argument named `text`.
        b.element(
            ElementDef::new(
                owner,
                ["shout"],
                SyntaxDef::Macro { args: vec![ArgDef::mandatory("text")] },
                element,
            )
            .docs("Shouts its text: writes it as bold inline content."),
        )?;

        // How it renders: the default rule for this element, on every backend.
        b.lowering_rule(
            LoweringRule::new(
                SHOUT_RULE,
                SHOUT,
                LoweringDecl::new().produces(pres::SPAN),
                Arc::new(ShoutRule),
                DefaultMark::Everywhere,
            )
            .docs("`\\shout` lowers to a bold span"),
        )?;

        Ok(())
    }
}

// Register it beside a package of the standard features.
let mut builder = RegistryBuilder::new();
builder.use_package(flm_core::stdlib::add_features(PackageEntry::new("std"), flm_core::stdlib::StdlibConfig::new()));
builder.use_package(flm_core::math_passthrough::package());
builder.feature(Arc::new(Shout));
let registry = builder.build(&RegistryInputs::new())?;

# use flm_core::model::doc::{Doc, DocContent, FragmentLayout};
# use flm_core::core::plan::{Overrides, Plan};
# use flm_core::core::run::{Externals, Run, RunOptions};
# use flm_core::lang::{FlmOrigin, ParseOptions, parse_fragment};
# use flm_core::stdlib::backends::text::{self, TEXT_OUTPUT};
# use flm_core::techy::source::Source;
// Render a document that uses it through the `text` workflow.
let source =
    Arc::new(Source::new("Please \\shout{listen} now.").with_origin(FlmOrigin::none()));
let fragment =
    parse_fragment(registry.lang(), source, FragmentLayout::default(), &ParseOptions::default())?;
let mut content = DocContent::new();
content.place(Arc::new(fragment));

let plan = Arc::new(Plan::for_workflow(&registry, text::WORKFLOW, &Overrides::none())?);
let mut run = Run::new(Arc::new(Doc::new(content)), plan, Externals::none())?;
run.execute(&RunOptions::new())?;

// Plain text cannot show boldness, so the emitter prints the content alone.
assert_eq!(run.table(TEXT_OUTPUT)?.expect("written").text, "Please listen now.\n");
# Ok::<(), Box<dyn std::error::Error>>(())
```

The example shows three separations that the rest of the chapter relies on:

- The **element** ([`ElementSpec`](crate::model::element::ElementSpec)) is the value
  that says what a node means: a declaration with a stable dotted type name, identified
  by the element value itself (its allocation) and not by its name.
- The **syntax** ([`ElementDef`](crate::lang::mint::ElementDef)) says how the construct
  is written, separately from the element.
- The **lowering rule** ([`LoweringRule`](crate::core::lowering::LoweringRule)) says how
  the construct renders, separately from both.

The builder records every declaration as the declaration of the feature that is
registering. A declaration that holds its owner's name, such as `ElementDef::new` above,
takes it from [`FeatureBuilder::feature`](crate::core::registry::FeatureBuilder::feature),
which returns the name under which the feature was registered, so the feature does not
repeat its name there.

## Writing a feature

A feature implements [`FlmFeature`](crate::core::registry::FlmFeature), which has two
required methods:

- [`info`](crate::core::registry::FlmFeature::info) returns a
  [`FeatureInfo`](crate::core::registry::FeatureInfo): the feature's registered name, a
  title, documentation and an optional version. The name is unique in a registry. By
  convention it is the middle segment of the names of everything the feature declares:
  `refs` in the stage name `flm.refs.resolve`.
- [`register`](crate::core::registry::FlmFeature::register) declares everything the
  feature contributes, by calling methods on the
  [`FeatureBuilder`](crate::core::registry::FeatureBuilder) it is handed.

A third method, [`settings`](crate::core::registry::FlmFeature::settings), is optional:
a feature whose settings can be written as data returns their declaration from it (see
[Settings given as data](#settings-given-as-data)).

Implement the trait on a value that holds the feature's own configuration (for example
`Blocks::new(BlocksConfig { .. })`), so that the compiler checks the configuration
rather than a schema. A feature's configuration is the plain Rust value the feature is
constructed from; it is fixed when the registry is built and cannot vary per document or
per render ([settings, options and
configuration](crate::guide::concepts_overview#settings-options-and-configuration)). The
registry build consumes the feature value; the finished registry keeps only its
`FeatureInfo` ([`FlmRegistry::features`](crate::core::registry::FlmRegistry::features)).

The **registry digest** ([`digest`](crate::model::digest)) is a number computed from
everything about a registry that can change what processing produces; a cache of results
keyed on it is reused only for an identical registry. The build computes the digest from
the declarations it can enumerate. A configuration that changes what processing produces
in a way the declarations do not show, such as the text of an author-written template,
must be passed to
[`FeatureBuilder::digest_input`](crate::core::registry::FeatureBuilder::digest_input), so
that the digest changes when that configuration changes. A feature's version string, if
it sets one, is also an input of the digest, so two registries whose features differ only
in version have different digests.

### The builder only records

Calling a method of the feature builder records one declaration. Nothing is resolved,
looked up or checked while a feature registers. **Registration order therefore never
limits what a feature may declare**: a feature may refer to a capability, a table or a
stage that another feature declares, whether or not that feature has registered yet, and
features never have to be listed in dependency order.

All the checking happens afterwards, in
[`RegistryBuilder::build`](crate::core::registry::RegistryBuilder::build), which works
through five phases: collect, finalize, validate, language and late initialization
([`BuildPhase`](crate::core::registry::BuildPhase); the [build
module](crate::core::registry::build) describes each). Each phase collects every problem
it finds. The first phase that finds a problem stops the build and returns all the
problems of that phase together, as one
[`RegistryBuildError`](crate::core::registry::RegistryBuildError); the phases after it
do not run, because they would report the consequences of the earlier problems as
problems of their own. A successful build returns a frozen
[`FlmRegistry`](crate::core::registry::FlmRegistry), which every plan and run built
against it shares through an `Arc` and which never changes again.

Features register in two rounds: `register` is the first, and the second is described
under [Build hooks](#build-hooks).

### Names

Every entity a feature registers, other than an element, is identified by a
[`Name`](crate::model::names::Name): a string, usually dotted and by convention
lowercase, whose first segment says who owns it: `flm` for the standard features, a
prefix of your own for anything you write. An element also has a name, its type name,
but it is identified by its element value (see [Element values](#element-values)). Each
kind of name has a Rust type of its own
([`ElementName`](crate::model::names::ElementName),
[`CapName`](crate::model::names::CapName),
[`StageName`](crate::model::names::StageName),
[`RuleName`](crate::model::names::RuleName), and the others of
[`names`](crate::model::names)), so that a function that asks for a capability name
cannot be given a stage name by mistake ([names and
identity](crate::guide::concepts_overview#names-and-identity)).

Capabilities, tables and collections share one set of names: declaring a table declares
a capability of the same name, and a collection may not take the name of either.
Features, stages, lowering rules, backends, outputs and workflows each have a set of
names of their own.

The usual forms are `<owner>.<thing>` for an element and
`<owner>.<element>.lower.<variant>` for a lowering rule. The standard features write a
stage's name `flm.<feature>.<verb>`, as in `flm.refs.resolve`.

Two kinds of name are also **a public interface for a stylesheet**: the name of a
presentation element, and the **role** that a lowering rule puts in a presentation
node's payload, a dotted name that says what a container is (`flm.heading.number` for
the number of a heading; [`pres::payload`](crate::stdlib::backends::pres::payload);
[decorations, roles and kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)).
The HTML backend
derives a CSS class from each of them, with every hyphen doubled and every dot turned
into one hyphen ([`class_of_role`](crate::stdlib::backends::html::names::class_of_role)):
`flm.heading.number` becomes `flm-heading-number`, and a page's stylesheet selects on
that class. Renaming a role therefore breaks every stylesheet written against it, as
renaming a public function breaks its callers: choose the name once and keep it. The
rendering guide describes the classes and attributes a stylesheet may rely on ([the HTML
contract](crate::guide::rendering#the-html-contract)).

The class reads back to exactly one name only when the name is **well formed**: each of
its segments (the parts between the dots) is non-empty and neither begins nor ends with
a hyphen. A name written in the usual forms above is well formed. Nothing checks the
condition, and a name that breaks it can share its class with another name
(`mypkg.a.-b` and `mypkg.a-.b` both give `mypkg-a---b`, and `mypkg.a..b` gives
`mypkg-a--b`, the class of the well-formed name `mypkg.a-b`).

## Declaring elements

An element is the value that says what a node means
([`ElementSpec`](crate::model::element::ElementSpec)); the syntax is how the construct is
written in the source. One declaration gives both: an element declaration
([`ElementDef`](crate::lang::mint::ElementDef)) is the plain data a feature gives for an
element, the syntax it is written in (macro, environment or special character sequence),
its arguments (each with a parser, a layout, a parsing mode and the scoped packages
available inside it) and its body. It lists the names the construct is written under, a
[`SyntaxDef`](crate::lang::mint::SyntaxDef) saying how those names are parsed, and the
element value its nodes carry. A feature registers it with
[`FeatureBuilder::element`](crate::core::registry::FeatureBuilder::element).

A feature gives the parser plain data only. From these declarations the library builds
the packages and specifications of techy, the parser toolkit FLM is built on, that a parse
resolves against. This step is called *minting* ([`lang::mint`](crate::lang::mint)).
Every parsed node therefore carries its element directly, and no lookup is needed to find
what a node means.

### Syntax

[`SyntaxDef`](crate::lang::mint::SyntaxDef) has five forms:

- `Macro { args }`: `\name` followed by its list of arguments;
- `Environment { args, body }`: `\begin{name}…\end{name}`, with its arguments after
  `\begin{name}` and its body;
- `Inclusion { args }`: a macro that brings the content of another file into the
  document, such as `\input{reference}`; the language's own inclusion parser reads it
  ([`lang::input`](crate::lang::input));
- `Specials { trigger, args }`: a special character sequence, such as `~` or `--`,
  followed by its arguments;
- `Synthesized`: no syntax at all. The element is never parsed: only a rewrite stage, a
  lowering rule, or a declaration elsewhere that carries its own syntax creates nodes of
  it.

The field element ([`FIELD`](crate::lang::structural::FIELD), `flm.field`) is one of the
language's structural elements, which no feature declares. A field is a macro that a
construct absorbs as data rather than as content, such as `\label` after a heading
([fields: data a construct
reads](crate::guide::concepts_overview#fields-data-a-construct-reads)). The construct that
accepts the field declares it as data, with the macro syntax by which it is parsed there,
and its node carries the field element (see [Fields absorbed after a
construct](#fields-absorbed-after-a-construct)). The `lowering` feature
([`LoweringFeature`](crate::stdlib::backends::lowering::LoweringFeature)) registers the
default lowering rule of field nodes.

A declaration is available in text mode unless it lists its parsing modes with
[`ElementDef::modes`](crate::lang::mint::ElementDef::modes): a command of mathematics
is declared with `[Mode::Math]`, and a command that applies in text and in mathematics
alike with `[Mode::Text, Mode::Math]`. So a command a feature declares without thinking
about mathematics cannot be written inside a formula: there it is an unknown command.
Two features that define one name in parsing modes that do not overlap do not clash.

### Arguments

Each argument is declared by an [`ArgDef`](crate::lang::mint::ArgDef): the parser that
reads it (one of the standard kinds of [`ArgStdKind`](crate::lang::mint::ArgStdKind), or
a parser of the feature's own,
[`FlmArgumentParser`](crate::lang::mint::FlmArgumentParser)), an optional name, the
parsing mode it is read in, its layout, whether its content is kept as typed under an
opaque wrapper, its scoped packages (the last three described below), and
documentation. Give an argument a name whenever anything reads it: a reader that
finds an argument by name keeps working when the argument list changes later, and one
that finds it by position does not.

| standard kind ([`ArgStdKind`](crate::lang::mint::ArgStdKind)) | what it reads |
|---|---|
| [`Mandatory`](crate::lang::mint::ArgStdKind::Mandatory) | a `{…}` group; a single token also counts, as in TeX |
| [`Optional`](crate::lang::mint::ArgStdKind::Optional) | an optional `[…]` group |
| [`Star`](crate::lang::mint::ArgStdKind::Star) | an optional `*` marker |
| [`Marker`](crate::lang::mint::ArgStdKind::Marker) | an optional marker of one or more characters other than a lone `*`, matched as written, as the `!` of `\name!` or the `\big` of `\name\big` |
| [`DelimitedGroup`](crate::lang::mint::ArgStdKind::DelimitedGroup) | a group between a prescribed pair of characters, as the `(…)` of `\name(arg)`; a single token does not count |
| [`OptionalDelimitedGroup`](crate::lang::mint::ArgStdKind::OptionalDelimitedGroup) | the same, optional |
| [`AnyDelimitedGroup`](crate::lang::mint::ArgStdKind::AnyDelimitedGroup) | a group in `{…}`, `[…]`, `(…)` or `<…>`, whichever the use site opens |
| [`OptionalAnyDelimitedGroup`](crate::lang::mint::ArgStdKind::OptionalAnyDelimitedGroup) | the same, optional |
| [`BracedOnly`](crate::lang::mint::ArgStdKind::BracedOnly) | a `{…}` group and nothing else: a single token does not count |
| [`Embellishments`](crate::lang::mint::ArgStdKind::Embellishments) | marker characters each followed by one expression, in any order, each at most once, as the `_{a}^{b}` of `\name_{a}^{b}` |
| [`KeyVals`](crate::lang::mint::ArgStdKind::KeyVals) | an optional `[key=value,…]` group |
| [`CharsGroup`](crate::lang::mint::ArgStdKind::CharsGroup) | a `{…}` group read as plain characters, as in `\label{sec:intro}` |
| [`Verbatim`](crate::lang::mint::ArgStdKind::Verbatim) | raw text between a pair of delimiters, as in `\verbcode\|…\|`; the closing delimiter is matched to the opening character unless the declaration prescribes the pair |
| [`TackOn`](crate::lang::mint::ArgStdKind::TackOn) | the fields ([`TackOnField`](crate::lang::mint::TackOnField)) that the construct absorbs after its own arguments, as `\section{…}` absorbs `\label{…}` |
| [`Terminated`](crate::lang::mint::ArgStdKind::Terminated) | everything up to a fixed *terminator*, as FLM markup or as raw text: `\phf … \endphf`, or the code span `` `…` `` that ends at the first place where as many backticks as opened it follow one another |

A terminated argument is written in three parts: a *prefix*, which may be a run of copies
of one character (as many as the author writes) followed by a fixed opener; the content;
and the terminator, which repeats the run of the prefix. At the argument's own level, the
terminator is matched character for character before any other markup, and it is never
read as a command: in `\phf … \endphf`, `\endphf` ends the content even where a command
`\endphf` exists. Nothing is trimmed from the content. What the content may hold depends
on the declaration:

- With `raw: true`, the content is raw text, like a verbatim argument's: the terminator is
  the only thing recognized in it, so the content needs no escaping.
- With `raw: false`, the content is parsed as FLM markup and follows the document's
  rules: commands are read as usual, groups must pair, and `%` starts a comment. Inside a
  nested `{…}` group the terminator is not recognized: `\phf a{b\endphf}c\endphf` ends at
  the second `\endphf`.

The variant's documentation gives the complete rules (such as where a longer run of the
repeated character ends the argument) and the errors reported for a missing terminator or
an incomplete prefix.

### An argument's syntax in settings

Settings written as data cannot hold a parser, so they give the syntax of each argument as
data, in one of two forms:

- The **structured syntax** is a standard kind written as data: a map whose key `syntax`
  holds the kind's name, in lowercase with hyphens, and whose other keys hold the kind's
  parameters, as in `{syntax: delimited-group, delimiters: ["(", ")"]}` for a group in
  parentheses or `{syntax: chars-group}` for a group read as plain characters. Every
  standard kind above can be written this way. A tack-on argument lists its fields, each
  with its name, its own arguments (an argument list, described below), whether it may be
  repeated and its documentation: `{syntax: tack-on, fields: [{name: label, args:
  [{syntax: chars-group}], repeatable: true}]}` accepts any number of `\label{…}` written
  after the command. The [documentation of
  `ArgStdKind`](crate::lang::mint::ArgStdKind#the-kind-as-data) lists each kind's name and
  parameters, and what reading a kind refuses.
- An **argument code** is a short text that stands for one structured syntax: `{` for a
  mandatory group, `[` for an optional one, `r()` for a group in parentheses, `e{_^}` for
  a subscript and a superscript, ``` F`` ``` for raw text after a run of backticks up to
  the same run followed by one more backtick (a code span, whose first backtick the
  command itself reads). A terminated argument has four codes: `u<terminator>` (content
  up to the terminator), `U<terminator>` (raw text up to it), `f<c><terminator>` (content
  after a run of the character `<c>`, up to the same run followed by the terminator, which
  may be empty) and `F<c><terminator>` (the same, raw text); these four are FLM's own. The
  [table of codes](crate::lang::mint::codes#the-codes) gives each code with the
  structured syntax it stands for. Four forms have no code and are written with the
  structured syntax: a group read as plain characters (`chars-group`), a group of
  `key=value` pairs (`key-vals`), a tack-on argument (`tack-on`), and a terminated
  argument with an opener or with fixed text before the repeated run of its terminator
  (`terminated` with `opener` or `head`).

An argument list ([`ArgListData`](crate::lang::mint::ArgListData)) is written in one of
three shapes: one text of one-character codes, such as `"[{"`; a list of codes; or a list
of entries, each a code or an argument's map. An argument's map
([`ArgDataFields`](crate::lang::mint::ArgDataFields)) gives the syntax in exactly one of
the two forms, the key `syntax` with the kind's parameters or the key `code`, beside the
argument's own keys: its name, layout, opaque wrapper (`opaque_wrapper`: `true` or
`false`), documentation, parsing mode (`mode`: `text` or `math`), scoped packages
(`scoped`: a list of names) and role. So
`{syntax: delimited-group, delimiters: ["(", ")"], name: size}` and
`{code: "r()", name: size}` declare the same argument. Two functions read these into
declarations:
[`arg_def_from_code`](crate::lang::mint::arg_def_from_code) reads one code, and
[`ArgListData::arg_defs`](crate::lang::mint::ArgListData::arg_defs) reads an argument
list. A declaration read from a code keeps that code
([`ArgDef::code`](crate::lang::mint::ArgDef::code)), and one read from a structured syntax
holds its standard kind, so that each can be written back in the form it was read from.

A feature whose own settings declare commands reads their argument lists through these
functions, as the `userdefs` feature does: it declares the settings field as
`Vec<ArgDef>` read with
[`deserialize_arg_list`](crate::lang::mint::deserialize_arg_list). It never reads an
argument's syntax itself, so that a syntax means the same form of argument in every
settings file.

An extension in JavaScript, or in Rust written against the guest client `flm_ext::guest`
(see [A Rust extension compiled to
WebAssembly](#a-rust-extension-compiled-to-webassembly)), declares its arguments with the
same data, since its declarations cross to FLM as data. In JavaScript, `new ArgDef(syntax)`
and `ArgDef.named(name, syntax)` take a code (`"r()"`) or a structured syntax
(`{ syntax: "chars-group" }`), and `arg_def_from_code(code)` answers the argument a code
stands for. In Rust, `ArgDef::new(kind)` and `ArgDef::named(name, kind)` take a standard
kind (`ArgStdKind::CharsGroup`), and `ArgDef::from_code(code)` and
`ArgDef::named_from_code(name, code)` read a code where the argument is made, with the
library's reader, `define` included; a text that is not a code is an error of kind
`arg-code`, with the library's message. A tack-on
argument is declared the same way, its fields as data: `{ syntax: "tack-on", fields: [{
name: "label", args: [new ArgDef({ syntax: "chars-group" })], repeatable: true }] }` in
JavaScript, and `ArgStdKind::TackOn { fields }` in Rust, each field a
`TackOnField::new("label", args)` with its own `ArgDef`s. When FLM gives an argument to an
extension, in a declaration or as the answer of a function such as `label_fields_arg()`,
it writes the argument in the form it was read from: with its code, with its structured
syntax, or, for a parser of a feature's own, with neither.

### What an argument holds: its role

An argument may state its **role**: a registered, dotted name that says what kind of thing
it holds, independently of how it is written. The argument of `\ref` and the argument of
`\eqref` are written differently, but both hold a label that points at a construct, so
both have the role `flm.refs.target`. The command `flm info` shows each argument's role on
the page of its command. The registry lists every argument that has a given role
([`Declarations::role_uses`](crate::core::registry::Declarations::role_uses), reached
through [`FlmRegistry::declarations`](crate::core::registry::FlmRegistry::declarations)),
which a program that describes the language or an editor can use, for example to complete
a label or a file path. Parsing and processing never read the role, and it is not an input
of the [registry digest](crate::model::digest).

Roles are names in a namespace of their own, the *argument roles*. A feature declares a role
with [`FeatureBuilder::argument_role`](crate::core::registry::FeatureBuilder::argument_role),
giving its name and a documentation text, and sets it on an argument with
[`ArgDef::role`](crate::lang::mint::ArgDef::role()):

```rust
# use std::sync::Arc;
# use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry};
# use flm_core::lang::mint::{ArgDef, ArgStdKind};
struct Glossary;
impl FlmFeature for Glossary {
    fn info(&self) -> FeatureInfo { FeatureInfo::new("glossary", "Glossary") }
    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        b.argument_role("acme.glossary.entry", "The key of a glossary entry.")?;
        let key = ArgDef::named("key", ArgStdKind::CharsGroup).role("acme.glossary.entry");
        # let _ = key;
        Ok(())
    }
}
# let registry = build_registry([Arc::new(Glossary) as Arc<dyn FlmFeature>])?;
# assert!(registry.argument_role_named("acme.glossary.entry").is_some());
# Ok::<(), flm_core::core::registry::RegistryBuildError>(())
```

The registry lists the roles with their documentation
([`FlmRegistry::argument_roles`](crate::core::registry::FlmRegistry::argument_roles),
[`argument_role_named`](crate::core::registry::FlmRegistry::argument_role_named)). In
settings written as data, an argument entry gives its role under the key `role`
(`{syntax: chars-group, name: target, role: flm.refs.target}`); an extension in
JavaScript or in Rust declares a role with `b.argument_role(name, docs)` and sets it with
`.role(name)` on its `ArgDef`. The same map gives the argument's name, layout,
documentation, mode, scoped packages and opaque wrapper (`opaque_wrapper: true` keeps the
argument's text as typed).

A feature may set a role that another feature declares. When that other feature may be
absent from the registry, the feature setting the role declares it as a peer with
[`FeatureBuilder::peer_argument_role`](crate::core::registry::FeatureBuilder::peer_argument_role),
as for the other [peer declarations](#peer-declarations): if no feature of the registry
declares the role, the registry still builds, with one note. A role that no feature declares
and that the feature setting it did not declare as a peer stops the build
([`BuildError::UndeclaredArgumentRole`](crate::core::registry::BuildError::UndeclaredArgumentRole)),
which catches a misspelled name.

The standard features declare eight roles:

| role | declared by | set on |
|---|---|---|
| `flm.refs.target` | `refs` | the label of `\ref` and `\hyperref`; `\eqref` of `math` |
| `flm.refs.defined-label` | `refs` | the label of the field `\label`, inside the scoped package `flm.refs.label` too; the `\label` of an equation line of `math` |
| `flm.citations.key` | `citations` | the keys of `\cite`, and of the field `\cite` written after `\cite` or `\R` |
| `flm.defterm.defined-term` | `defterm` | the term of the environment `defterm` and of the field `\aliasterm` |
| `flm.defterm.target` | `defterm` | the term that `\term` points at |
| `flm.graphics.path` | `graphics` | the path of `\includegraphics` |
| `flm.input.path` | `input` | the file of `\input` |
| `flm.href.address` | `href` | the address of `\href`, `\url` and `\email` |

The names are constants of their features (for example
[`refs::TARGET_ARG_ROLE`](crate::stdlib::features::refs::TARGET_ARG_ROLE)), and a feature
of your own that sets one of these roles uses the constant. A role of your own begins with
a prefix of your own, as every name does (see [Names](#names)), and follows the form of the
standard ones, `<owner>.<feature>.<thing>` (`acme.glossary.entry`).

### An argument's layout

An argument's content is laid out by the block-structure pass, the rewrite that lays out
content in paragraphs and blocks, or as inline content
([`blocks`](crate::lang::rewrites::blocks)), unless it is an [opaque
region](crate::guide::concepts_overview#opaque-regions), which the pass carries over as
written: content read in mathematics mode, verbatim text, and content under an opaque
wrapper (an argument declared with
[`ArgDef::with_opaque_wrapper`](crate::lang::mint::ArgDef::with_opaque_wrapper), and every
characters-only group). An argument declared with an opaque wrapper
takes no layout: a layout other than inline is refused when the language is built.
The argument's declaration chooses its layout
([`ArgDef::layout`](crate::lang::mint::ArgDef::layout)), one of the three values of
[`ArgLayout`](crate::lang::mint::ArgLayout):

- **inline content**, the default: no paragraph is built inside the argument. A blank
  line in it is reported and read as one space; a block-level element in it is reported
  and kept where it is written.
- **a region of blocks** ([`ArgDef::blocks`](crate::lang::mint::ArgDef::blocks)):
  paragraphs are built inside the argument and block-level elements stay on their own,
  as in an environment body declared
  [`BodyLayout::Blocks`](crate::lang::mint::BodyLayout::Blocks). One line of text is one
  paragraph.
- **inferred from the content**
  ([`InlineOrBlocks`](crate::lang::mint::ArgLayout::InlineOrBlocks)): a region of blocks
  when the content holds a blank line or a block-level element, inline content
  otherwise. A fragment laid out
  [`InlineOrBlocks`](crate::model::doc::FragmentLayout::InlineOrBlocks) applies the same
  test to its top level.

An argument's layout does not depend on where the command is written: a command written
in the middle of a paragraph, or in a heading's title, still holds paragraphs in an
argument declared as blocks.

Two declarations can never take effect, and minting reports both: a layout other than
inline on an argument declared with an opaque wrapper
([`ArgDef::with_opaque_wrapper`](crate::lang::mint::ArgDef::with_opaque_wrapper);
[`MintError::LayoutOnOpaqueWrappedArgument`](crate::lang::mint::MintError::LayoutOnOpaqueWrappedArgument)),
and the blocks layout on an argument read in mathematics mode
([`ArgDef::mode`](crate::lang::mint::ArgDef::mode);
[`MintError::BlocksOnMathArgument`](crate::lang::mint::MintError::BlocksOnMathArgument)).
The block-structure pass carries the content of both over untouched ([opaque
regions](crate::guide::concepts_overview#opaque-regions)).
The check of the tree contract
([`check_block_contract`](crate::lang::rewrites::blocks::check_block_contract)) reports
an argument whose content does not match its declared layout, as it does for an
environment body.

An element that must know whether one of its arguments holds blocks (to choose its own
block role, which the block-structure pass reads, and again to choose how it is rendered
after that pass) calls
[`argument_holds_blocks`](crate::lang::rewrites::blocks::argument_holds_blocks) instead
of inspecting the content. The function decides from the declared layout and, for an
inferred layout, by the same test the block-structure pass applies, and it returns the
same result on the tree before the pass and after it. The decision is therefore made in
one place, and no element works it out again.

The worked case is `\footnote`, which the
[`xnotes`](crate::stdlib::features::xnotes) feature declares. Its content argument is
inferred by default, since a note is usually one line of text and sometimes several
paragraphs, and the feature's configuration may fix the layout for a kind of note. Its
optional argument accepts the `\label{…}` of the note, and nothing else, through a
scoped package (see [Scoped packages](#scoped-packages) below):

```text
[
    ArgDef::optional("labels").scoped("flm.refs.label"),
    ArgDef::mandatory("xnote").layout(kind.layout),
]
```

With this declaration, `\footnote[\label{fn:a}]{One line.}` and a `\footnote{…}` holding
two paragraphs are both read as the author means them, and `\label` written in the
running text or inside the note's content is an unknown command. The scoped package
`flm.refs.label` belongs to the `refs` feature, which declares `\label`. The `xnotes`
feature makes a peer declaration of it (see [Scoped packages](#scoped-packages)), so a
registry without the `refs` feature still builds, and the optional argument then
accepts nothing.

### Fields absorbed after a construct

A field is a macro that a construct absorbs as data rather than as content, and a
construct takes its fields through its **tack-on argument**
([`ArgStdKind::TackOn`](crate::lang::mint::ArgStdKind::TackOn)), the argument that absorbs
the field macros written at its position in a call, after the arguments declared before
it ([fields: data a construct
reads](crate::guide::concepts_overview#fields-data-a-construct-reads)). Its fields must
have distinct names; minting reports a declaration that breaks this rule
([`MintError::FieldDeclaredTwice`](crate::lang::mint::MintError::FieldDeclaredTwice)).

The fields a tack-on argument absorbed are **data that the construct which declared the
argument reads**, and nothing else reads them. Every field node is a macro node that
carries the element `flm.field` ([`FIELD`](crate::lang::structural::FIELD)), and its macro
name is the field's name as written ([`field_name`](crate::lang::mint::field_name) returns
it). A field is declared as data ([`TackOnField`](crate::lang::mint::TackOnField): its
name, its arguments, whether it may be repeated, and its documentation), in Rust or in
settings given as data, and chooses no element. A field's
name means what its declaring construct says it means, and nothing across the document is
keyed on it: your `\label` field is your construct's own, even though the `refs` feature
declares a field of that name too.

Where a field is written in the content makes no difference, since it represents no
content there. For that reason, a field node that reaches a backend is an error
(`flm.lowering.field-not-read`): it means that the construct that absorbed it did not
read its data. Read your fields in the aspect or the lowering rule that needs them, and
write what they mean from there.

A user definition (a macro, environment or special character sequence that a document's
author or the host defines by substitution;
[`Definition`](crate::lang::rewrites::userdefs::Definition)) may declare a tack-on
argument, but its template may not refer to it: the macros a call absorbed are whole
commands and have no meaning as the value of a parameter. A template that refers to one
is an error, reported when the definition is compiled, on every backend. What such a call
absorbs is written nowhere; no placeholder exists today that reads the absorbed fields.

### Environment bodies

An environment's body is declared by a [`BodyDef`](crate::lang::mint::BodyDef), which
says:

- how the block-structure pass lays the body out
  ([`BodyLayout`](crate::lang::mint::BodyLayout): inline, blocks, or according to the
  element's own block role);
- what reads the body when it is not read the ordinary way: raw text
  ([`BodyDef::verbatim`](crate::lang::mint::BodyDef::verbatim)), or a body parser of the
  feature's own ([`BodyDef::parser`](crate::lang::mint::BodyDef::parser));
- which parsing mode the body is read in;
- whether the body's content is kept as typed under an opaque wrapper
  ([`BodyDef::with_opaque_wrapper`](crate::lang::mint::BodyDef::with_opaque_wrapper);
  [opaque regions](crate::guide::concepts_overview#opaque-regions)), in which case a
  layout other than the default, `FromRole`, is refused when the language is built;
- which scoped packages are available inside it.

### Scoped packages

A scoped package ([`ScopedPackageDef`](crate::lang::mint::ScopedPackageDef)) is a set of
element declarations that can be written only inside the environment bodies and
arguments whose declarations refer to the package by name, for instance `\item` inside a
list's body or `\caption` inside a float's body. A body or an argument refers to a
scoped package with [`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped) or
[`ArgDef::scoped`](crate::lang::mint::ArgDef::scoped), and a feature declares one with
[`FeatureBuilder::scoped_package`](crate::core::registry::FeatureBuilder::scoped_package)
([scoped packages](crate::guide::concepts_overview#scoped-packages)).

A scoped package gives an environment or a command constructs of its own, which mean
nothing outside it, without adding them to the language everywhere. The parser adds the
package to the parsing state for the length of the body or the argument, so its
declarations take precedence over any other declaration of the same name there. Any
body or argument may refer to a scoped package, whatever reads it: inside a reading
that recognizes no command, such as a characters-only group or a verbatim argument,
the package's declarations cannot be reached, and nothing is reported. The
`math` feature declares one for the commands of an equation line, which can be written
only inside the bodies of its display-math environments
([`math::lines`](crate::stdlib::features::math::lines)); `\footnote`'s optional
argument, above, is the case of an argument. A scoped package may add as little as one
special character: the data argument of the `cells` feature's `\celldata` refers to a
package that holds `&` alone
([`cells::DATA_PACKAGE`](crate::stdlib::features::cells::DATA_PACKAGE)), so that `&`
ends an entry there and is an ordinary character everywhere else. Two scoped packages
that declare one name (two features each giving `\\` a meaning inside its own
environment) never clash: each is available only where it is referred to, and where one
is added inside the other, the inner one takes precedence.

Any feature may declare a scoped package, whether it registers before or after the
features that refer to it. A feature that refers to a package which another feature
owns makes a **peer declaration** of it with
[`peer_scoped_package`](crate::core::registry::FeatureBuilder::peer_scoped_package). A
peer declaration ([`PeerName`](crate::core::registry::PeerName)) is a feature's forward
declaration of something another feature owns (see [Peer declarations](#peer-declarations)).
When no feature of the registry declares the package, the build succeeds with one Note,
the bodies and arguments that refer to the package get nothing from it, and every
command the package would define is an unknown command there.

The registry build fails, with a [`MintError`](crate::lang::mint::MintError), in two
cases:

- a body or an argument refers to a package that no feature declares and that the
  referring feature did not peer-declare; this catches a misspelled name
  ([`MintError::UnknownScopedPackage`](crate::lang::mint::MintError::UnknownScopedPackage));
- packages refer to each other in a circle, through bodies or arguments
  ([`MintError::ScopedPackageCycle`](crate::lang::mint::MintError::ScopedPackageCycle)).

### Element values

One element *type name* may have several element *values*. `\section` and `\subsection`
are two values of the single element type `flm.heading`, which differ in the data each
value carries ([`ElementSpec::with_value`](crate::model::element::ElementSpec::with_value));
the four commands of the `textstyles` feature are four values of `flm.textstyle`. A
family of related commands is declared as one element type with one element value per
command: the type name says what kind of thing a node is, and the data of each element
value tells the commands apart ([elements and
aspects](crate::guide::concepts_overview#elements-and-aspects)). One lowering rule, written
for the element type, then serves every command of the family.

An element value is shared as `Arc<ElementSpec>`, and its **identity is the allocation**,
not the name: two handles designate the same element when
[`ElementSpec::same_value`](crate::model::element::ElementSpec::same_value) returns
`true`. Several names may share one element value: an
[`ElementDef`](crate::lang::mint::ElementDef) lists every name its element is written
under, and every command of one heading kind is, in this way, a name of that kind's one
element value.

### Fallbacks, and replacing another feature's definition

Two more declarations concern the names of commands rather than elements.

A **fallback** ([`FallbackDef`](crate::lang::mint::FallbackDef), registered with
[`FeatureBuilder::fallback`](crate::core::registry::FeatureBuilder::fallback)) says what
a command name means in a parsing mode where no declaration defines it. The
`math-passthrough` feature declares two fallbacks, one for macros and one for
environments, both restricted to mathematics mode. In mathematics, a command that no
feature declares therefore becomes a node of the element `flm.math-passthrough.opaque`
([`OPAQUE`](crate::math_passthrough::OPAQUE)), which keeps its source
character for character and is not reported, instead of an unknown command reported as
an error.

Where several features define one command name in a parsing mode, the definition of the
feature placed last in the order of features applies (each mode is decided on its own:
a definition for text mode never meets one for mathematics mode). This is allowed when
the chains of the feature order
([`FeatureChain`](crate::core::registry::FeatureChain); a package's `feature_order`)
place that feature after every other feature that defines the name in that mode, or
when that feature declares its definition as an override with
[`override_callable`](crate::core::registry::FeatureBuilder::override_callable), giving
the command's callable kind (macro, environment or special character sequence;
[`CallableKind`](crate::lang::mint::CallableKind)) and its name. Otherwise the registry
build fails, with a message naming the features and the chain that would choose the
last one's definition. Only the override of the feature placed last is consulted; the
others' are never read.

## Aspects

An aspect is a piece of behavior attached to an element when the feature registers it
and read back through a trait object; it answers per occurrence of the element and reads
no options ([elements and aspects](crate::guide::concepts_overview#elements-and-aspects)).
A stage or a backend finds out what an element does by asking for one of its aspects
("is this a block?", "which reference points does this node carry?"), never by matching
the element's name against a list. A stage written today therefore works on an element
that a feature written later declares. A feature of an extension written in JavaScript
answers the aspects `Referenceable` and `Sectioning` through objects of its script (see
[What a feature in JavaScript adds to the
output](#what-a-feature-in-javascript-adds-to-the-output)).

Any object-safe trait whose implementations can be shared between threads (a trait with
`Send + Sync` as supertraits) can serve as an aspect: an aspect trait needs no
registration, and a feature, or a test, may define its own. An element carries at most one
implementation of each aspect. Attach an aspect when you build the element value, with
[`ElementSpec::with`](crate::model::element::ElementSpec::with), and read it back with
[`ElementSpec::aspect`](crate::model::element::ElementSpec::aspect):

```rust
use std::sync::Arc;
use flm_core::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use flm_core::model::element::ElementSpec;

// Any object-safe trait with `Send + Sync` as supertraits can be an aspect; the trait
// is registered nowhere.
trait Glossary: Send + Sync {
    fn term(&self) -> &str;
}
struct Term(&'static str);
impl Glossary for Term {
    fn term(&self) -> &str { self.0 }
}

let element = ElementSpec::new("thm.term")
    .docs("a glossary term")
    .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
    .with::<dyn Glossary>(Arc::new(Term("stabilizer")));

assert!(element.has_aspect::<dyn Glossary>());
assert_eq!(element.aspect::<dyn Glossary>().map(|g| g.term()), Some("stabilizer"));
```

Two rules hold for every aspect:

- **An aspect is evaluated per occurrence.** The node is a parameter of every method, so
  the same heading element declares a different reference point at each place it
  occurs.
- **An aspect reads no options.** Aspects are consulted during the rewrite stages and
  while a plan is built, before option values are bound. A fact that varies from
  document to document is an option of the stage that uses the aspect's result, not of
  the aspect. A fact fixed by the feature's configuration is held by the element's data
  or by the aspect's implementation.

### The standard aspects

The aspects that many features implement, and the aspects that state what an element is,
are in [`model::aspects`](crate::model::aspects):

- [`BlockRoleAspect`](crate::model::aspects::BlockRoleAspect): whether an occurrence is a
  block, inline content, a displayed item (content set on lines of its own inside its
  paragraph, such as a display equation; see [paragraphs, blocks and displayed
  items](crate::guide::concepts_overview#paragraphs-blocks-and-displayed-items)), or a
  decorator attached to its block;
- [`Referenceable`](crate::model::aspects::Referenceable): the reference points an
  occurrence declares;
- [`Referencing`](crate::model::aspects::Referencing): the reference sites an occurrence
  declares, the places that point at a reference point;
- [`Sectioning`](crate::model::aspects::Sectioning): a heading's level, whether it is
  listed in the table of contents, and what the table of contents shows for it
  ([`toc_title`](crate::model::aspects::Sectioning::toc_title)); the
  [`toc`](crate::stdlib::features::toc) feature lists every element that carries this
  aspect, a heading of an extension's own element included;
- [`ApartFromText`](crate::model::aspects::ApartFromText): the content of an occurrence
  that is not part of the text around it, such as the words of a footnote written in a
  heading's title;
- [`InCopy`](crate::model::aspects::InCopy): what replaces an occurrence in a copy of
  content shown a second time, away from where it is written;
- [`Whitespace`](crate::model::aspects::Whitespace): that each occurrence is whitespace,
  as `~` and `\ ` are. The block-structure pass removes such a node where it removes
  whitespace: beside an element whose block role removes the whitespace on that side
  ([`InlineSpacing`](crate::model::aspects::InlineSpacing), as `\cite` does before it), on
  both sides of a displayed item, at the edges of a paragraph, and between blocks. A
  paragraph that a lowering rule writes itself, over content it cuts out of a longer run
  (a quotation's passage, attribution and lines, a `\celldata` entry), is trimmed by
  [`stage_trimmed`](crate::stdlib::backends::lowering::stage_trimmed), which removes the
  same whitespace at its edges as the pass does, whitespace nodes included, and the
  standard features' tests for blank content count such a node as whitespace (a footnote
  holding only `~` is empty), except the tests of text read as typed or with its markup,
  such as a citation key or a term, of which the node is part (a term holding only `~` is
  not empty). Everywhere else the node is kept, as a node of its own, which its element's
  lowering rule lowers. The aspect has no method: attach its
  implementation
  [`IsWhitespace`](crate::model::aspects::IsWhitespace), and read it with
  [`is_whitespace_of`](crate::model::aspects::is_whitespace_of).

Three aspects are read when a document is rendered and are declared with the elements of
the presentation vocabulary (the presentation elements the standard backends write;
[`pres`](crate::stdlib::backends::pres)): [`Decoration`](crate::stdlib::backends::pres::Decoration),
[`OpaqueContent`](crate::stdlib::backends::pres::OpaqueContent) and
[`ContentInOpaque`](crate::stdlib::backends::pres::ContentInOpaque).

Three further aspects are declared beside the rewrite pass that reads them, because they
mean nothing apart from it:

- [`Expand`](crate::lang::rewrites::userdefs::Expand), through which an element rewrites
  its own use sites while user definitions are expanded;
- [`BlockStructure`](crate::lang::rewrites::blocks::BlockStructure), through which an
  element lays out its own content while paragraphs and blocks are built;
- [`BlockTransparent`](crate::lang::rewrites::blocks::BlockTransparent), through which a
  [block-transparent](crate::guide::concepts_overview#block-transparent-elements) element
  is cut into parts before any paragraph is built.

The rewrite pass calls each of these through an interface of its own (an
[`Expander`](crate::lang::rewrites::userdefs::Expander), a
[`BlockStructurer`](crate::lang::rewrites::blocks::BlockStructurer), a
[`BlockCutter`](crate::lang::rewrites::blocks::BlockCutter)), in the same way as a
lowering rule works through a [`Lowerer`](crate::core::lowering::Lowerer): the
element's implementation never accesses the rewrite pass itself.

### A block role that depends on the position

An element whose block role depends on where it is written returns its role from its
aspect, which receives the node. The `cells` feature's `\cell` is a block where it is
a direct child of the body of a `cells` environment, and inline content anywhere else
([`InBody`](crate::stdlib::features::cells::InBody)); the `graphics` feature's image is
a block where it is a direct child of a float's body. Keep the test in one function
([`cells::stands_in_body`](crate::stdlib::features::cells::stands_in_body)), and make
the element's lowering rule, or any other reader, either call that function or read
exactly the nodes the function accepts (the `cells` reader reads the direct children of
the body, which are those nodes and no others), so that the role and the reading cannot
disagree. Make the function test the element of the environment whose body holds the
node (the node's owner), not any other node that this environment holds.

### Reference points and labels

A reference point is one place in a document that can be referred to, numbered, or
given an anchor (a heading, an equation line, a theorem, a footnote); an element
declares its reference points per occurrence through the
[`Referenceable`](crate::model::aspects::Referenceable) aspect, and the `refpoints`
feature records them per tree ([`RefPoint`](crate::model::aspects::RefPoint)). A label is
the text an author writes as `\label{type:label}` after a construct, which the construct
reads as a field and attaches to its reference point ([reference points, labels and
anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)).

**A construct with labels takes three steps.**

1. Declare [`label_fields_arg`](crate::stdlib::features::refs::label_fields_arg) as
   the element's last argument, so that `\thing{…}\label{x:y}` is parsed.
2. Read the fields with [`label_uses`](crate::stdlib::features::refs::label_uses), and
   split them with [`point_labels`](crate::stdlib::features::refs::point_labels) into
   the labels written `type:label` and the texts that are not, which the `refs` feature
   then reports.
3. Put both lists on the [`RefPoint`](crate::model::aspects::RefPoint) that your
   `Referenceable` implementation returns.

Nothing else reads those fields, and nothing else has to: a `\label` is data your
construct absorbed. If your construct has a lowering rule of its own on the recomposed
LaTeX, write its labels there with
[`stage_label`](crate::stdlib::features::refs::stage_label) and
[`stage_label_group`](crate::stdlib::features::refs::stage_label_group); the rule must
declare what those functions read and produce, which their documentation lists (among
others, the table of safe labels
[`flm.labels.safe`](crate::stdlib::features::refs::SAFE_LABELS)).

A reference point states **the two things a reference to it may show**:

- a [number source](crate::model::aspects::RefPoint::number), where the construct can be
  numbered at all. A number source
  ([`NumberSource`](crate::model::aspects::NumberSource)) is what a reference point says
  it is numbered by: the counter, the counter style, the scoped instances it counts
  under, and optionally a number template of its own;
- [content](crate::model::aspects::RefPoint::content), where the construct has content
  of its own: an argument of the node, its body, one node of its tree, or, for content
  that no node holds by itself (a label text that the feature's configuration supplies, a
  part of a run of characters), a small tree that the construct builds
  ([`ContentRef::Synthesized`](crate::model::aspects::ContentRef::Synthesized)).

A reference shows the first of them that exists: the number, where the document numbered
the point; else the content; else the label the reference was written with. A construct
states both, one, or neither. A point that states a number source is numbered by the
[numbering](crate::stdlib::features::numbering) feature, which has no setting that
turns numbering off for a point; whether a point states one is therefore the construct's
decision, taken from its node and from its feature's configuration. The headings feature
states a number source for a heading whose kind its configuration numbers (no kind, by
default), so a reference to a heading shows the heading's number in a registry that
numbers that kind, and its title in one that does not. The mathematics feature states one
for every line that has neither `\nonumber` nor `\tag`, unless its configuration numbers
no equations; a tagged line states its tag as content instead. A
construct of your own is numbered in the same way (see [Number a construct of your
own](#number-a-construct-of-your-own)).

A reference point also declares **which label types may be written for it**
([`RefPoint::accepts`](crate::model::aspects::RefPoint::accepts)). A label is written
`type:label`, and the label type says what sort of thing the label marks.
[`AcceptedRefTypes::these(["thm", "lem"])`](crate::model::aspects::AcceptedRefTypes)
accepts those two types and refuses every other, and
[`AcceptedRefTypes::Any`](crate::model::aspects::AcceptedRefTypes) accepts every type,
which suits a construct whose label types are not fixed in advance. A refused label
defines nothing: no reference resolves through it, a point whose every label was refused
gets no anchor from a label, and the label check reports
`flm.refs.label-type-not-accepted`.

### Templates with values the feature computes

A feature may write its macros as templates, like user definitions, and also place in
those templates values that the feature computes at each use, such as a delimiter drawn
at the size the use asked for. Such a feature declares its macros as
[`Definition`](crate::lang::rewrites::userdefs::Definition)s and declares the extra
placeholders of each with
[`Definition::extra_placeholder`](crate::lang::rewrites::userdefs::Definition::extra_placeholder)
(`#{name}`, or `#[…]{name}` when the placeholder takes a substitution argument). A
placeholder is a reference in a template to an argument, the body, or a name whose
content an expansion hook computes ([the template
language](crate::lang::rewrites::userdefs::template)).

The templates compile as every user definition's do, arguments, default values and
parsing modes included, through
[`UserDefinition::compile_with`](crate::lang::rewrites::userdefs::UserDefinition::compile_with),
called from a [`LateInit`](crate::core::registry::LateInit) hook (see [Build
hooks](#build-hooks)). The feature then attaches its own `Expand` aspect to the element,
in place of the definition's, and instantiates the definition's template with
placeholder bindings of its own: they give the content of the extra names and pass every
other reference to
[`DefinitionBindings`](crate::lang::rewrites::userdefs::DefinitionBindings), the
bindings a user definition's own expansion uses. `#1`, a named argument and a default
value therefore mean the same in the feature's templates as in an author's.
[`ExtraValues`](crate::lang::rewrites::userdefs::ExtraValues) give such bindings
without an implementation of
[`PlaceholderBindings`](crate::lang::rewrites::userdefs::PlaceholderBindings): the
feature adds a value for each extra placeholder written in the template and in the
default values of the definition's arguments
([`ModeVariant::defaults`](crate::lang::rewrites::userdefs::ModeVariant::defaults)),
under the placeholder's name and the text of its substitution argument
([`CompiledTemplate::substitution_text`](crate::lang::rewrites::userdefs::CompiledTemplate::substitution_text)),
and lays the values over `DefinitionBindings` with
[`ExtraValues::over`](crate::lang::rewrites::userdefs::ExtraValues::over).

A value the feature computes is given as a finished tree
([`PlaceholderValue::Tree`](crate::lang::rewrites::userdefs::PlaceholderValue::Tree)),
which the feature can prepare once, when the registry is built: it compiles the value's
text with
[`compile_template_with`](crate::lang::rewrites::userdefs::compile_template_with)
through [`compile_in_modes`](crate::lang::rewrites::userdefs::compile_in_modes), which
applies the rule a user definition's text follows: the text is kept in each parsing mode
where it compiles, and its failures are reported only when it compiles in none. The
feature's values and the definitions' templates then exist in the same parsing modes.

A feature may also compile a template that refers to no argument of a use site, only to
values the feature computes (for example a heading's title line `#{number}. `, compiled
from the feature's configuration), and instantiate it outside the expand pass, from a
lowering rule. [`instantiate`](fn@crate::lang::rewrites::userdefs::instantiate)
instantiates a compiled template under any placeholder bindings, as a new tree whose
root's children the rule splices into its output
([`Lowerer::splice`](crate::core::lowering::Lowerer::splice)).
[`ValueBindings`](crate::lang::rewrites::userdefs::ValueBindings) are the bindings for
such a template: `ValueBindings::new().with("number", tree)` gives the extra placeholder
`#{number}` the finished tree `tree`; an extra placeholder they hold no tree for has no
value (`\IfNoValueTF{#{name}}` takes its first branch), and an argument or the body,
which such a template does not have, makes `instantiate` fail. The instantiation
descends the template recursively, so it runs on a worker thread of the library, as a
lowering rule and an expansion hook do ([the worker-thread
requirement](crate::lang::guard#the-worker-thread-requirement)).

Three more functions let such a feature register its definitions without repeating any
rule of the user definitions:

- [`UserDefinition::element_def_with`](crate::lang::rewrites::userdefs::UserDefinition::element_def_with)
  builds the element and its declaration as for a user definition, but with the
  feature's `Expand` aspect: the element still carries the definition as its data, its
  block role and its parsing modes.
- [`UserDefinition::variant_for_use`](crate::lang::rewrites::userdefs::UserDefinition::variant_for_use)
  returns the compiled templates for a use site, or the condition to report where the
  definition cannot expand that use (the definition was refused when the registry was
  built, or its text did not parse in the use site's parsing mode).
- [`element_name_under`](crate::stdlib::features::userdefs::element_name_under)
  derives the element's type name from the feature's own prefix (for example
  `mypack.macro.ket`), and
  [`expand_in_tree_rule_for`](crate::stdlib::features::userdefs::expand_in_tree_rule_for)
  builds the element's lowering rule for every backend. That rule requires the trees
  table that the `userdefs` feature's rewrite stage for the definition's expansion policy
  writes ([`ALWAYS_EXPANDED`](crate::stdlib::features::userdefs::ALWAYS_EXPANDED) for an
  `always` definition, [`EXPANDED`](crate::stdlib::features::userdefs::EXPANDED) for a
  `per-plan` one), so the plan schedules that stage. Only the `userdefs` feature declares that table, so a registry that holds such a rule without the `userdefs`
  feature does not build.

The extension `phfpack`, written in Rust, uses these functions through the guest client
of the extension interface (see [A Rust extension, end to
end](#a-rust-extension-end-to-end)), with
[`ExtraValues`](crate::lang::rewrites::userdefs::ExtraValues) for the values it
computes at each use.

### User definitions in the recomposed LaTeX

On the `latex-recomposed` backend, a user definition is not only expanded: the backend
writes it back as a LaTeX definition of its own in the style file (the `.sty` file
written beside the recomposed LaTeX document), and writes each use site as a call of it.
Everything a definition can declare is written back in this way: arguments of every form
listed above, in any position and in any number, default values, the fourteen
conditionals of the template language, a name declared twice (once per parsing mode),
and a definition that uses itself.

Three kinds of definition are written expanded at every use site instead:

- a definition of a **special character sequence**, whose trigger is not a LaTeX command;
- a definition marked **always expanded**, which asked for it;
- a definition the registry **refused**, whose refusal was reported when it happened.

A definition that uses one of these three is written expanded with it. So is a definition
whose template holds a placeholder that no use site gives (one that an expansion hook of
a feature computes, or one written with a substitution argument); no definition written
in a document's settings can hold one. The rendering guide shows the form a call and a
definition take, and lists what is written expanded and why ([user definitions in the
recomposed LaTeX](crate::guide::rendering#user-definitions-in-the-recomposed-latex)).

### Attaching an aspect to someone else's element

[`FeatureBuilder::attach`](crate::core::registry::FeatureBuilder::attach) gives an
aspect to every element value whose element type has a given name, including other
features' elements and the language's structural elements:

```rust
use std::sync::Arc;

use flm_core::model::element::ElementSpec;
use flm_core::core::registry::{
    BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry,
};
use flm_core::lang::mint::{ElementDef, SyntaxDef};

// The aspect one feature wants every "box" to have.
trait Fillable: Send + Sync {
    fn fill(&self) -> &str;
}
struct Solid;
impl Fillable for Solid {
    fn fill(&self) -> &str { "solid" }
}

// The feature that owns the element, and does not depend on `Fillable`.
struct Shapes;
impl FlmFeature for Shapes {
    fn info(&self) -> FeatureInfo { FeatureInfo::new("shapes", "Shapes") }
    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        b.element(ElementDef::new(
            "shapes",
            ["shapebox"],
            SyntaxDef::Macro { args: Vec::new() },
            Arc::new(ElementSpec::new("shapes.box")),
        ))
    }
}

// The feature that gives the element behavior, and does not own it.
struct Filling;
impl FlmFeature for Filling {
    fn info(&self) -> FeatureInfo { FeatureInfo::new("filling", "Filling") }
    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        b.attach::<dyn Fillable>("shapes.box", Arc::new(Solid))
    }
}

let registry = build_registry([
    Arc::new(Shapes) as Arc<dyn FlmFeature>,
    Arc::new(Filling) as Arc<dyn FlmFeature>,
])?;

let element = registry.element_named("shapes.box").expect("declared above");
assert_eq!(element.aspect::<dyn Fillable>().map(|f| f.fill()), Some("solid"));
# Ok::<(), flm_core::core::registry::RegistryBuildError>(())
```

A feature gives behavior in this way to elements it does not own, and to the language's
structural elements, which no feature declares (`flm.text`, `flm.group`;
[structural elements](crate::lang::structural::StructuralElements)). The
`lowering` feature uses it to mark elements of the presentation vocabulary: it attaches
[`Decoration`](crate::stdlib::backends::pres::Decoration) to the three decoration
elements, [`OpaqueContent`](crate::stdlib::backends::pres::OpaqueContent) to the two
elements whose content is source text, and
[`ContentInOpaque`](crate::stdlib::backends::pres::ContentInOpaque) to
`flm.pres.math-text`; the lowering driver (the shared code of
[`LoweringStage`](crate::stdlib::backends::lowering::LoweringStage) that applies the
rules) recognizes those elements by their aspects,
not by their names.

Give the aspect as its **trait-object type** (`attach::<dyn Fillable>`): an aspect is
looked up by the trait it is requested as, and a concrete type fails to compile. Two
mistakes are registry build errors rather than silent successes: attaching to an element
type name that no feature declares, and attaching an aspect that an element already
carries.

## Tables and stages

A table is typed data that one stage writes beside the frozen trees and other stages
read; its identity is its registered dotted name, never its Rust type, and that name is
also a capability ([`Table`](crate::core::data::table::Table)). A frozen tree is a
document tree after the rewrite stages have run: it is never changed again, and
everything a later stage computes about it is stored in tables beside it, keyed by node
address ([frozen trees and computed
data](crate::guide::concepts_overview#frozen-trees-and-computed-data)).

To define a table, implement [`Table`](crate::core::data::table::Table) on its value
type. The only required method is [`absorb`](crate::core::data::table::Table::absorb),
which adds to the accumulated value a table piece (the part of a table that one stage
invocation produced) of the same table; the runner passes the pieces of a per-tree stage
in the run's order of the trees. Two methods have defaults:
[`project`](crate::core::data::table::Table::project) writes the value for dumps and
tests, and [`piece_class`](crate::core::data::table::Table::piece_class) says whether a
piece states a fact about the document as a whole, which [value
catch-up](crate::guide::concepts_overview#value-catch-up) needs to know.

A stage is one unit of work of the pipeline: it declares the capabilities it provides
and requires, the tables it reads and writes, its effect (compute, check, or
input/output) and its scope (once per tree, or once per document), and the plan decides
whether and when it runs ([`Stage`](crate::core::stage::Stage)). There are two kinds:

- A [`RewriteStage`](crate::core::stage::RewriteStage) runs *before* the trees are
  frozen and turns one tree into another. It reads no computed data, and it publishes
  the trees it produced in a table named after the capability it provides
  ([`TreesTable`](crate::core::stage::TreesTable)). The standard features provide four:
  two expansions of user definitions (the `userdefs` feature), one for the definitions
  expanded in every plan and one for the definitions that each plan expands or keeps;
  the insertion of included files (the `input` feature); and the layout of content in
  paragraphs and blocks (the `blocks` feature).
- A [`Stage`](crate::core::stage::Stage) runs *after* the trees are frozen. It reads the
  frozen trees and the tables it declared, and writes tables of its own.

A stage describes itself in two parts, at two different moments:

- Its **declaration** ([`StageDecl`](crate::core::stage::StageDecl)), returned by
  [`Stage::decl`](crate::core::stage::Stage::decl), is fixed when the feature registers
  the stage: its name; its [`Effect`](crate::core::stage::Effect) (it computes data,
  only reports diagnostics, or has an effect outside the computed data, such as handing
  an output's files to the program that writes them); its
  [`Scope`](crate::core::stage::Scope) (once per tree, or once for the whole document);
  the capabilities it provides; and the tables it writes.
- Its **needs** ([`Needs`](crate::core::stage::Needs)) are computed once per plan by
  [`Stage::needs`](crate::core::stage::Stage::needs), from the plan request: the
  capabilities it requires, the tables it reads (required or optional), the option types
  it reads, and its ordering edges. Most stages return a constant; a stage whose inputs
  depend on the plan request computes them there, as a backend's lowering stage does.

Declaring a table as written provides that table's capability, and declaring a table as
read requires it, so a stage's author lists the reads and writes and nothing else.

The `index` feature ([`index`](crate::stdlib::features::index)) is one table and one
stage: it declares one table and registers one `Compute` stage of `PerTree` scope that
requires nothing; the stage walks each frozen tree once and records which nodes carry
which element. The following example declares a table and a stage the same way:

```rust
use flm_core::core::stage::{Effect, Needs, Scope, StageDecl};
use flm_core::core::data::table::{Table, TableName};

// A table is any type that can absorb another piece of itself.
#[derive(Debug, Default)]
struct WordCount(usize);

impl Table for WordCount {
    fn absorb(&mut self, piece: WordCount) {
        self.0 += piece.0;
    }
}

const WORDS: TableName<WordCount> = TableName::new("example.words");

let decl = StageDecl::new("example.words.count", Effect::Compute, Scope::PerTree)
    .writes(WORDS)
    .docs("counts the words of each tree");
let needs = Needs::new().requires("flm.blocks.structured");

// Writing a table provides its capability, so nothing else has to be declared.
assert!(decl.provides.is_empty());
assert_eq!(needs.requires.len(), 1);
```

In the feature's `register` method, declare the table with
[`FeatureBuilder::table`](crate::core::registry::FeatureBuilder::table) (or with
[`table_named`](crate::core::registry::FeatureBuilder::table_named) when the name is
computed, as `flm.lowered.<backend>` is), and register the stage with
[`FeatureBuilder::stage`](crate::core::registry::FeatureBuilder::stage) or
[`FeatureBuilder::rewrite_stage`](crate::core::registry::FeatureBuilder::rewrite_stage).

A stage of an extension ([Extensions](#extensions)) reads the frozen trees through
traversals: `cx.walk()` and `node.descendants()` hand over the nodes one at a time, and
`cx.trees()` the trees. A stage that looks for the nodes of a few elements restricts its
traversal with `elements(names)`, so that the other nodes cost it nothing, and it reads
the rows of an extension's own table, `cx.get(name).ext.items()`, as a sequence
([Traversals and sequences](#traversals-and-sequences)).

A feature written in JavaScript ([Extensions](#extensions)) registers a rewrite stage
with `b.rewrite_stage(stage)`, where `stage` is an object with three methods: `decl()`
answers the stage's name and the capability it publishes (`new RewriteDecl(name,
publishes)`), `needs()` its ordering edges, and `restage(node, cx, rs)` decides what
becomes of one node. The script does not build the new tree itself: the library walks
the tree and calls `restage` once for each node it reaches. The handler answers
`Restage.Descend` to keep the node, whose children the library then visits in turn, or
`Restage.Emit([...])` with the nodes it created in the node's place through `rs`, the
*restager*: characters with `rs.stage_chars(text, like)`, a copy of a part of the tree
with `rs.restage_subtree(node)` (whose nodes go through `restage` again), a copy of a
macro call with new content in an argument with `rs.restage_argument_with_content` and
`rs.restage_invocation`. `rs.restage_subtree` and `rs.restage_children` return a
`StagedNodes` sequence, which the handler places in the array given to `Restage.Emit` as
it is ([Traversals and sequences](#traversals-and-sequences)). A handler that fails leaves its node as it was, with the Error
`flm.ext.handler-failed` at the node, and the rest of the tree is rewritten. An
operation after which the new tree cannot be built (for example the tree's root replaced
by two nodes) abandons the rewrite of that tree, with an Error at its root, and the tree
is absent from the output. The test extension `smartdash` (the folder
`flm-ext/tests/js/smartdash/` of the FLM repository) replaces `--` and `---` by dashes
outside mathematics and verbatim content, and sets its macro `\sdquote{…}` between
quotation marks; the documentation of the module `flm_ext::quickjs` describes every method
of `rs`.

An external table is a table that no stage of the run writes: the caller installs its
value when the run is constructed ([`Externals`](crate::core::run::Externals); declared
with [`external_table`](crate::core::registry::FeatureBuilder::external_table)). Data from
outside the processing of one document takes part in a plan in this way: the `refs`
feature declares one for the labels of the *other* documents of a
[corpus](crate::guide::concepts_overview#documents-fragments-and-the-corpus).

## Capabilities, collections, ordering and workflows

A capability is a registered dotted name for a state of processing that a stage brings
about, such as `flm.blocks.structured`: a stage declares the capabilities it provides and
the capabilities it requires, and a caller demands the capabilities it wants
([`CapabilityDef`](crate::core::registry::CapabilityDef)). To demand a capability is to
ask the plan for a stage that provides it ([`PlanRequest`](crate::core::plan::PlanRequest)).
Every table already declares its own capability, so a feature declares a capability with
[`FeatureBuilder::capability`](crate::core::registry::FeatureBuilder::capability) only
for a state that no table represents: a marker, the result of a check, or the parent of
refinements.

A capability may **refine** another, which means that it is a stronger form of it
([refinement](crate::guide::pipeline#refinement)):
`flm.blocks.structured` and `flm.blocks.raw` are two refinements of `flm.blocks`, so a
stage providing either satisfies a demand for `flm.blocks`, and a plan that demands both
is refused. At most one refinement of a capability may be marked
[`default`](crate::core::registry::CapabilityDef::default); a demand for the parent
alone selects it when nothing else decides.

A capability can carry what a plan error says when a plan needs it and no registered stage
provides it ([`unprovided`](crate::core::registry::CapabilityDef::unprovided)): the
condition in the words of the feature that declares the capability, with its fix when the
fix is not obvious. An extension gives the text as the third argument of `b.capability(name, docs,
unprovided)`, or `null` (`None` in Rust) for the generic text.

A **collection** ([`CollectionDef`](crate::core::registry::CollectionDef)) is a name for a
set of capabilities that any feature may add to; demanding the collection demands every
member. `flm.validated` is one. A feature that provides a check declares its own check
capability and adds it to the collection with
[`collection_member`](crate::core::registry::FeatureBuilder::collection_member). Every
workflow of the standard features then runs that check too: the `check` workflow demands
the collection and nothing else, and each rendering workflow demands it beside its
output. A collection is only demanded; no stage provides one. A member added to a
collection that no feature of the registry declares is dropped without a diagnostic, so
a feature that provides a check can be registered on its own.

An **ordering edge** says that a stage runs after, or before, the stage that provides
some capability. A stage ordinarily gets its place in the order from what it requires and
reads; edges exist for the case where one feature must place its stage within another
feature's order without needing that work's results. **An edge concerns order only**: it
never causes a stage to be scheduled, and it has no effect when the stage that provides
the capability is not scheduled.

There are two ways to declare an edge. A stage declares its own edges in its needs, with
[`Needs::after`](crate::core::stage::Needs::after) and
[`Needs::before`](crate::core::stage::Needs::before); the block-structure rewrite does
so, adding an edge after the expansion of user definitions only when the registry
declares that capability. An [`OrderingDef`](crate::core::registry::OrderingDef),
registered with [`FeatureBuilder::ordering`](crate::core::registry::FeatureBuilder::ordering),
declares an edge from outside: any feature may contribute edges on any registered stage.
A feature orders a stage it does not own in this way.

A **workflow** ([`WorkflowDef`](crate::core::registry::WorkflowDef)) is a named set of
demands together with the choices that go with them: which outputs to produce, which
other capabilities to demand, which stages and lowering rules to prefer, which elements
to accept as unrenderable, and which render option values to set. A workflow is data held
in the registry, so a caller chooses one by name instead of writing a plan request by
hand. A workflow may extend another, and inherits the fields it does not declare.

The `flm` program and its host library `flm-host` choose a workflow through a
*profile*, a name given with the option `-p` or the front matter's `default_profile`:
the profile `NAME` runs the workflow `NAME` (`flm render -p text` runs the workflow
`text`). A workflow that an extension declares is therefore run by its name as the
profile, once the document uses the extension. An extension named `profile-NAME`
needs no such listing: the profile `NAME` alone loads it, after the document's other
packages, and an extension of that name must declare the workflow `NAME`. A workflow can
so come with the packages it needs, listed under `use` in the extension's manifest, and
with its own settings, in the workflow's `settings`, which apply only when the workflow
runs:

```yaml
# _flmextensions/profile-draft.yaml
flm:
  use: [mystyle]
  workflows:
    draft:
      extends: html
      settings:
        html: {heading_tags: {section: h3}}
```

`flm render -p draft paper.flm` then uses `mystyle` and runs `draft`; a command with
another profile uses neither the extension `profile-draft` nor `mystyle`. A feature of a
scripted extension `profile-NAME` may name what it declares after the profile as well as
after the extension's stem ([Extensions](#extensions)): its output `NAME`, its tables and
stages `NAME.SOMETHING`, so that the output, like the workflow, carries the profile's
name. The guide of the `flm` program describes profiles in full
([Profiles and workflows](crate::guide::command_line#profiles-and-workflows)).

## Lowering rules

Lowering rewrites each frozen tree into a presentation tree for one backend, by applying
the lowering rule selected for each element, in rounds, until only elements the backend
writes natively remain; the result is computed data in the table `flm.lowered.<backend>`
([backends, lowering and
outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)). A lowering rule
is a named registry entity written for one element: it declares what it requires, reads
and produces, and implements `Lower`, which stages the element's presentation for one
backend ([`LoweringRule`](crate::core::lowering::LoweringRule)). To stage a node is to
build it into the tree that a lowering rule or a rewrite hook is producing, through the
context the rule or hook is handed; the staged nodes exist in that tree only
([`Lowerer`](crate::core::lowering::Lowerer)).

A feature registers a rule with
[`FeatureBuilder::lowering_rule`](crate::core::registry::FeatureBuilder::lowering_rule).
A [`LoweringRule`](crate::core::lowering::LoweringRule) holds:

- a name;
- the element it lowers;
- a [`LoweringDecl`](crate::core::lowering::LoweringDecl), which says what the rule
  needs and which presentation elements it may build;
- the [`Lower`](crate::core::lowering::Lower) implementation;
- a [`DefaultMark`](crate::core::lowering::DefaultMark), which says on which backends the
  rule is chosen when nothing else decides.

A rule is written for an element, not for a backend, so it is written once and used by
every backend whose plan selects it. Where an output format needs something more
specific, a second rule for the same element is registered with
[`DefaultMark::OnBackends`](crate::core::lowering::DefaultMark::OnBackends) for that
backend, and the plan selects it there. A rule that a caller must ask for by name is
registered with [`DefaultMark::Never`](crate::core::lowering::DefaultMark::Never): the
`userdefs` feature's `instantiate-at-lowering` rule is one, an alternative to two default
rules, which a plan request selects with
[`LoweringSelection::prefer`](crate::core::plan::LoweringSelection::prefer)
([`userdefs::kept`](crate::stdlib::features::userdefs::kept)). Lowering rule selection
chooses one rule per element and backend in a fixed order: the rule the request prefers
by name, else the backend's native emission, else a rule marked default on that backend,
else a rule marked default everywhere, else the sole candidate
([`SelectedRules`](crate::core::plan::SelectedRules)).

The declaration lets a rule take part in a plan without the rule being called: plan
construction reads it. The capabilities the rule requires, the tables it reads and the
option types it reads are added to the needs of its backend's lowering stage, so a rule
that reads the table of resolved references causes the stage that writes that table to
be scheduled. The presentation elements the rule declares it produces are checked
against what it stages: building an element it did not declare is an error
([`LowerError::UndeclaredProduces`](crate::core::lowering::LowerError::UndeclaredProduces)).

A rule whose output nothing checks before the program that reads it says so in its
declaration, per backend, with what it writes and what reads it
([`unchecked_output`](crate::core::lowering::LoweringDecl::unchecked_output)): a plan
that selects the rule on that backend keeps one warning per backend and feature, which
every run of the plan reports at its start as `flm.run.unchecked-output`. The rules of
`math-passthrough` declare it for their formulas on `html`, `latex-rendered` and
`latex-recomposed`, since nothing reads the formulas before the formula renderer or LaTeX
does. The declaration is fixed when the rule is registered, so
the warning depends on the plan alone, not on what a document holds.

A table read with [`reads_opt`](crate::core::lowering::LoweringDecl::reads_opt) is read
only if the run holds it, and the rule then works without the feature that owns the
table. The backend's lowering stage turns such a read into a required read whenever the
registry declares the table and some stage writes it, so that the stage writing it is
scheduled. The read stays optional for a table that no stage writes (an external table,
which the caller installs), and it is left out of the stage's needs for a table that no
feature of the registry declares (a peer declaration that resolved to nothing, described
below). In both of these cases the rule reads `None` when the run does not hold the
table.

A lowering rule of an extension works through the same lowerer. The lowerer's methods
that lower content (`lower_children`, `lower_body`, `lower_arg_named`, `lower_nodes`, …)
return the staged nodes as a sequence, which the rule passes on to `pres`, to a
presentation tree or to `Lowering.Emit` as it is, alone or joined with other staged
nodes, without reading the staged nodes one by one ([Traversals and
sequences](#traversals-and-sequences)).

### Peer declarations

A rule registered for one backend often refers to things that its feature does not
register: the backend it is the default on; presentation elements that belong to that
backend's family (the `headings` feature's rule for the `latex-recomposed` backend stages
the LaTeX family's macro construct); and sometimes a table another feature computes (the
same rule reads the table of safe labels
[`flm.labels.safe`](crate::stdlib::features::refs::SAFE_LABELS) to write the safe label
of each of the heading's labels). The registry build refuses a reference to anything that
no feature declares, and the feature must not depend on the backend's feature, or a host
that renders plain text only
would have to register the LaTeX features too.

The feature therefore makes a **peer declaration** of each. A peer declaration is a
feature's forward declaration of an element, element type, table, service slot, scoped
package or backend that another feature owns, with the element's payload type or the
table's value type as the signature; the registry build resolves it after every feature
has registered, and a lowering rule that depends on a name nobody declares is set aside
(excluded from rule selection, with one build Note)
([`PeerName`](crate::core::registry::PeerName)). A peer declaration registers nothing,
and it counts only for the feature that makes it. There are six forms:

- [`peer_backend`](crate::core::registry::FeatureBuilder::peer_backend) declares a
  backend by name;
- [`peer_element`](crate::core::registry::FeatureBuilder::peer_element) declares a
  presentation element by name, with its payload type as the signature;
- [`peer_table`](crate::core::registry::FeatureBuilder::peer_table) declares a table by
  name, with its value type as the signature. A peer table is another feature's table,
  computed by that feature's stage; it differs from an external table, which the caller
  installs;
- [`peer_slot`](crate::core::registry::FeatureBuilder::peer_slot) contributes a value to
  a service slot that another feature owns (see [Services and service
  slots](#services-and-service-slots));
- [`peer_scoped_package`](crate::core::registry::FeatureBuilder::peer_scoped_package)
  declares a scoped package that this feature's bodies and arguments refer to (see
  [Scoped packages](#scoped-packages));
- [`peer_element_value`](crate::core::registry::FeatureBuilder::peer_element_value)
  declares one more value, with the commands that produce it, of an element type that
  another feature declares: for example a float type of your own, of the element type
  that the `floats` feature declares and lowers. The declaration is kept where some
  feature declares an element of that type name in any way (with
  [`element`](crate::core::registry::FeatureBuilder::element), inside a scoped package,
  as a fallback, a presentation element or a field). Where none does, the declaration is
  dropped with one Note: its commands are unknown commands, so no node of that element
  exists, and no plan is refused because no rule lowers it.

When the registry is built, every peer declaration is resolved against what the features
registered. A name that some feature declares resolves: an element's payload type and a
table's value type are checked, and a mismatch is
[`BuildError::PeerElementMismatch`](crate::core::registry::BuildError::PeerElementMismatch)
or [`BuildError::PeerTableMismatch`](crate::core::registry::BuildError::PeerTableMismatch);
the rule then takes part like any other. A name that no feature declares leaves the
declaration unresolved: the build succeeds, and one Note
([`UnresolvedPeer`](crate::core::registry::UnresolvedPeer)) joins the registry's build
diagnostics. A rule that *depends* on the unresolved name is then **set aside**: it is
excluded from rule selection and from the check that every element can be lowered, in
that registry; a registry built with the missing feature includes the rule. A rule depends on the backend it is
the default on, on every element it produces, and on every table it reads with
[`reads`](crate::core::lowering::LoweringDecl::reads). A table read with
[`reads_opt`](crate::core::lowering::LoweringDecl::reads_opt) is the exception: the rule
runs and reads the table as absent. A rule uses such a read to write what it can without
the peer feature: the heading rule reads the anchors table in this way, so in a registry
without the `refs` feature, headings are printed without anchors. With a required read,
the rule would be set aside, and headings would have no rule on any backend.

A stage of the feature may also *write* a peer table: the peer feature declares the
table, and this feature's stage writes it. The `graphics` feature's publish stage writes
the copies of images into an output's artifact table, which the backend declares. A stage
that writes an unresolved peer table is not registered at all, since it would have no
table to write and the feature that reads the table is absent; the Note gives the stage's
name.

The frozen registry lists the peer declarations with their outcome
([`peer_backends`](crate::core::registry::FlmRegistry::peer_backends),
[`peer_elements`](crate::core::registry::FlmRegistry::peer_elements),
[`peer_tables`](crate::core::registry::FlmRegistry::peer_tables),
[`peer_slots`](crate::core::registry::FlmRegistry::peer_slots),
[`peer_scoped_packages`](crate::core::registry::FlmRegistry::peer_scoped_packages),
[`peer_element_values`](crate::core::registry::FlmRegistry::peer_element_values)) and the
rules set aside ([`set_aside_rules`](crate::core::registry::FlmRegistry::set_aside_rules)),
so a misspelled name can be found on any registry that holds the feature. The `headings`
feature's [`latex::register`](crate::stdlib::features::headings::latex::register) shows
the usual set of peer declarations for a rule on the recomposed LaTeX.

### Presentation elements of your own

A **presentation element** is an element of the trees that lowering produces, which a
backend writes natively or lowers further; the shared [presentation
vocabulary](crate::stdlib::backends::pres) is the set the standard backends write. A
feature declares a presentation element of its own with
[`presentation_element`](crate::core::registry::FeatureBuilder::presentation_element),
which takes the element's name and its payload type and returns the element value your
rules build nodes of. A feature needs one only when no element of the shared vocabulary
can carry what its element means; most features need only a lowering rule.

A backend writes such an element natively, or a rule lowers it further, in another round
of lowering. An element lowered on each backend by its own rules carries what the feature
computed from one rule to the next, and leaves each backend's own way of writing it to a
rule of that backend: the `math-techxt` extension's rules of a formula, on `text` and
`html`, stage its element `math-techxt.rendered-as-text`, the formula's rendered lines
with each text command's content in a content slot; a second rule per backend, marked as
the default on that backend alone, writes the element in that backend's elements: the
shared vocabulary's lines and verbatim atoms on `text`, `<span>` elements with a
stylesheet of the extension's own on `html`. No backend writes the element natively, and
the plan of a backend without such a rule never stages it.

A feature written in JavaScript ([Extensions](#extensions)) declares a presentation
element with `b.presentation_element(name, docs)`. The payload of every such element is
data: a rule gives any data value as the payload when it stages the node,
`lw.pres(cx, element, { kind: "warning" }, children)` (the rule lists the element among
the elements it produces), and a stage reading the lowered trees gets the value back with
`node.payload()`. Only a backend that lists the element in its native set receives it, so
the feature registers two rules for the element of the document that the new element
presents: one marked as the default on the backend that writes the new element
(`DefaultMark.OnBackends([backend])`), staging it; and one marked as the default
everywhere, lowering the element into the shared vocabulary for every other backend.

### Format-native output: the construct elements

A construct element is a presentation element that mirrors one fundamental construct of
an output format (an HTML tag; a LaTeX macro call, environment, raw text or definition),
so that format-specific output is structured data in the lowered tree rather than a
string ([backends, lowering and
outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)). A rule stages
one where it must produce something that an output format has and the shared vocabulary
does not. Only the backends of the construct's own format write it natively, and it is
not part of the shared vocabulary, so a rule that stages one is a rule for that format
and is registered as the default on that format's backend.

The LaTeX family ([`latex::construct`](crate::stdlib::backends::latex::construct),
registered by the `latex` feature) has four construct elements: a macro call, an
environment, raw text and a definition. The HTML backend
([`html::construct`](crate::stdlib::backends::html::construct), registered by the `html`
feature) has one, `flm.pres.html.tag`, whose payload
([`HtmlTagPayload`](crate::stdlib::backends::html::HtmlTagPayload)) holds one tag: its
name; its attributes in the order they are written; its content, which is either the
node's own content slot or a string of already-formed HTML
([`TagBody`](crate::stdlib::backends::html::TagBody)); and whether the tag is
block-level, which decides the line breaks the emitter writes around it.

A tag construct is outside the HTML contract (the classes and attributes the emitter
derives from the presentation vocabulary; [the HTML
contract](crate::guide::rendering#the-html-contract)), and outside the policy that
decides which addresses a link or an image may carry: the rule that stages the tag writes
its own classes, attributes and addresses, and is responsible for them. Where the tag's
content is already-formed HTML, the rule's author creates it with
[`Markup::trusted`](crate::stdlib::backends::html::Markup::trusted) and accepts the
requirement stated there: the bytes are HTML that is safe to place in a page, and
anything that came from an input the author does not control is sanitized first. Outside
the library, bytes reach a page without being escaped in two ways only: through that
constructor, and through
[`HtmlSink::raw_text_element`](crate::stdlib::backends::html::HtmlSink::raw_text_element),
which writes the content of a `<style>` or a `<script>`.

A feature that stages a construct element registers neither the element nor the backend
it writes for: it makes a peer declaration of both (see [Peer
declarations](#peer-declarations)), so that it builds in a registry that does not hold
that backend, with its rule set aside.

### Adding an output format

A backend is the registration bundle for one output format: the elements its emitter
writes natively, a lowering stage, an emit stage and a final stage
([`BackendDef`](crate::core::registry::BackendDef)). A feature registers the four
together with [`FeatureBuilder::backend`](crate::core::registry::FeatureBuilder::backend),
so that a plan recognizes the three stages as one backend's.

The lowering stage is not written from scratch: create an instance of the shared
[`LoweringStage`](crate::stdlib::backends::lowering::LoweringStage) for the backend's
name, and declare the table `flm.lowered.<backend>` that it writes with
[`table_named`](crate::core::registry::FeatureBuilder::table_named) under the name
[`lowered_table_name`](crate::stdlib::backends::lowering::lowered_table_name) returns.
What is left to write is the emitter and the final stage. 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.

The native set must satisfy every **native-set implication** the registry holds: a
declared requirement on what a backend's native set must contain, checked against every
backend when the registry is built
([`NativeImplication`](crate::core::registry::NativeImplication)). The lowering driver
(the shared code of [`LoweringStage`](crate::stdlib::backends::lowering::LoweringStage)
that applies the rules) stages two elements by itself, without any rule declaring them, so no chain of
rules leads to them and plan construction cannot see that a backend needs them. The
`lowering` feature therefore declares two implications
([`native_implications`](crate::stdlib::backends::lowering::native_implications)):

- every backend must write `flm.pres.unsupported` natively, the stand-in for an element
  the backend cannot render or for a rule that failed;
- a backend that writes natively any element carrying the
  [`Decoration`](crate::stdlib::backends::pres::Decoration) aspect must write
  `flm.pres.deco-mark` natively, the mark left where a decoration was moved out of a
  content run ([decorations, roles and
  kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)).

A native set that misses one fails the build with
[`BuildError::NativeSetIncomplete`](crate::core::registry::BuildError::NativeSetIncomplete),
which gives the backend, the element it must write natively and the native element that
caused the requirement. A feature whose own code stages an element without declaring it
declares an implication of its own with
[`native_implication`](crate::core::registry::FeatureBuilder::native_implication).

An [`OutputDef`](crate::core::registry::OutputDef), registered with
[`FeatureBuilder::output`](crate::core::registry::FeatureBuilder::output), then gives the
format a name that a caller can ask for. It holds the capability a plan must reach, the
table that holds the output's artifact set, and the media type and file extension of the
entry artifact. An artifact is one file's worth of output held as a value (a folder
artifact holds the files of a folder), identified by its producer and a name and never by
a path; an artifact set is the artifacts of one
output, at most one of which is the entry artifact, the one that stands for the output as
a whole ([`ArtifactSet`](crate::core::artifact::ArtifactSet)). A
[`WorkflowDef`](crate::core::registry::WorkflowDef) that lists the output makes it
available by name. The `text` backend
([`TextBackend`](crate::stdlib::backends::text::TextBackend)) does all of this in one
`register` method.

A backend's feature registers the rules that are its own (the `latex-recomposed` backend
registers two, for paragraphs and paragraph breaks) and no rule for another feature's
elements. A feature that wants its element written in the new format ships the rule
itself, with peer declarations of the backend and of the format's presentation elements
(see [Peer declarations](#peer-declarations)). The backend therefore depends on no content
feature, and an absent content feature contributes no rule. An element that no rule
lowers makes plan construction fail, unless the plan request accepts it as unrenderable:
an accepted unrenderable element is an element the plan request lists, per backend, as
one the backend need not render; the plan builds anyway, and each occurrence lowers to a
childless `flm.pres.unsupported` node with one Error diagnostic
([`PlanRequest`](crate::core::plan::PlanRequest)).

**An output made of regions.** An output region is one named part of an output's entry
artifact (the document's content; each piece, a document-level value a backend places
beside the content ([`Piece`](crate::core::piece::Piece)); and on HTML the stylesheets, the scripts, the title and the language), which the backend writes once into
the table `flm.output.<backend>.regions` ([`Regions`](crate::core::region::Regions)). A
backend whose entry artifact a host may want to assemble in another way, through a
template, splits its final work in two, as the four standard backends do:

- a stage `flm.<backend>.regions` writes the output's regions into the table
  `flm.output.<backend>.regions`;
- the backend's final stage assembles the entry artifact from those regions, in a layout
  of the backend's own ([output regions and the final
  stage](crate::guide::concepts_overview#output-regions-and-the-final-stage)).

The backend then contributes a [`RegionsOutput`](crate::core::region::RegionsOutput) to
the service slot `flm.output.regions`
([`REGIONS_SLOT`](crate::stdlib::backends::lowering::REGIONS_SLOT)): the output's name,
its tables, and the capability its final stage provides. A host's own assembler reads
that service slot and serves the output without code of its own for it. The files written
beside the entry artifact are in the tables that the `RegionsOutput` lists: a table of
the backend's own for its own files (the recomposed LaTeX's style file), and the output's
artifact table `flm.output.<backend>.artifacts`, which only the `graphics` feature's
publish stage writes. The final stage adds them to the artifact set with
[`ArtifactSet::insert_entry_with`](crate::core::artifact::ArtifactSet::insert_entry_with),
which reports a malformed set.

**An output made from the files of another output.** Some outputs are made by processing
the files of another output instead of the document: an output of PDF files, for
instance, is made by running LaTeX over the files of the `latex-rendered` output. Such an
output needs no backend. Its feature registers a table of type
[`ArtifactSet`](crate::core::artifact::ArtifactSet), the output, and a stage that reads
the other output's table (it declares the read among its
[`Needs`](crate::core::stage::Needs), which makes the plan schedule the stages that write
that table) and writes the output's artifact set. The output's declaration lists the other
output with [`OutputDef::made_from`](crate::core::registry::OutputDef::made_from). A host
reads that list before any plan is built, to prepare those outputs as well: the `flm`
program sets up the compose template of each output in the list, so the compose template
chosen for `latex-rendered` assembles the LaTeX that the PDF is made from. The registry
build refuses a name in the list that no feature declares as an output.

The stage writes the files of the other output where it needs them (into a folder where
it runs a program, for instance) at the paths the host would write them at, so that the
links between the files hold: a LaTeX document loads its style file and includes its
images by those paths. [`path_of`](crate::core::artifact::path_of) gives the path of
each artifact: its [fixed path](crate::core::artifact::Artifact::fixed_path) when it has
one, else the path that the host's naming of files gives it (the
[`ArtifactNamer`](crate::core::artifact::ArtifactNamer) that the host contributes to the
service slot `flm.artifacts.namer`,
[`NAMER_SLOT`](crate::stdlib::backends::lowering::NAMER_SLOT), read for a scope built with
[`NamingScope::of`](crate::core::artifact::NamingScope::of) over the registry and the
plan's demands). The output's declaration, passed to `path_of`, gives an entry artifact
the extension of the output's entry file.

**A backend written in JavaScript.** A feature written in JavaScript
([Extensions](#extensions)) registers a backend and an output through the same
builder methods, `b.backend(new BackendDef(name, native, lowering, emit, final_stage))`
and `b.output(new OutputDef(name, capability, table, media_type, extension))`. The name
of such a backend, and of its output, is the extension's stem itself or begins with the
stem and a dot, since a reader types it on the command line (`-f typst`); an extension
whose stem is `profile-NAME` may also use `NAME` in place of its stem. The three stages:

- the lowering stage is the library's: `new LoweringStage(backend)`, whose table the
  feature declares with `b.table_named(lowered_table_name(backend),
  StandardTable.LoweredTrees, docs)`;
- the emit stage is a stage object, as `b.stage` takes one: it reads the lowered trees
  by the table's name (`cx.get(name).lowered`, whose `tree(id)` answers a tree), walks
  the nodes of each from its `root()` (`element_name()`, `payload()`, `body()`,
  `children()`, `slot_count()`, `slot_content_nodes(index)`) and pushes the text it
  writes into a table of the extension's own;
- the final stage is a stage object that reads that text and pushes the artifact set
  into a table declared with `b.table_named(name, StandardTable.ArtifactSet, docs)`:
  each artifact is written as data, `Artifact.bytes(new ArtifactId(owner, name),
  media_type, content).as_entry()` for the entry artifact or `Artifact.folder(id, [[path,
  content], …])` for a folder artifact.

**The content of a file, as data.** An extension gives the bytes of a file, the
`content` above, in one of three forms: a text or `{ text: TEXT }`, for bytes that are
UTF-8 text (the bytes of the text), or `{ base64: TEXT }`, for bytes of any kind, written
in base64 with the standard alphabet and padding (an image, a PDF file). When an
extension reads a file, its content is `{ text }` when the bytes are UTF-8 and `{ base64
}` otherwise. The host service `programs` (see [Host services](#host-services)) takes the
files it writes for a program, and gives back the files it collects, in the same two
forms, so an extension passes a file between an artifact and a program without
converting it. The host service `cache` takes and gives back the blobs of a value in the
same two forms (see [Caches of an extension](#caches-of-an-extension)).

**Reading the files of an output from an extension.** A stage of an extension that
declares a read of a table of type `ArtifactSet` (the table of another output, such as
`flm.output.latex-rendered.document`) gets the output's files as data:
`cx.get(name).projection` is `{ artifacts, violations }`. `artifacts` holds every artifact
of the set, ordered by identity, each as a map of seven fields: `id`, `media_type`,
`entry`, `data` (each content `{ text }` or `{ base64 }`), `fixed_path`, `refs` and
`extension` (the class `Artifact` writes five of them, without `fixed_path` and `refs`).
Each map has one more field, `path`: the path at which the host writes the file, relative
to the output's folder,
computed as [`path_of`](crate::core::artifact::path_of) computes it (a folder artifact's
files go under it, each at `path/FILE`); `null` when the file has no fixed path and the
host contributes no naming of files. Writing each file at its `path` keeps the links
between the files intact. `violations` holds the text of each problem recorded in the set
(two files of one identity, two main files). An artifact read can be pushed into another
table of files as it is: a push ignores `path`. The output made from these files lists
the output it reads with `new OutputDef(…).made_from(name)` (see the paragraph on outputs
made from another output's files above).

The native set lists the elements the emit stage writes: the presentation vocabulary
(`ALL` of `flm:stdlib/backends/pres`), the structural elements the lowered trees keep
(six of the names of `flm:lang/structural`, `TEXT`, `GROUP`, `OPAQUE_WRAPPER`, `COMMENT`,
`CONTAINER` and `PARBREAK`: a run of characters, a group, a group holding content kept as
typed, a comment, a list of nodes, a paragraph break),
and the extension's own presentation elements. The backend
covers, by its native set or by its rules, every element the documents it serves can
hold. The standard features register some of their rules for their own backends only (the
`graphics` feature's rule for `flm.graphics.image`), so a backend written in JavaScript
registers a rule of its own for such an element, which may stage the stand-in
`flm.pres.unsupported`; an element no rule brings into the native set makes plan
construction fail. A workflow written in the package's `flm` block that lists the output
(`flm: { workflows: { typst: { outputs: ["typst"], demands: ["flm.validated"] } } }`)
makes it available by name, so that the `flm` program renders a document with `-p typst`. The emit stage must escape every character that the output's syntax
reserves, in link addresses and verbatim content as well as in text.

The test extension `typst` (the folder `flm-ext/tests/js/typst/` of the FLM repository)
writes a document as Typst markup this way: the library's lowering stage, an emit stage
in its own module `emit.js`, a final stage writing one entry artifact with the media type
`application/x-typst`, the output `typst` with the extension `typ`, the workflow `typst`,
a presentation element of its own for its macro `\tcallout[kind]{text}`, and a rule that
lowers an image to the stand-in. Its registration, abridged:

```js
const lowered = lowered_table_name("typst");                       // "flm.lowered.typst"
b.table_named(lowered, StandardTable.LoweredTrees, "the lowered trees");
b.table("typst.output", "the document as Typst markup");
b.table_named("typst.document", StandardTable.ArtifactSet, "the Typst file");
const emitStage = {
  decl: () => new StageDecl("typst.emit", Effect.Compute, Scope.Document).writes("typst.output"),
  needs: () => new Needs().reads(lowered),
  run(cx, out) { out.table("typst.output").push(emit(cx, cx.get(lowered).lowered)); },
};
const finalStage = {
  decl: () => new StageDecl("typst.final", Effect.Compute, Scope.Document).writes("typst.document"),
  needs: () => new Needs().reads("typst.output"),
  run(cx, out) {
    const [text] = cx.get("typst.output")?.ext.items() ?? [];
    if (text !== undefined)
      out.table("typst.document").push(
        Artifact.bytes(new ArtifactId("typst", "document"), "application/x-typst", text).as_entry());
  },
};
b.backend(new BackendDef("typst", [...ALL, TEXT, GROUP, OPAQUE_WRAPPER, COMMENT, CONTAINER, PARBREAK, "typst.pres.callout"],
                         new LoweringStage("typst"), emitStage, finalStage));
b.output(new OutputDef("typst", "typst.document", "typst.document", "application/x-typst", "typ"));
```

Such an output is made of no regions and contributes no
[`RegionsOutput`](crate::core::region::RegionsOutput), so a compose template cannot
assemble it; and the library's pieces stage does not run for it, so the text of a
document's footnotes, which the standard backends place as pieces beside the content, is
not written into it (the footnote marks are).

### Templates and template engines

The library's feature [`compose`](crate::stdlib::features::compose) assembles each
output made of regions through a **compose template**: a text with named places for an
output's regions, chosen by name (the `flm` program's option `-t`). The feature is not
among the standard features that [`stdlib::add_features`](crate::stdlib::add_features)
adds: a host that wants it registers it, as the `flm` program's
host library `flm-host` does in its package `std`. It declares two service slots, and a
feature of any package contributes to them as the package `std` does:

- `flm.compose.templates` ([`TEMPLATES_SLOT`](crate::stdlib::features::compose::TEMPLATES_SLOT))
  takes the templates ([`Template`](crate::stdlib::features::compose::Template)). A template holds its name, the output it
  serves, its engine, its text, the pieces it accepts (every piece, or a list of names:
  the pieces the render then builds for that output), the pieces it requires (a plan in
  which no stage provides one fails), its own settings with their defaults, the files
  it ships beside the output's main file
  ([`TemplateArtifact`](crate::stdlib::features::compose::TemplateArtifact)), and the
  place of its text, the qualified path of the file the text was read from
  ([`Template::source`](crate::stdlib::features::compose::Template::source); see below).
- `flm.compose.engines` ([`ENGINES_SLOT`](crate::stdlib::features::compose::ENGINES_SLOT))
  takes the template engines, each a value that implements
  [`TemplateEngine`](crate::stdlib::features::compose::TemplateEngine). The feature
  contributes `content-only`, which places the content and the pieces with nothing
  around them; `std` contributes `minijinja`.

A template reads the regions by name, the pieces by name with their words and their
place, the document's metadata, its own settings, and the path of each file it ships
(`artifacts`, a map from the file's name to the path the host's naming service gives,
relative to the folder of the main file)
([`TemplateContext`](crate::stdlib::features::compose::TemplateContext) lists them). A
feature contributes to the two slots as a peer
([`FeatureBuilder::peer_slot`](crate::core::registry::FeatureBuilder::peer_slot)), so
that its registry still builds where `compose` is switched off. An extension ships
compose templates as files (see [Extensions](#extensions)).

**The settings of a template.** A template declares its own settings as a JSON Schema of
an object
([`Template::settings`](crate::stdlib::features::compose::Template::settings)): each
property is one setting, with its type, its description, its default and its marks
([`Mark`](crate::core::settings::Mark), written under `x-flm-marks`; see [Settings given
as data](#settings-given-as-data)). The defaults are also given as the map
[`Template::config`](crate::stdlib::features::compose::Template::config). A document
writes the settings under `compose.template_config.OUTPUT.NAME`, and the feature
`compose` marks the three levels `template_config`, `OUTPUT` and `NAME` with
`merge-object-key-values`, so that the sources are combined key by key. The schema of a
setting belongs to the feature that contributes the template, not to `compose`: that
feature's settings declaration declares the schema as the entry
`template_config.OUTPUT.NAME` of the feature `compose`, with
[`compose::declare_settings`](crate::stdlib::features::compose::declare_settings) for a
list of templates, or
[`compose::declare_template_settings`](crate::stdlib::features::compose::declare_template_settings)
for a template known by its output and its name before it is made. The cascade then combines
each written value by the marks of that schema, and leaves out a key that the schema does
not declare, with a warning
([`WarningKind::UndeclaredKey`](crate::core::settings::cascade::WarningKind::UndeclaredKey);
the `flm` program reports it as `flm.host.unknown-setting`). The marks of a schema given as data are described in
[Settings given as data](#settings-given-as-data).

**Shipped files and folders.** A template ships two kinds of
[`TemplateArtifact`](crate::stdlib::features::compose::TemplateArtifact):

- [`File`](crate::stdlib::features::compose::TemplateArtifact::File): one file, with its
  name, its extension, its media type, whether it is itself applied as a template (filled
  in with the same values as the main file, through
  [`TemplateEngine::render_text`](crate::stdlib::features::compose::TemplateEngine::render_text)),
  and its bytes;
- [`Folder`](crate::stdlib::features::compose::TemplateArtifact::Folder): a whole folder,
  with its name and its files, each by its path relative to the folder and its bytes. It
  is never applied as a template.

The composer turns each into one artifact `compose:NAME`. A folder becomes a *folder
artifact*: an [`Artifact`](crate::core::artifact::Artifact) whose data is
[`ArtifactData::Files`](crate::core::artifact::ArtifactData::Files), named by the host's
naming service as a folder
([`ArtifactRef::folder`](crate::core::artifact::ArtifactRef::folder)); the template reads
the folder's path, with no `/` at its end, in `artifacts`. A host that writes the files
writes each file of the folder under that path (see [Outputs and
artifacts](crate::guide::rendering#outputs-and-artifacts) in the rendering guide).
[`Template::from_data`](crate::stdlib::features::compose::Template::from_data) makes a
template from its description written as data, whose keys `name` and `output` give the
template's name and the output it serves. It reads the template's files through
three functions its caller gives, so that this library reads no file itself: one for the
file of the template's text (the description's key `main`), one for a file the
description lists under `artifacts` (`file`), and one for a folder listed there (`dir`).
Each function receives the path as the description writes it, relative to the folder of
the description; a fourth function gives the place of each file read, its qualified
path.

**Files chosen when a template is applied.** The composer takes the list of the files a
template ships from the template's engine:
[`TemplateEngine::artifacts`](crate::stdlib::features::compose::TemplateEngine::artifacts)
is called once each time the template is applied, before the composer names the files,
with the context's values (`artifacts` still empty, since no file is named yet). Its
default answers the template's own list, which is what `content-only` and the `flm`
program's `minijinja` do. An engine whose templates choose their files when they are
applied answers them there, for example a stylesheet computed from the template's
settings: the composer names and ships the files in the order given, and `render`
receives their paths in `artifacts`. An `Err` fails the template as a failure of
`render` does (`flm.compose.template-failed`), and the output is not made.

**Files shipped while a template is applied.** A template engine may also ship a file
that the template's text selects as the template is applied, for instance a font or an
image whose path is a setting of the template. The composer gives the engine a handle for
this, a value implementing
[`TemplateShipper`](crate::stdlib::features::compose::TemplateShipper), as the third
argument of
[`TemplateEngine::render`](crate::stdlib::features::compose::TemplateEngine::render) and
of [`TemplateEngine::render_text`](crate::stdlib::features::compose::TemplateEngine::render_text).
The engine calls
[`ship`](crate::stdlib::features::compose::TemplateShipper::ship) with a
[`ShippedFile`](crate::stdlib::features::compose::ShippedFile) (the stem of the file's
name, its extension, its media type and its bytes), and writes the path that `ship`
returns, relative to the folder of the main file, as it writes a path of `artifacts`.

- The composer makes one handle for each application of a template, and passes it to
  every call of that application.
- The file's identity is `compose:<stem>-<digest>`, the digest being eight hexadecimal
  digits computed over the file's bytes and its media type. Shipping the same file again
  returns the same path and adds nothing, so an engine may ship a file on each call.
- Once the template is applied, the composer adds the shipped files to the output's
  artifact set, after the files of the template's own list, in the order in which they
  were first shipped.
- Where no package in use provides a naming service for files (the slot
  `flm.artifacts.namer`), `ship` returns an `Err`, and the template fails as a failure of
  `render` does.

The handle is an [`Arc`](std::sync::Arc), so that an engine can keep a clone of it inside
a function of its template language that must own what it holds. An engine that ships
nothing ignores the argument, as `content-only` does. The engine `minijinja` of the
`flm` program ships a file through it with its function `include_artifact_url` (see [Compose
templates](crate::guide::command_line#compose-templates) in the command-line guide).

**Files a template includes.** A template's text may be built from other files when it
is applied. For instance, the engine `minijinja` of the `flm` program offers the
statement `include`, which applies another file as a template with the same values, and
the functions `include_raw`, `include` and `include_artifact_url`, which read a file by
a path with its root (`self:`, `ext+NAME:`, `std:`, `doc:`, `cwd:`, or an address
`https://…` for `include_raw` and `include_artifact_url`), or by a bare path relative to
the file that writes it ([Paths with a root](crate::guide::command_line#paths-with-a-root)
in the command-line guide). Each text carries its *place*, the
qualified path of the file it was read from:
[`Template::source`](crate::stdlib::features::compose::Template::source) for the
template's text, the field `source` of
[`TemplateArtifact::File`](crate::stdlib::features::compose::TemplateArtifact::File) for
a shipped file, which
[`TemplateEngine::render_text`](crate::stdlib::features::compose::TemplateEngine::render_text)
receives with the text it applies. An engine reads a path written without a root beside
the file of the text that writes it. This library reads no file: the engine reads
through the program that provides it. The files are read when the template is applied,
not when it is made, so the path of an included file may be computed; a host that
records the files a build reads (the `flm` program's live preview does, to build again
when one changes) records those reads too.

### Style and script definitions

A style definition (`StyleDef`) or a script definition (`ScriptDef`) is a stylesheet or a
script that a feature's output depends on, recorded in the registry under an identifier;
a lowering rule or an emitter *requires* it by identifier, and the backend that writes
the output decides its *delivery*: written into the output, loaded from an address, or
left to the host ([`StyleDef`](crate::core::registry::StyleDef); [style and script
definitions](crate::guide::concepts_overview#style-and-script-definitions)).

A rule requires a definition in one of two ways:

- [`LoweringDecl::selection_requires`](crate::core::lowering::LoweringDecl::selection_requires)
  for a definition the rule needs whenever the plan selects it;
- [`Lowerer::require`](crate::core::lowering::Lowerer::require) for a definition it
  needs because of the node it is lowering.

Both record an identifier, and both are collected into the requirements of the lowered
tree. A feature registers the definitions those identifiers designate with
[`style_def`](crate::core::registry::FeatureBuilder::style_def) and
[`script_def`](crate::core::registry::FeatureBuilder::script_def), and they can be read
back from the finished registry. A definition's content is an **ordered list of parts**
([`DefContent`](crate::core::registry::DefContent)), each part the content itself, the
name of a file the host reads, or an address that the output loads and that this library
never fetches. Several parts let one identifier cover one concern that needs several
contents: for example, a script definition whose first part is the script's
configuration and whose second part is the address the script is loaded from. The parts
are written to the output in that order.

The backend that writes the output turns the identifiers into something a reader
receives. The HTML backend adds to each tree's requirements the style definition that
every element it writes needs, resolves all the requirements against the registry, lets
the render request say how each definition reaches the page, and writes the result into
the table `flm.html.definitions`
([`DEFINITIONS_TABLE`](crate::stdlib::backends::html::DEFINITIONS_TABLE)), which its
page assembly reads. A host that assembles its own pages reads that table too. Plain text
has no stylesheet, so the text backend records requirements and reads none. A rule
selected on several backends therefore requires an HTML definition only where
[`Lowerer::backend`](crate::core::lowering::Lowerer::backend) returns the HTML backend.

A script that **transforms elements of the page** in the browser (it replaces an
element's content by something it computes, as a script that typesets mathematical
formulas does)
must follow three rules, because a host may bring one output region of the page up to date
without loading the page again (the `flm` program's live preview does), and a script of
the page may show a copy of part of it:

- just before transforming an element, the script records the HTML inside it in the
  attribute `data-flm-original-html`; an update that brings the same HTML then leaves the
  transformed element as it is;
- the script listens for the event `flm:region-updated`, which bubbles up to `document`,
  and transforms the elements of the updated region that carry no record;
- the script listens for the event `flm:content-copied`, which another script of the page
  dispatches on a copy of part of the page that it shows (a popup previewing the target of
  a link, say), and transforms the elements of the copy that carry no record and those it
  had not finished transforming when they were copied, which first get back the HTML of
  their record.

The rendering guide states these rules ([a page updated in
place](crate::guide::rendering#a-page-updated-in-place)); the configuration script that
the HTML backend ships for its formula typesetting follows them.

The [rendering guide](crate::guide::rendering) describes these mechanisms in detail: how
a rule is called, what it may read, how one is chosen per backend, what the presentation
vocabulary offers, how a definition reaches a page ([style and script
definitions](crate::guide::rendering#style-and-script-definitions)), and what the
stylesheets of the HTML backend hold ([the stylesheets this backend
ships](crate::guide::rendering#the-stylesheets-this-backend-ships)). A worked example of
a feature that ships a stylesheet of its own is in [the AI guide on
extending](crate::guide::ai_guide_extending).

### Definition pieces for the rendered LaTeX

The rendered LaTeX ([the `latex-rendered`
backend](crate::guide::rendering#the-rendered-latex-backend)) writes a feature's content
through the shared presentation elements: a block, a span or a link carrying the
feature's **role** (a dotted name, `callout.box`) and **kind tokens**. Each element is one
`\flmx…` command or environment of a style file, which looks up LaTeX code registered
under the element's role or kind tokens and otherwise uses its default. A feature gives
its roles a look on this backend by shipping a **definition piece**
([`LatexPreambleDef`](crate::stdlib::backends::latex::LatexPreambleDef)), LaTeX text
that registers that code with the registration commands of the contract
(`\flmxDefineBlock`, `\flmxDefineSpan`, `\flmxDefineLink`, …; [Registering a
look](crate::guide::rendering#registering-a-look)).

The piece is brought into a document's style file by the feature's **style identifier**,
the identifier of its HTML stylesheet. The feature's general lowering rule requires that
identifier wherever it writes the feature's content
([`Lowerer::require`](crate::core::lowering::Lowerer::require)); the HTML backend resolves
it to the stylesheet, and this backend to every definition piece that declares, with
[`delivering`](crate::stdlib::backends::latex::LatexPreambleDef::delivering), that it
delivers it. A feature with nothing to style on the page registers a style definition
with no part under the identifier, so that the HTML backend knows it and writes nothing.
The piece requires the core of the contract, which defines the registration commands, and
is contributed to the LaTeX family's preamble slot through a peer declaration, so that the
feature builds in a registry without the LaTeX backends:

```rust
use std::sync::Arc;
use flm_core::core::registry::{
    BuildError, DefContent, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry, RegistryBuilder,
    RegistryInputs, StyleDef,
};
use flm_core::model::names::Name;
use flm_core::stdlib::backends::latex::{LatexPreambleDef, preamble};
use flm_core::stdlib::backends::latex_rendered::contract::CORE_CHUNK;
use flm_core::stdlib::{self, StdlibConfig};

/// The style identifier the feature's general rule requires at every callout.
const STYLE: &str = "callout.style";

struct Callout;

impl FlmFeature for Callout {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new("callout", "Callout boxes")
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        // The page's stylesheet for the role `callout.box`.
        b.style_def(StyleDef {
            id: Name::from(STYLE),
            content: vec![DefContent::Inline(String::from(".callout-box { margin: 1em 0; }\n"))],
            docs: String::from("the callout box"),
        })?;
        // The rendered LaTeX's look for the same role: the block set in LaTeX's
        // `quote` environment, the target of its anchor first.
        let piece = LatexPreambleDef::new(
            "callout",
            "\\flmxDefineBlock{callout.box}\n  {\\begin{quote}\\flmxIfKey{anchor}{\\flmxTarget{\\flmxKey{anchor}}}{}}\n  {\\end{quote}}\n",
            "the callout box",
        )
        .requires([CORE_CHUNK])
        .delivering([STYLE]);
        b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(piece))?;
        // The element and its general rule, which stages a block of role
        // `callout.box` and calls `lw.require(&Name::from(STYLE))`, are declared
        // as in the rest of this guide.
        Ok(())
    }
}

let mut builder = RegistryBuilder::new();
builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
builder.feature(Arc::new(Callout));
let registry = builder.build(&RegistryInputs::new())?;
# let _ = registry;
# Ok::<(), flm_core::core::registry::RegistryBuildError>(())
```

Register each role and kind token in one piece only: the shipped pieces never register a
name twice, and a name your feature writes belongs to your feature's piece. A **template**
changes the look again by registering the same name after the style file is loaded
(`\flmxDefineBlock{callout.box}{…}{…}` after `\usepackage{…}`); the later registration
wins. A definition piece can be contributed only by a feature compiled into the program:
an extension written in JavaScript or as data has no counterpart yet, and its style
identifiers write nothing on this backend.

## Options and services

A feature takes its values in three forms that differ by when they are fixed: its
configuration, a plain Rust value fixed when the registry is built; its option values, set
on a document or on a render request according to the option type's binding; and its
settings, the same values written as data ([settings, options and
configuration](crate::guide::concepts_overview#settings-options-and-configuration)). This
section describes option types, settings, and services, through which features supply
values to each other.

### Option types

An option type is a plain Rust struct a feature declares once; its values are set on a
document or on a render request (the type's binding says which), and a stage reads the
value for an option type it declared a read of: the render value if one is set, otherwise
the document value, otherwise the type's default ([`options`](crate::model::options)). A
feature declares an option type with
[`FeatureBuilder::options`](crate::core::registry::FeatureBuilder::options), or with
[`options_with_docs`](crate::core::registry::FeatureBuilder::options_with_docs), which
also records a description of the type for a generated reference. The option type's Rust
type is its identity: option types have no names of their own. Every option type
implements `Default`, `Hash` and `Debug`, and can be shared between threads
([`Options`](crate::model::options::Options)); the hash reduces a set of option values to
one number, which is part of the identity of a plan and of the record of how a tree was
produced.

The declaration's binding ([`Bind`](crate::model::options::Bind)) says where a value may
be set:

- [`Document`](crate::model::options::Bind::Document): on the document, with
  [`Doc::with_options`](crate::model::doc::Doc::with_options);
- [`Render`](crate::model::options::Bind::Render): on the render request, in
  [`PlanRequest::render_options`](crate::core::plan::PlanRequest::render_options());
- [`Either`](crate::model::options::Bind::Either): on the document, on the render
  request, or on both, the render request's value replacing the document's;
- [`Registry`](crate::model::options::Bind::Registry): nowhere, because the value is
  part of the configuration the feature was constructed with, and the feature holds it.

A stage, a rewrite stage or a lowering rule declares the option types it reads (a stage
and a rewrite stage with [`Needs::option`](crate::core::stage::Needs::option), a lowering
rule with [`LoweringDecl::option`](crate::core::lowering::LoweringDecl::option)) and
reads the value from its context
([`StageCx::option`](crate::core::run::StageCx::option), or `option` on the
[`Lowerer`](crate::core::lowering::Lowerer)). The lookup order is the same everywhere
(the render value, else the document value, else the type's `Default`), so no feature
defines a precedence of its own. Reading an option type that was not declared is an
error, and so is setting a value in a place the binding does not admit. A stage may not
declare a read of a [`Bind::Registry`](crate::model::options::Bind::Registry) option type:
the read could only return the default, since the feature holds the value itself, so
building the plan fails.

### Settings given as data

Settings are a feature's configuration and option values written as data, one map per
feature from key to value, which the library reads into the feature's own Rust types; a
settings key is one field of those types ([`settings`](crate::core::settings)). Values
given outside Rust code, such as on a command line or in a document's front matter, take
this form.

A feature that takes settings declares them once, in a
[`SettingsDecl`](crate::core::settings::SettingsDecl), which it returns from
[`FlmFeature::settings`](crate::core::registry::FlmFeature::settings):

- [`config`](crate::core::settings::SettingsDecl::config) declares the type the feature
  is constructed from;
- [`options`](crate::core::settings::SettingsDecl::options) declares each option type,
  with its binding.

Every field of those types is one settings key, read by the type's `serde::Deserialize`
implementation. Each type therefore derives `serde::Deserialize`, with
`#[serde(default, deny_unknown_fields)]` so that an empty map reads as the default and a
misspelled key is refused, and `schemars::JsonSchema`, from which the schema of the
settings is derived, with the fields' documentation as descriptions. A crate outside the
library lists `serde` and `schemars` among its dependencies and derives both; no cargo
feature of the library is involved.

The registry build declares the option types listed in the settings declaration, with
their bindings, before it calls the feature's `register` method, so `register` does not
declare them again. A package factory lists each feature with its settings declaration
(see [Bundling features as a package](#bundling-features-as-a-package)). Each key, each
binding and the feature's name are therefore stated once, by the feature.

Five settings marks (the [marks](crate::core::settings::Mark) a feature sets on a
setting or on a value below one;
[`SettingsDecl::marks`](crate::core::settings::SettingsDecl::marks)) tell a host how to
combine or read a value. A mark belongs to a node of the settings' JSON Schema: the schema
that [`json_schema`](crate::core::settings::SettingsDecl::json_schema) returns lists the
names of the marks of each node under `x-flm-marks`
([`MARKS_KEYWORD`](crate::core::settings::MARKS_KEYWORD)). A part declared from data, such
as the settings of a feature in JavaScript, writes its marks on the nodes of its own
schema ([`config_data`](crate::core::settings::SettingsDecl::config_data),
[`options_data`](crate::core::settings::SettingsDecl::options_data)); the default entries
of a map combined key by key are then the `default` of its node. A declaration written in
Rust sets each mark with a method that takes the path of the node at any depth (see
[`KeyMark`](crate::core::settings::KeyMark) for its form) and panics when the path
reaches no node of the declaration's schema:

- An object whose keys are combined one at a time is marked with
  [`merge_entries`](crate::core::settings::SettingsDecl::merge_entries), which also
  takes a function that writes the object's default entries as data (for a collection of
  named things read with
  [`named::deserialize`](crate::core::settings::named::deserialize), usually
  [`named::to_data`](crate::core::settings::named::to_data) over the field's default). A
  host that combines several sources of settings, such as `flm`, then combines the
  entries one at a time, with the default entries as the lowest-ranked source, so that a
  source adds or replaces one entry and leaves the others as they are.
- An object in which a key whose value is `false` is removed is marked with
  [`remove_false`](crate::core::settings::SettingsDecl::remove_false). A collection of
  named things carries both this mark and `merge_entries`, so that a source removes one
  entry by writing `false`.
- A setting that a value of `null` gives its default is marked with
  [`default_on_null`](crate::core::settings::SettingsDecl::default_on_null).
- Text in FLM markup is marked with
  [`markup`](crate::core::settings::SettingsDecl::markup).
- A path to a file is marked with [`path`](crate::core::settings::SettingsDecl::path).

The schema that [`json_schema`](crate::core::settings::SettingsDecl::json_schema)
returns describes every key with its documentation as plain text, without code blocks and
without anything from the first heading on (`# Examples`). Write the first paragraphs of
a field's documentation for a person who edits a settings file.

```rust
use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
use flm_core::core::settings::SettingsDecl;
use flm_core::model::options::Bind;

/// How loudly the shouting feature shouts, set per render.
#[derive(Debug, Clone, Default, Hash, serde::Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
struct ShoutOptions {
    /// How many exclamation marks follow each shout; 0 by default.
    marks: u8,
}

struct Shout;
impl FlmFeature for Shout {
    fn info(&self) -> FeatureInfo { FeatureInfo::new("shout", "Shouting") }
    fn settings(&self) -> Option<SettingsDecl> {
        Some(SettingsDecl::new("shout").options::<ShoutOptions>(Bind::Render, "How loudly to shout."))
    }
    fn register(&self, _b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        Ok(())
    }
}

let data = serde_json::json!({ "marks": 3 });
let read = Shout.settings().unwrap().read(data.as_object().unwrap()).unwrap();
assert_eq!(read.render_options().get::<ShoutOptions>().unwrap().marks, 3);
```

### Services and service slots

A service is a value that can be shared across threads (behavior behind a trait object,
or plain data) which one feature supplies for another feature, or for the host, to
use. A service slot is the declaration, by the feature that owns an
interaction, of a dotted name, the type of the values the slot takes and its arity
(at most one value, or any number); any feature, and the host through the registry
builder, may contribute a value to it, and the registry build assembles all
contributions once ([`services`](crate::core::services); [services and service
slots](crate::guide::concepts_overview#services-and-service-slots)).

The owning feature declares the slot with
[`service_slot`](crate::core::registry::FeatureBuilder::service_slot), giving a name, a
value type and an [`Arity`](crate::core::services::Arity). A feature contributes a value
with [`contribute_to`](crate::core::registry::FeatureBuilder::contribute_to) (or
[`contribute`](crate::core::registry::FeatureBuilder::contribute), which finds the slot
by the value's type), and the host with
[`RegistryBuilder::contribute`](crate::core::registry::RegistryBuilder::contribute). A
feature that cannot work in any plan without a service declares it with
[`require_service`](crate::core::registry::FeatureBuilder::require_service): an unfilled
required slot then fails the registry build, instead of a render.

A contribution to a service slot that no feature declares is a registry build error,
which catches a misspelled name. A feature that contributes to a slot that *another*
feature owns, and that may be absent, makes a **peer contribution** with
[`peer_slot`](crate::core::registry::FeatureBuilder::peer_slot), the service-slot form of
a peer declaration. If some feature declares the slot, the value fills it exactly as
`contribute_to` would, with its type checked and after the contributions already made. If
no feature declares it, the value is dropped, the build still succeeds, and one Note
([`UnresolvedPeer`](crate::core::registry::UnresolvedPeer)) joins the build diagnostics. A
feature can therefore offer a value, such as a counter declaration or a cell style, to a
feature that the host may not have registered, without depending on it.
[`peer_slots`](crate::core::registry::FlmRegistry::peer_slots) lists every peer
contribution, resolved or not.

The `graphics` feature's three service slots divide one job among services by what each
of them can do:

- the **graphics resolver**
  ([`GraphicsResolver`](crate::stdlib::features::graphics::GraphicsResolver),
  `flm.graphics.resolver`, one value) finds and reads an image file;
- the **inspector**
  ([`GraphicsInspector`](crate::stdlib::features::graphics::GraphicsInspector),
  `flm.graphics.inspector`, one value) reports an image's kind and size. It receives the
  file's content when a graphics resolver has read it; otherwise it receives the path and
  finds the file itself;
- the **converters**
  ([`GraphicsConverter`](crate::stdlib::features::graphics::GraphicsConverter),
  `flm.graphics.converters`, any number, asked in contribution order) turn content of
  one format into another; they receive content and open no file.

A feature of your own contributes a converter with `peer_slot`, as a host does with
`contribute_to`; an output's conversion rules
([`ConversionRule`](crate::stdlib::features::graphics::ConversionRule), one of the
graphics feature's settings) can then select it by name in their `via` field, where they
want that converter only:

```rust
use std::sync::Arc;

use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
use flm_core::progress::Scope;
use flm_core::stdlib::features::graphics::{
    CONVERTERS_SLOT, ConversionRequest, GraphicsConvertError, GraphicsConverter, ImageFormat,
};

/// Turns a WebP image into a PNG (a stand-in: it keeps the bytes).
struct WebpToPng;

impl GraphicsConverter for WebpToPng {
    fn name(&self) -> &str {
        "webp-to-png"
    }

    fn offers(&self, from: ImageFormat, to: ImageFormat) -> bool {
        (from, to) == (ImageFormat::Webp, ImageFormat::Png)
    }

    fn convert(&self, request: &ConversionRequest<'_>, _progress: &Scope) -> Result<Vec<u8>, GraphicsConvertError> {
        Ok(request.content.to_vec())
    }
}

/// A feature contributing the converter, whether or not `graphics` is registered.
struct Webp;

impl FlmFeature for Webp {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new("webp", "WebP images")
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        b.peer_slot::<dyn GraphicsConverter>(CONVERTERS_SLOT, Arc::new(WebpToPng))
    }
}
# let _ = Webp;
```

A stage reads services from its context: [`StageCx::service`](crate::core::run::StageCx::service)
returns one service of a given type, and
[`StageCx::services`](crate::core::run::StageCx::services) every service of that type. An
empty slot never fails a render: `service` returns `None` and `services` returns nothing,
and the stage reports the absence as a diagnostic of its own.

The registry build assembles the service slots once, between the two registration rounds,
and they never change afterwards. A value that exists only once some work has been done,
such as an index over a collection of documents, is therefore not a service but data
installed when a run is constructed (an [external
table](crate::core::run::Externals)): a value that is empty at one moment and filled at
another would make a run's result depend on when a stage read it.

**In JavaScript.** A feature of an extension written in JavaScript (see
[Extensions](#extensions)) declares and fills service slots through the same builder
methods, with data as the values:

- `b.service_slot(name, arity, docs)` declares a slot whose values are data; `arity` is
  `Arity.Single` or `Arity.OrderedMany` (from `flm:core/services`), and the name begins
  with the extension's stem and a dot (or with `NAME` and a dot, for an extension whose
  stem is `profile-NAME`), as every name the feature declares;
- `b.contribute_to(slot, value)` adds a value after those contributed so far,
  `b.contribute_first_to(slot, value)` before them, and `b.peer_slot(slot, value)` adds
  it when some feature declares the slot (otherwise the value is dropped with one Note, as
  above); a feature of any package of any extension may contribute;
- a stage reads the slot by its name: `cx.services(name)` answers every value in the
  assembled order, the values contributed first, then the others, each group in the
  order contributed (an empty list when there is none);
  `cx.services_by_precedence(name)` every value in the order of precedence, the values
  contributed first, then the others, and within each group the values of the feature
  placed last in the feature order first, each feature's in the order it contributed
  them; and `cx.service(name)` the first value in the order of precedence (`null` when
  the slot is empty or no feature declares it), so that between features the value of
  the feature placed last wins.

The values are data in both directions: a value with functions in it is refused, and a
slot of a compiled feature whose values are not data, such as the graphics converters,
cannot be read from a script. A data value contributed to such a slot fails the registry
build, with the message of the library naming the slot's type. Two slots of the standard
features take objects with methods instead of data: the citation providers and the
compose templates ([A citation provider from a
script](#a-citation-provider-from-a-script), [A compose template written as a
module](#a-compose-template-written-as-a-module)).

The extension `bibfile` of FLM's repository (`flm-ext/tests/js/bibfile/`) declares a slot
in its default package and fills it from its package `extra`; its stage reports each value
as a Note:

```javascript
import { StageDecl, Effect, Scope } from "flm:core/stage";
import { Arity } from "flm:core/services";

const NOTES = "bibfile.notes";

// In the feature `bibfile` of the package `_`:
register(b, settings) {
  b.service_slot(NOTES, Arity.OrderedMany, "notes other packages add, each `{ note }`");
  b.table(NOTES, "the notes, one item per contribution");
  b.stage({
    decl: () => new StageDecl("bibfile.notes", Effect.Compute, Scope.Document).writes(NOTES),
    run(cx, out) {
      for (const { note } of cx.services(NOTES)) {
        out.table(NOTES).push({ note });
        out.diags({ id: "bibfile.note", severity: "note", message: `a package notes: ${note}` });
      }
    },
  });
},

// In the feature `extra` of the package `extra`, which uses `.#_`:
register(b) {
  b.contribute_to(NOTES, { note: "the extra package was used" });
},
```

## Reporting progress from a stage or a service

A program that builds a document can show how far the build has gone, and can
cancel it, through the build's *progress sheet* ([`flm_core::progress`](crate::progress);
[following a build](crate::guide::embedding#following-a-build) describes the
program's side). The sheet is a tree of *rows*: each row stands for one piece of
work a person may wait for, has a state, and optionally counts units done out of
a total. The run declares one row for each scheduled stage ([the rows of a
run](crate::guide::pipeline#progress-and-cancellation-of-a-run)). A stage or a
service whose work is slow declares rows of its own under the row it works
under, and checks whether the build was cancelled.

Your code receives a [`Scope`](crate::progress::Scope), the handle of the row it
works under:

- a stage, through [`StageCx::progress`](crate::core::run::StageCx::progress):
  the scope of the stage's row, shared by the per-tree calls of the stage;
- a citation provider, through
  [`ProviderCx::progress`](crate::stdlib::features::citations::ProviderCx::progress):
  the scope of the row of the stage that retrieves the citations;
- a graphics converter, as the argument `progress` of
  [`GraphicsConverter::convert`](crate::stdlib::features::graphics::GraphicsConverter::convert):
  the scope of the row `flm.graphics.convert` ("Converting graphics") that the
  publish stage declares for that conversion. A converter that has no parts to
  report declares nothing: that row already stands for the conversion;
- a host service of `flm-ext`, as an argument of its method `call`: the scope of
  the extension's handler call ([host services for
  extensions](crate::guide::embedding#host-services-for-extensions)).

A build that reports nowhere gives [`Scope::none`](crate::progress::Scope::none),
whose methods do nothing. Your code calls them all the same, with no test of its
own: a call on a scope with no row behind it costs one test.

### Declaring rows

[`Scope::child`](crate::progress::Scope::child)`(&kind, label)` declares a row
under the scope's row and returns it as a [`Pending`](crate::progress::Pending),
not started. Start it with [`start`](crate::progress::Pending::start), which
returns a [`Task`](crate::progress::Task), or, for a row with a count, with
[`start_counted`](crate::progress::Pending::start_counted)`(unit, total)`, which
returns a [`Counted`](crate::progress::Counted) that you
[`advance`](crate::progress::Counted::advance) as units are done. End the row
with `finish`. A `Task` or a `Counted` dropped without `finish`, by an early
return or a panic, ends as `Failed`; a `Pending` dropped without being started
ends as `NotRun`. Only the code that declared a row ends it: a stage cannot end
the stage's row, which the run owns.

Follow these rules when you choose the rows:

- **A row for a heavy item, an increment for a light one.** A row is for a piece
  of work a person may wait for: a program run, a conversion, a network fetch.
  Copying one of many small files is an increment of a count.
- **A total counts the slow units only.** A citation provider counts the keys it
  fetches over the network, and not those it answers from a cache, where it can
  tell them apart before it starts. The total is given when the row starts, and
  never changes.
- **Declare possible work in advance.** Where a piece of work may be needed, such
  as a conversion of a resource whose format is known only once it has been
  fetched, declare its row before you know, and drop the `Pending` when the work
  is not needed. A row declared in advance and not run moves the estimate of the
  build forward; a row declared late moves it back. A row may still be declared
  at any time while its parent runs, for work that could not be foreseen.
- **One row for the items of a tree.** A per-tree stage declares, in each call,
  one row for the items of its tree, labeled with the tree's source where the
  stage can tell it; that row then stands for the tree in the count of the stage's
  row. A document stage
  declares one row for its items.

A row's [`Kind`](crate::progress::Kind) is a dotted name for the sort of work,
the same for every row of that sort, which you declare as a constant beside the
code that does the work, in your feature's namespace (`acme.pages`). The name is
the key of a table of expected durations that a program measures and keeps, so a
kind that is renamed loses its measured durations. A kind whose rows a person
should see has a *title*, the fixed text that a display shows for its rows
([`Kind::titled`](crate::progress::Kind::titled)). A title says what is being
done, begins with a capital letter and a verb in "-ing", and has no article and
no final period: "Rendering pages". A display passes over a row with no title
and shows the nearest row above it that has one. A row's *label* tells it from
the other rows of its kind, such as a file or a citation key.

### Stopping when the build is cancelled

Ask [`Scope::cancelled`](crate::progress::Scope::cancelled) once for each unit of
your work (a tree, an image, a formula, a citation key), not inside an inner
loop. When it returns `true`, return as soon as you can. The run discards
everything that the step under way produced, so what you return then need not be
meaningful. A cancellation is not a problem of the document: report no
diagnostic for it. A row you leave running ends as `Failed` when its handle is
dropped.

Work with effects outside the run, such as writing files or running a program,
is not undone when the step is discarded: choose the points at which you check
the cancellation so that what your code leaves is whole.

The example below converts the pages of a document in a counted row, declares
the row of a slow step that only some documents need before it knows, and checks
the cancellation once per page:

```rust
use flm_core::progress::{Kind, Scope, Unit};

const PAGES: Kind = Kind::titled("acme.pages", "Rendering pages");
const FONTS: Kind = Kind::titled("acme.fonts", "Embedding fonts");

fn render(scope: &Scope, pages: &[&str], embeds_fonts: bool) -> Vec<String> {
    // Declared before the pages are rendered, although it may not run.
    let fonts = scope.child(&FONTS, None);
    let row = scope.child(&PAGES, None).start_counted(Unit::Items, pages.len() as u64);
    let mut rendered = Vec::new();
    for page in pages {
        if scope.cancelled() {
            return rendered; // discarded; `row` ends as failed, `fonts` as not run
        }
        rendered.push(page.to_uppercase());
        row.advance(1);
    }
    row.finish();
    if embeds_fonts {
        let task = fonts.start();
        // ... embed the fonts ...
        task.finish();
    } // otherwise `fonts` is dropped, and ends as not run
    rendered
}

assert_eq!(render(&Scope::none(), &["one", "two"], false), ["ONE", "TWO"]);
```

### Log lines

[`Scope::log`](crate::progress::Scope::log)`(level, text)` writes a *log line*:
text for a person about what the work does, such as each request sent over the
network, at a [`LogLevel`](crate::progress::LogLevel) (`Error`, `Warn` or
`Info`). The program decides where it goes: the `flm` program prints `Error` and
`Warn` lines always and `Info` lines under `-v`. Call
[`Scope::log_enabled`](crate::progress::Scope::log_enabled) before you build a
text that is costly to build. A problem of the document is never a log line: it
is a diagnostic.

### Progress in extensions

An extension's handlers report on the same sheet through the module of the
extension interface for progress: `flm:progress` in JavaScript,
`flm_ext::guest::progress` in a Rust extension compiled to WebAssembly, and
`flm_ext::api::progress` in a Rust extension compiled into a program, each with
the same names. A stage's context and a citation provider's context give the
scope with `cx.progress()`, a `ProgressScope` with two methods:

- `child(kind, title, label)` declares a row and returns it, not started. The kind
  is given as its name and its title as a text (`null` for none);
- `cancelled()` returns whether the build was asked to stop.

The row returned has the methods `start()` and `start_counted(unit, total)`, with
`Unit.Items` or `Unit.Bytes` from `flm:progress`; a started row has `scope()` and
`finish()`, and a counted row also `advance(n)`. Every handle is valid for the
handler call that lent it: a row that the handler leaves running when the call
ends ends as `Failed`, and a row it declared and never started ends as `NotRun`.
An extension has no depth limit and writes no log line through a scope: it writes
on its `console`, whose lines go to the program's log sink with the extension's
name as their source (`console.error` at `Error`, `console.warn` at `Warn`,
`console.log`, `console.info` and `console.debug` at `Info`).

When the build is cancelled, the engine stops a running handler of a JavaScript
extension, and a handler of a WebAssembly module at its next call into the
host; the handler's failure is discarded with the step. A Rust extension compiled
into a program checks `cancelled()` itself. The host service `programs` declares
a row `flm.programs.run` ("Running program"), labeled with the program, for the
time the program runs, and when the build is cancelled it stops the program and
the call fails.

The stage `math-mathjax.render` of FLM's repository
(`extensions/js/math-mathjax/render.js`) counts the formulas of its tree in this
way:

```javascript
import { Unit } from "flm:progress";
import { MATH, ENVIRONMENT } from "flm:stdlib/features/math";

const FORMULAS_KIND = "math-mathjax.formulas";
const FORMULAS_TITLE = "Rendering formulas";

// In the stage's object:
run(cx, out) {
  const tree = cx.my_tree();
  if (tree === null) return;
  // The formulas are counted with a first traversal, since the row's total
  // is fixed when it starts, and converted with a second one.
  const formulas = () => tree.root().descendants().elements([MATH, ENVIRONMENT]);
  let count = 0;
  for (const _ of formulas()) count += 1;
  if (count === 0) return;
  const progress = cx.progress().child(FORMULAS_KIND, FORMULAS_TITLE, null).start_counted(Unit.Items, count);
  for (const node of formulas()) {
    // ... convert the formula, and push its row into the stage's table ...
    progress.advance(1);
  }
  progress.finish();
},
```

## Build hooks

A build hook is a callback that the registry build calls on a feature at a fixed moment.
The two build hooks let a feature declare things it cannot know by itself:

- A [`Finalizer`](crate::core::registry::Finalizer), registered with
  [`FeatureBuilder::finalizer`](crate::core::registry::FeatureBuilder::finalizer), is the
  build's **second registration round**. It runs after every feature's first round, once
  the service slots are assembled, so it can read the services
  ([`FeatureBuilder::services`](crate::core::registry::FeatureBuilder::services)) and
  declare further entities (an element, a stage, a lowering rule) derived from what other
  features contributed. Because the service slots are closed by then, a finalizer may not
  declare a service slot, contribute to one, require one, or register another finalizer;
  those methods return
  [`BuildError::ContributionAfterAssembly`](crate::core::registry::BuildError::ContributionAfterAssembly).
  There are exactly two rounds, so the build is finite and its order is easy to follow.
- A [`LateInit`](crate::core::registry::LateInit) hook, registered with
  [`FeatureBuilder::late_init`](crate::core::registry::FeatureBuilder::late_init) in
  either round, runs once the **language is built**. The usual use is compiling
  templates: a feature configured with author-written definitions cannot parse them while
  the language is still being built, since the definitions may use commands that other
  features declare. A problem the hook finds in the configuration it prepares, such as a
  template that does not parse, does not fail the build: it is written to the registry's
  build diagnostics
  ([`FlmRegistry::build_diagnostics`](crate::core::registry::FlmRegistry::build_diagnostics)),
  for the host to report once per build (the `userdefs` feature also reports a refused
  definition again at each use). The hook returns an error only when it could not do its
  own work, and that fails the build.

A late-initialization hook is also the place for a fact about the *whole* of a feature's
configuration, one that needs every entry at once (for example, whether another
definition has the same name as this one). The hook works it out once and records it on
the element values it initializes, so that no later stage needs the configuration again.

A value that the hook builds against the language, such as a compiled template or a
parsed tree, refers to the language. When the data or an aspect of one of your elements
reads such a value, store the value in a [`LangOwned`](crate::lang::LangOwned) cell, as
[`UserDefinition`](crate::lang::rewrites::userdefs::UserDefinition) does for its compiled
templates. The language then owns the value, and the element reads it through the cell
for as long as the registry exists. The reason is the memory of the registry: the
language owns its elements, so an element that owned a value referring to the language
would form a reference cycle, and the language would stay allocated after the registry
is dropped. A lowering rule or a stage is owned by the registry and not by the language,
so it can own such a value directly (for instance in a `OnceLock`).

A feature of an extension written in JavaScript registers both hooks as objects of its
script: `b.late_init({ late_init(lang, diags) { … } })`, whose `diags.push(diagnostic)`
writes to the registry's build diagnostics, and `b.finalizer({ finalize(b) { … } })`; an
exception thrown by either fails the build (see [What a feature in JavaScript adds to the
output](#what-a-feature-in-javascript-adds-to-the-output)).

## Bundling features as a package

A package is a named bundle of features together with the packages it builds on
([`PackageEntry`](crate::core::registry::PackageEntry)): its name, the packages it
`uses`, and its own features in the order they register. A program passes it to
[`RegistryBuilder::use_package`](crate::core::registry::RegistryBuilder::use_package),
which adds the features of the packages it uses first, then its own.

```rust
use std::sync::Arc;
use flm_core::core::registry::{
    BuildError, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry, RegistryBuilder,
    RegistryInputs,
};
use flm_core::stdlib::{self, StdlibConfig};

# struct Shout;
# impl FlmFeature for Shout {
#     fn info(&self) -> FeatureInfo { FeatureInfo::new("shout", "Shouting") }
#     fn register(&self, _b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> { Ok(()) }
# }
// A package of one feature, built on a package of the standard features.
let mine = PackageEntry::new("mine")
    .uses(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()))
    .feature(Arc::new(Shout));

let mut builder = RegistryBuilder::new();
builder.use_package(mine);
let registry = builder.build(&RegistryInputs::new())?;

assert!(registry.has_feature("shout"));
assert!(registry.has_feature("headings")); // came in with `std`
# Ok::<(), flm_core::core::registry::RegistryBuildError>(())
```

The registry builder records each package by its name, and skips a package whose name it
has already added. A package that two other packages both use therefore registers its
features once.

A package that a document can select by name, or whose settings are given as data, also
has a [`PackageFactory`](crate::core::registry::PackageFactory): its name, the names of
the packages it uses, and the function that builds its entry from the final settings
([`PackageSettings`](crate::core::settings::PackageSettings)), leaving out a feature that
the settings switch off. The factory finds the package's features, each with its settings
declaration, by building the package once from empty settings and asking each feature it
holds, so nothing about a feature is written a second time for the factory.
A package that holds the standard features builds them in its build function with
[`stdlib::add_features_from_settings`](crate::stdlib::add_features_from_settings).

Registration **order** matters in a few places only, because the checks run once every
feature has registered. The registry numbers capabilities, tables, stages and lowering
rules in the order they were declared, and the same order breaks ties when a plan has
nothing else to decide between two stages; two builds from the same features in the same
order therefore produce the same numbering and the same plans. Contributions fill a
service slot in the order they were made (a read for precedence takes the feature placed
last first), and the fields that several features register for one workflow apply in
registration order. Where several features define one command, the feature placed last
supplies the definition (see [Fallbacks, and replacing another feature's
definition](#fallbacks-and-replacing-another-features-definition)). The registration
order is the order the packages give, changed by the chains of the feature order: a
package's ([`PackageEntry::feature_order`](crate::core::registry::PackageEntry::feature_order);
`feature_order` in an extension's `flm` block, [An extension of the data
engine](#an-extension-of-the-data-engine)) and the host's
([`RegistryBuilder::feature_order`](crate::core::registry::RegistryBuilder::feature_order);
the `flm` program's are the front matter's).
[`stdlib::add_features`](crate::stdlib::add_features) adds the standard features in a
fixed order for these reasons.

## Features and packages chosen at run time

A document may list, in its `use` list, packages that are not compiled into the host: the
host finds them by name when it processes the document. This library declares the
interface and reads no file. A
[`PackageCatalog`](crate::core::registry::PackageCatalog) finds a package's
[`PackageFactory`](crate::core::registry::PackageFactory) by name: first among the
factories compiled into the host, then through the
[`PackageResolver`](crate::core::registry::PackageResolver) implementations the host
added, which may read files. [`resolve_all`](crate::core::registry::PackageCatalog::resolve_all)
walks the packages that a list of names uses and returns them in the order in which they
register: each package after the packages it uses, and each once; a package already found,
or one whose walk is under way, is skipped, so two packages that use each other cause no
problem. A resolver's factory is identified by its name, so a resolver that finds one file
under two spellings gives one factory for both, and the package is used once.

The crate `flm-ext` provides a resolver: its loader of extensions finds a package of an
extension, written as data, in JavaScript, compiled to WebAssembly or compiled into the
program, through the sources
the host gives it (see
[Extensions](#extensions)). The library itself ships no resolver.

A package of an extension may write fields for a workflow that a compiled package defines
under the same name. The host combines the fields that the packages write for the
workflow, by the rule between packages of the settings cascade
([`workflow_def`](crate::core::settings::cascade::workflow_def)), and registers the result
with
[`RegistryBuilder::workflow_fields`](crate::core::registry::RegistryBuilder::workflow_fields):
those fields replace the fields of the workflow of that name, or define the workflow when
no package does, so that the two make one workflow. A compiled feature registers fields
for a workflow in the same way, with
[`FeatureBuilder::workflow_fields`](crate::core::registry::FeatureBuilder::workflow_fields).

## Documentation texts

Every declaration a feature makes carries a documentation text: the feature itself
([`FeatureInfo::docs`](crate::core::registry::FeatureInfo::docs)), a command
([`ElementDef::docs`](crate::lang::mint::ElementDef::docs)), an argument
([`ArgDef::docs`](crate::lang::mint::ArgDef::docs)), a field written after a command, an
element type (below), a scoped package, a stage, a table, a lowering rule, an argument
role, an option type, a heading kind, a counter, and the other entities the builder
records. The registry keeps these texts with the declarations, and the command `flm info`
shows them: a feature's page shows its text, a command's page the texts of the command and
of each argument, an element type's page the type's text and the summary of each of its
values. This section states what such a text holds and how it is shown.

### What a documentation text holds

A documentation text is written for the person who reads the pages of `flm info`, and it
follows these rules:

- **It is FLM.** The text is read as an FLM document that uses the extension `flmdoc`
  (below): plain text and the commands of the standard features (`\emph{…}`), with code
  written between backticks, as in Markdown: `` `\section{title}` ``. The backtick is the
  only Markdown-like sequence; `*…*` and `**…**` are shown as written. Outside a code span
  a backslash starts a command, braces must pair up, and a lone `%` is an error, so write
  a command's name, a LaTeX fragment or a file name between backticks.
- **Its first paragraph is its summary.** The text up to its first blank line is shown
  wherever the item is listed (the list of a feature's commands, for example); the whole
  text is shown on the item's own page. A text is usually one sentence; write more
  paragraphs only when the thing needs them.
- **It says what the thing does.** A command's text begins with what the command does, not
  with how it is written: the page shows the command's signature and each argument
  separately.

The descriptions of a feature's settings come from another place: the Rust documentation
of the settings type, which the schema-derivation library turns into the settings' JSON
Schema ([`SettingsDecl::json_schema`](crate::core::settings::SettingsDecl::json_schema)).
Each description is first turned into plain text (a code block and everything from the
first heading on are dropped, a link keeps its words alone), and then read by the same
rules, as FLM with code between backticks. Write a settings field's documentation
accordingly: `` `true` ``, not `true` in quotes, and `` `\label` `` between backticks.

The program's own texts are tested to be valid FLM. A text that an extension wrote may not
be; `flm info` then shows it as written, as plain text, with a warning, and does not fail
(see [Documentation texts that are not valid FLM](crate::guide::command_line#documentation-texts-that-are-not-valid-flm)).

### The text of an element type

An element type is the name its element values share (`flm.heading`, for every level of
heading), and each value carries a text of its own
([`ElementDef::docs`](crate::lang::mint::ElementDef::docs) states the text of the command,
[`ElementSpec::docs`](crate::model::element::ElementSpec::docs) the text of the value).
The type itself may have one more text, which says what the nodes of the type mean,
whatever their value; write it for the type, not as a copy of one value's text. A feature
gives it with
[`FeatureBuilder::element_type_text`](crate::core::registry::FeatureBuilder::element_type_text):

```
# use std::sync::Arc;
# use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry};
# use flm_core::lang::mint::{ElementDef, SyntaxDef};
# use flm_core::model::element::ElementSpec;
# struct Notes;
# impl FlmFeature for Notes {
#     fn info(&self) -> FeatureInfo { FeatureInfo::new("notes", "Notes") }
fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
    let note = Arc::new(ElementSpec::new("notes.note").docs("A note of the author."));
    b.element(ElementDef::new("notes", ["note"], SyntaxDef::Macro { args: Vec::new() }, note)
        .docs("Starts a note."))?;
    b.element_type_text("notes.note", "A note, set apart from the text around it.")
}
# }
# let registry = build_registry([Arc::new(Notes) as Arc<dyn FlmFeature>])?;
# assert_eq!(registry.element_type_text("notes.note").map(|text| text.owner.as_str()), Some("notes"));
# Ok::<(), flm_core::core::registry::RegistryBuildError>(())
```

Only a feature that declares the type may give its text: one of its declarations other than
a value added to another feature's type
([`peer_element_value`](crate::core::registry::FeatureBuilder::peer_element_value)) creates
an element of that name. An element type has at most one text: of several features that
declare one type, one gives it. A text for a type the feature does not declare, and a
second text for one type, are errors when the registry is built. The language gives the
texts of its structural element types (`flm.text`, `flm.paragraph`, `flm.field`, …), and a
presentation element has the text it is declared with. The registry gives a type's text,
with the feature that gave it, by the type's name
([`FlmRegistry::element_type_text`](crate::core::registry::FlmRegistry::element_type_text));
a type of which no declaration gives a text has none.

An extension in JavaScript or in Rust gives the text of an element type it declares with
`b.element_type_text(name, docs)` on its feature builder, by the same rules; the type's
name begins with the extension's stem and a dot, as the name of every element it declares
does (see the names of [an extension in JavaScript](#an-extension-in-javascript)).

### Writing documentation pages: the extension `flmdoc`

The extension `flmdoc` provides the markup in which the pages of `flm info` are written,
and any document may use it. It is written in Rust and compiled into the `flm` program, so
nothing needs to be installed; a document lists it in its front matter's `use` list, or
the command line adds it with `--use flmdoc`:

```text
---
flm:
  use: [flmdoc]
---
The command `\section` starts a section; see \docref{features/headings}{the feature}.
```

It offers four things:

- **Code spans.** A code span begins with a run of backticks and ends at the next place
  where as many backticks follow one another (unlike in CommonMark, a longer run also ends
  it, at its first backticks, and the backticks left over follow the span); its content is
  shown as inline code, exactly as written (a backslash, a brace or a percent sign is an
  ordinary character there). To show a backtick, open the span with a longer
  run: ``` ``a`b`` ``` shows ``a`b``. As in CommonMark, each line ending in a span becomes a
  space, and when the content both begins and ends with a space (and is not all spaces),
  one space is removed from each end. Code spans are written in text; inside mathematics a
  backtick is an ordinary character. In a document that uses
  `flmdoc`, every backtick in text opens a code span, so the quotation marks that FLM
  otherwise writes with backticks (``` ``…'' ``` and `` `…' ``) are not available: write “…”
  and ‘…’ directly. A backtick that no later run of as many backticks closes is an error.
- **The documentation of an item**, laid out by a few constructs. The page of the macro
  `\section`, as `flm info` writes it (without its front matter):

  ```text
  \begin{docitem}[declared-by={\docref{features/headings}{\verbcode{headings}}}, modes={\begin{docinlinelist} \item \verbcode{text} \end{docinlinelist}}]{macro}{\section}
  \docsignature{\section*[options]{title}\label{target}}
  \docsummary{Starts a heading of level 1.}
  \begin{docparams}
  \docparam{*}{star}{}{With a star, the heading is not numbered, as with `numbered=false`.}
  \docparam{[options]}{options}{}{The options of the heading, as key-value pairs: `numbered=true|false`, `toc=true|false`, and `alt={…}` for the title in a table of contents.}
  \docparam{{title}}{title}{}{The heading's title.}
  \end{docparams}
  \begin{docparams}[Fields written after it]
  \docparam[repeatable]{\label{target}}{label}{}{Attaches a label to the construct, which a reference can point at; may be repeated.}
  \docparam[field={\verbcode{\label}}]{{target}}{target}{flm.refs.defined-label}{The label, written `type:label` (`sec:intro`).}
  \end{docparams}
  \docfield{Element type}{\docref{namespaces/element/flm.heading}{\verbcode{flm.heading}}}
  \end{docitem}
  ```

  `\begin{docitem}[facts]{kind}{name} … \end{docitem}` documents one item of a kind
  (`macro`, `feature`, any word), with its facts as key–values (below), among them the
  anchor that a link points at (`anchor=…`); the facts are written after its body.
  `\docsignature{…}` shows how the item is written, as a block of code;
  `\docsummary{…}` states the summary of a documentation text, and
  `\begin{docdetails} … \end{docdetails}` holds the rest of that text, its paragraphs and
  blocks. `\begin{docparams}[title] … \end{docparams}` lists parameters under a title
  (`Arguments` by default), each given by `\docparam[facts]{form}{name}{role}{text}`,
  available only there, its facts written after its text. `\docfield{key}{value}` states
  one labeled fact with a plain value, `key: value`, its label written by the page. The
  kind and name of `docitem`, the signature, and the form, name and role of `\docparam`
  are raw text; one that holds a brace alone is written between another pair of
  delimiters (`\docsignature|\{|`).
- **Lists and types.** `\begin{docentries}[title={…}, intro={…}] … \end{docentries}` lists
  named things under a heading of the page (the key `title`, with its level under the key
  `level`, 1 by default) and a paragraph (the key `intro`), each given by
  `\docentry[facts]{name}{summary}`, available only there; the name, usually a link to the
  thing's page, may be empty. The first of the values of the element type `flm.heading`,
  on that type's page:

  ```text
  \begin{docentries}[intro={Its values, each with the commands written for it:}]
  \docentry[written={\begin{docinlinelist} \item \docref{features/headings/macros/section}{\verbcode{\section}} \end{docinlinelist}}, aspects={\begin{docinlinelist} \item \verbcode{flm_core::model::aspects::BlockRoleAspect} \item \verbcode{flm_core::model::aspects::Sectioning} \item \verbcode{flm_core::model::aspects::Referenceable} \end{docinlinelist}}]{}{`section`: A heading of level 1.}
  \end{docentries}
  ```

  `\begin{docinlinelist} \item[facts] … \item[facts] … \end{docinlinelist}` lists things
  inline, in a sentence or in the value of a fact, and `flmdoc` writes the commas between
  them; `\item` is available only there. `\docjsontype{schema}` writes the type that a
  JSON Schema describes, in words: `\docjsontype{{"type": "array", "items": {"type":
  "string"}}}` shows `list of string`. The schema is raw text, and text that is not JSON
  is an error.
- **Links to other pages.** `\docref{path}{text}` links to the documentation page of a
  path (raw text). The address depends on the render setting `flmdoc.link_style`: with
  `command`, the default, it is the command that shows the page,
  `flm info features/headings`, for reading the pages at a terminal; with `path`, it is
  the page's path followed by `.html`, `features/headings.html`, counted from the root of
  the page tree (not relative to the page holding the link), for a folder of HTML pages.
  The `text` profile prints a link as its text followed by its address. Any other value
  is an error, reported at each `\docref`.

A fact that the page composes from structure is a key–value of the construct of the thing
it describes, and `flmdoc` writes its label and its words: `declared-by={…}` on an item
writes “Declared by: the feature …”, `modes={…}` writes “Available in: … mode”,
`repeatable` on a parameter writes “It may be written more than once.” A value is
document content (a link, code, an inline list), a few keys take one word or a whole
number, and a flag takes no value; a value written as one group, `{…}`, is the group's content, so that it
may hold a comma. The keys concern who declared an item
and where (`declared-by`, `declarer`, `within`, `switched-off`, `page`), where a command is
available (`modes`, `places`), a package's origin (`origin`, `extension`), a stage's place
in a plan (`plan`, `workflow`, `batch`, `by`, `over`), the notes of an entry (`owner`,
`outputs`, `written`, `unwritten`, `aspects`, `rule`, …), of a parameter (`layout`,
`mode`, `scoped`, `kept`, `field`, `default`, `reader`, `repeatable`) and of an item of an
inline list (`package`, `body`, `argument`, `field`, `writer`, `optional`, `missing`).
The extension's README (`extensions/rust/flmdoc/README.md` in the FLM repository) lists
every key with the values it accepts and the words it writes. A key that a construct does
not read, and a value that a key does not accept, are errors at the construct; the rest of
the construct is still written.

Each construct becomes ordinary presentation nodes (paragraphs, blocks, headings, spans,
lists, inline and block code, a link) that carry a role named after the construct
(`flmdoc.item`, `flmdoc.signature`, `flmdoc.param.role`, `flmdoc.entry.name`, …), the
words of a fact in a span of a role named after the fact (`flmdoc.fact.declared-by`); the HTML output writes a role
as a class (`flmdoc-item`), and the extension ships no stylesheet. The constructs are
written for the profiles `text` and `html`; the profile `latex-rendered` writes the nodes
they become as it writes every such node, and the profile `latex-recomposed` cannot render
a document that uses them.

### Dropping the documentation texts: the cargo feature `docs`

The cargo feature `docs` of `flm-core`, on by default, keeps the documentation texts. A
program that never shows them (a build for WebAssembly that renders documents, for
example) can turn it off to carry none of them: every builder method, builder function
and constructor that takes a documentation text then stores an empty one, the texts read
from settings data (a user definition, a heading kind, a workflow) included. Turning the
feature off changes neither a rendered document nor the [registry
digest](crate::model::digest), since no documentation text is an input of either. What
does change, beside the texts: the top-level description of each feature's settings JSON
Schema, which is made of those texts (the descriptions of the individual settings keys stay,
being part of the schema), and the message of
[`RunError::MissingExternal`](crate::core::run::RunError::MissingExternal), which quotes a
table's text. A text that a program assigns directly to a public `docs` field is kept.

A library that shows the texts, such as `flm-info`, depends on `flm-core` without its
default features, so that the program that embeds it decides: that program keeps `docs`
on through its own dependency on `flm-core`.

## Extensions

### What an extension is

An *extension* is a set of files that a host finds by name while it processes a
document, without having been compiled with it, and that provides one or more packages.
A document lists a package of an extension under `use`, as it lists a compiled package.
A package of an extension lists, among the packages it uses, the packages of other
extensions it builds on; it need not list the standard features, which a host loads into
every document by default (the `flm` program, through its package `std`).
The words this chapter uses:

- the *extension* is the unit the host finds and reads: a manifest, and for an extension
  written as a folder, the files beside it;
- a *package* is the unit a `use` entry names; one extension provides one or more;
- the *engine* of an extension turns its files into packages. The engine `data` reads an
  extension written as data (settings, workflows, compose templates: no behavior); the
  engine `js` runs an extension written in JavaScript, whose features declare elements,
  tables, stages, rewrite stages, lowering rules, presentation elements, backends,
  outputs and settings through the same feature builder as a feature written in Rust;
  the engine `wasm` runs an extension compiled to one WebAssembly module, typically
  from Rust, whose features declare the same things through the same builder; the engine
  `native` runs an extension written in Rust and compiled into the program that loads it
  (see [A Rust extension compiled into a program](#a-rust-extension-compiled-into-a-program));
- the *manifest* is the extension's YAML file: `NAME.yaml` for an extension of one file,
  `NAME/flmextension.yaml` for an extension written as a folder.

The crate `flm-ext` holds the extension layer: the manifest's reader, the grammar of a
`use` entry, the engines, and the loader `flm_ext::ExtensionLoader`, a
[`PackageResolver`](crate::core::registry::PackageResolver) that a host adds to its
[`PackageCatalog`](crate::core::registry::PackageCatalog). The host gives the loader its
*sources*, which find an extension by name and read its files; the host library of the
`flm` program gives it the folders of its search path and, last, the extensions shipped
with FLM, compiled into the program. `flm-ext` reaches the library
only through this crate's public interface, as any other extension crate does.

### The manifest

The manifest's root holds two keys, each optional. `extension` says what the extension
is: `description`, `author`, `flm_version` (the versions of FLM it works with, as a
version requirement such as `>=0.5`), `engine` (`data` when the key is absent, `js`,
`wasm` or `native`), `js` (for the engine `js`: `{main: PATH}`, the main module's path inside the
extension's folder) and `wasm` (for the engine `wasm`: `{module: PATH}`, the module's path
inside the extension's folder). `flm` holds the package of an extension of the engine `data`, and is
refused for another engine. The command-line guide lists every key, the two layouts, the
grammar of a `use` entry (`LOCATOR` or `LOCATOR#PACKAGE`, `_` being the default package)
and the folders searched ([Extensions](crate::guide::command_line#extensions) and [Where
extensions are looked for](crate::guide::command_line#where-extensions-are-looked-for)).

### Paths inside an extension

An extension names its own files by paths: the main module of an extension in
JavaScript and the WebAssembly module, in the manifest (`extension.js.main`,
`extension.wasm.module`), the files a compose template's description gives and those the
template includes, the path a handler gives the service `files` under the root
`self`. Such a path is written with `/` between names, on every system; every other
character, `\` included, belongs to a name, so that `lib\x.js` names one file. The path
is relative to the file that names it: a path the manifest writes is relative to the
extension's folder, where the manifest stands; a path a compose template's description
writes is relative to the description's folder; a path given to the service `files` is
relative to the extension's folder. The path must stay inside the extension's folder: a
path that is absolute (it begins with `/`, or is `~` or begins with `~/`), and a path
whose `..` climbs above the extension's folder, are refused, and so is, on a disk, a file
that a symbolic link leads outside it. This check is against a broken or misconfigured
extension, not a protection. A JavaScript extension names the modules it imports by
JavaScript's own rule ([Imports](#an-extension-in-javascript), below), under which
only a specifier that begins with `/` is absolute; the files of those modules are then
read as above, a symbolic link leading outside the extension's folder refused.

### An extension of the data engine

An extension of the engine `data` provides one package, named `_`, so a document lists it
by its locator alone (`use: [mystyle]`). The package's contents are the manifest's `flm`
block, read by the same rule as the `flm` block of a document's front matter: `use` (the
packages it uses), `features` (settings of features, with the key `enabled: false`, or its shorthand `false`,
to switch one off),
`parsing`, `workflows` and `feature_order` (chains of the order of features, below). Any
other key is refused, `layout` and `default_profile` included, which a document's front
matter alone writes. When the extension is a folder whose folder `templates/` holds the
descriptions of compose templates (under `templates/OUTPUT/`, each either the folder
`FOLDER/` holding the description `flmtemplate.yaml` and the template's own files, or
the file `FILE.yaml`, a description alone; every other file is left out, a file of
`templates/` itself included; the description's keys `name` and `output`
give the template's name and the output it serves, not the names of its folders and
files; its key `main` gives the file of the template's text, and its key `artifacts` the
files and folders the compose template ships, each by its path relative to the
description's folder, read from the extension's files; the template's includes are read
from the extension's files too, when it is applied; see [the guide to the command-line
tool](crate::guide::command_line#extensions)), the package also has one feature, which
contributes them to the [`compose`](crate::stdlib::features::compose) feature's service
slot of templates, under the extension's `description` as its title. An extension
written as data never adds behavior.

**The order of features.** A package states the order it needs between features with
`feature_order`: one chain, or a list of chains, each two or more features' names (not
packages' names) joined by `<`:

```yaml
# mypreamble/flmextension.yaml
flm:
  use: [phfpack, math-mathjax]
  feature_order: [math-mathjax < phfqit]
```

The package's chains reach the registry build together with the chains of every other
package in use and of the document's front matter; a feature that is not in use is
left out of a chain, and the rest of the chain still applies. The order decides which
definition applies where two features define one command, and which feature's
contribution wins where two compete
([Features and packages](crate::guide::concepts_overview#features-and-packages)).
Declare a chain only when the extension needs that order: the chain then states that
the extension does not work with the reverse order, and a document or another package
that places the features the other way round stops the build with an error naming both
chains. An extension that works in either order says nothing. A chain orders two whole
features: every collision between them is settled one way. An extension that needs a
finer order splits a feature into several (`phfqit-delimiters`, `phfqit-stdmacros`), each
ordered on its own.

The settings an extension's package writes are a source of settings of their own, below
the document's front matter: a package wins over the packages it uses, and two packages
of which neither uses the other must agree (see [the ranks of the
settings](crate::guide::command_line#ranks-of-the-settings)). A host combines the
sources with the library's settings cascade
([`core::settings::cascade`](crate::core::settings::cascade)).

### An extension in JavaScript

An extension in JavaScript is a folder whose manifest names the engine `js` and its main
module:

```yaml
# wordcount/flmextension.yaml
extension:
  description: Counts words
  engine: js
  js:
    main: main.js
```

**The default export.** The main module's default export is a function. The engine calls
it once with the extension builder `ext`, and each call `ext.package(name, object)`
declares one package of the extension: `_` is the default package, which a `use` entry
without `#` names, and any other name (letters, digits, `-` and `_`) is reached as
`wordcount#name`.

**The package object** has these keys, each optional:

| key | what it holds |
|---|---|
| `uses` | the packages the package uses, as `use` entries: a package of another extension (`phfpack`, `letter#html`), a package compiled into the host (`math-passthrough`), or `.#core` for the package `core` of this extension |
| `flm` | a block of settings, as the `flm` block of an extension of the engine `data` writes it (`features`, `parsing`, `workflows`, `feature_order`: `{ feature_order: ["math-mathjax < phfqit"] }`) |
| `templates` | the compose templates the package ships: a list of the paths of their descriptions among the extension's files, relative to the extension's folder (`templates/html/fancy/flmtemplate.yaml`); each description gives its compose template's `name` and `output` |
| `host` | the host services the package's handlers call: a list of names ([Host services](#host-services)) |
| `features` | the package's features: a map from a feature's name to its feature object, in the order written |

**The feature object** has these keys:

| key | what it holds |
|---|---|
| `title`, `docs`, `version` | texts, optional: the feature's information, as a compiled feature's [`FeatureInfo`](crate::core::registry::FeatureInfo) |
| `settings` | optional: the feature's settings, declared as data (below) |
| `templates` | optional: the template modules the feature contributes, a map from a module's name to `{ output, settings }` ([A compose template written as a module](#a-compose-template-written-as-a-module)) |
| `register(b, settings)` | a function: it declares what the feature contributes through the feature builder `b`, a JavaScript object with the methods of [`FeatureBuilder`](crate::core::registry::FeatureBuilder); `settings` is the feature's configuration as written in the document's settings (`{}` when nothing is written under the feature), or as its reader answered it |
| `read(settings)` | a function, optional: the feature's configuration reader (below) |

**Settings.** A feature in JavaScript declares its settings as data, since it has no Rust
type to derive them from. `settings.config` is the feature's configuration, fixed when
the registry is built: `{ docs, schema }`, where `schema` is a JSON Schema of an object
whose properties are the configuration's settings keys. `settings.options` declares
option types by name: each `{ bind, docs, schema }`, where `bind` is `document`, `render`
or `either` (see [options](crate::guide::concepts_overview#settings-options-and-configuration)).
The library registers them as it registers a compiled feature's settings
([`SettingsDecl::config_data`](crate::core::settings::SettingsDecl::config_data),
[`SettingsDecl::options_data`](crate::core::settings::SettingsDecl::options_data)), so
a document writes the keys of both under `flm.features.NAME`, `flm schema` describes
them, and the preview's settings tool edits them. The marks of a setting, or of a value at
any depth inside one, are written on the node of the schema that they concern, under
`x-flm-marks`, as a list of mark names (see [Settings given as data](#settings-given-as-data)):

```javascript
settings: {
  config: {
    docs: "The callout boxes.",
    schema: {
      type: "object",
      properties: {
        kinds: {
          type: "object",
          default: { note: { title: "Note" } },
          additionalProperties: { type: "object", properties: { title: { type: "string", "x-flm-marks": ["markup"] } } },
          "x-flm-marks": ["merge-object-key-values", "remove-key-when-value-is-false"],
        },
      },
    },
  },
},
```

A document that writes `kinds: {warning: {title: Warning}}` then keeps the default entry
`note`, and `kinds: {note: false}` removes it. `register` receives the
configuration; a stage reads an option type by its name, after declaring the read in
its needs: `new Needs().option(name)` in `needs()`, then `cx.option(name)` in `run`,
which answers the option's settings as a map.

**The configuration reader.** The library checks the keys of a configuration declared as
data and nothing else of its values. A feature that reads its configuration gives
`read(settings)`, which the program calls whenever it reads a document's settings, for
every feature of a package the document uses that declares a reader and is not switched
off in the document's settings, before the registry is built: it receives the
configuration written under the feature (`{}` when nothing is written under the feature,
or none of the configuration's own keys) and answers `{ value }`, `value` being the
configuration that `register` receives (the configuration itself, for a reader that only
checks it), or `{ error: { path, detail } }`, the value at fault: `path` is its key path
below the feature's name (`macros.abs`; left out for the configuration as a whole) and
`detail` the condition it violates (``must be a text, not `3` ``), the shape of
`ReadError` in `flm:core/settings`. The program reports a fault as it reports a compiled
feature's settings that cannot be read, where the document wrote the value, and with no
place in the document when its settings do not name the feature
([`SettingsDecl::config_data_read`](crate::core::settings::SettingsDecl::config_data_read)).
A feature written in Rust gives its reader with `Feature::read`.

**Imports.** A module imports:

- the modules of the extension interface, under the prefix `flm:` (`flm:core/stage`,
  `flm:lang/rewrites/userdefs`, …), which mirror this crate's items, with the same names;
- the files of the extension, by a path relative to the importing module, with the file
  name's extension written (`./helpers.js`, not `./helpers`), resolved as JavaScript
  resolves a relative specifier, as a relative web address: joined to the importing
  module's folder, `.` and `..` resolved as text (`./a/../b.js` is the file `b.js` of the
  importing module's folder), `/` between names, `\` and `~` characters of a name
  (`./~/x.js` is the file `x.js` of the folder `~` of the importing module's folder); a
  path may not climb above the extension's folder, and two specifiers that resolve to
  one file are one module. The main module, read from the path the manifest gives
  (`extension.js.main`, [Paths inside an extension](#paths-inside-an-extension)), is the
  module that a specifier resolving to that path names: `./main.js` imported from
  `src/other.js` is the main module `./src/main.js`;
- the modules the host program offers, by a bare name.

A dynamic `import()` is refused: every module is imported by an `import` declaration at
the top of a module, and the extension's files are read once, when it is loaded.

**Names.** Every element, table, stage, capability, option type, scoped package, lowering
rule, style and script definition that a feature of an extension declares, and the name of
every value it contributes as data (a counter, a definition piece), must begin with the
extension's *stem* and a dot: the stem is the last segment of the locator through which
the extension was first reached (`wordcount` for `wordcount`, `style` for `@acme/style`).
An extension whose stem is `profile-NAME`, which the profile `NAME` uses ([Capabilities,
collections, ordering and workflows](#capabilities-collections-ordering-and-workflows)),
may also begin these names with `NAME` and a dot: wherever this chapter speaks of the
stem, `NAME` may take its place. A name that another feature owns, such as a table a
stage reads, is not checked. Nor is the identifier of a diagnostic a feature reports,
which is not a declaration: it may be any identifier, a library condition's included.

A feature's own name carries no stem, so that a front matter configures it under a short
key (`features: { wordcount: … }`). Two extensions that declare features of one name
cannot be used together: the build fails with an error. Give a feature of
your own a name that no other extension is likely to use, for example one that begins
with your organization's or your extension's name.

**What a script can reach.** A script runs in an engine instance that reaches nothing
outside itself: no files, network, timers or processes, and a clock and a random-number
generator that give the same answers on every run. What the program offers as *host
services*, and the package declares, is the one way out ([Host
services](#host-services)). A handler call has a time budget and
an engine instance a memory limit; the memory a handler needs depends on the objects it
keeps, and [Traversals and sequences](#traversals-and-sequences) describes how a handler
reads a long document without keeping its nodes. When an engine instance other than the one that
loaded the extension must run a stage or a hook, it first runs the feature's `register`
again with the same configuration, so a feature's `register` must declare the same
things under the same names every time it runs. The documentation of the module
`flm_ext::quickjs` states the sandbox, the limits and this rule in full, together with how
each item of the extension interface appears in JavaScript.

**Editor support.** The file `flm-ext/flm.d.ts` in FLM's repository declares every module
under `flm:` in TypeScript: its classes with their methods, the objects an extension writes
(a stage, an expansion hook, a rule's body) as interfaces, its enums and constants with
their values. A declaration that mirrors a documented Rust item carries the first sentence
of its documentation. An editor that reads TypeScript declarations completes the names a
script imports from `flm:` modules, shows each item's sentence, and reports a misspelled
method or a wrong number of arguments, once a file `jsconfig.json` beside the extension's
manifest points at the declarations (replace `PATH` with the path of `flm.d.ts`;
`"strict": false` keeps the checker from reporting every function parameter that has no
declared type):

```json
{ "compilerOptions": { "checkJs": true, "strict": false, "module": "es2022",
                       "moduleResolution": "bundler" },
  "files": ["PATH/flm.d.ts"], "include": ["**/*.js"] }
```

The declarations describe the extension interface of the `flm-ext` version written in the
file's first line. FLM itself reads neither file: the checks are the editor's. The
documentation of the module `flm_ext::quickjs` describes the declarations under "Editor
support".

### Traversals and sequences

An extension reads a document through objects of the extension interface: a node, a tree
or a staged node that a handler receives stands for an object that FLM holds in Rust.
Each call of a method of such an object is a call from the extension's engine into the
host program, and each such object that the engine holds takes some of the engine's
memory, which is limited (64 MiB by default). The methods that would return a number of
nodes, trees or rows that grows with the document therefore return one object, from
which the extension takes the items. There are two kinds of such objects: traversals and
sequences.

**Traversals.** `cx.walk()` (every node of every tree of the run, with its address),
`node.descendants()` (the nodes below a node, in document order) and `cx.trees()` (the
frozen trees of the document, each with its id) return a *traversal*. An extension
iterates a traversal once, in order:

```js
for (const { node, addr } of cx.walk()) { … }
for (const node of tree.root().descendants()) { … }
for (const [id, tree] of cx.trees()) { … }
```

The interface fetches the items from the host a group at a time, and hands them to the
loop one by one. A traversal has no length and no access by index. Calling the method
again returns a new traversal, which starts from the first item.

**Restricting a traversal to elements or to node kinds.** The two traversals of nodes,
`walk()` and `descendants()`, have two methods that return the traversal restricted to
the nodes that match:

- `elements(names)` keeps the nodes whose element has one of the names in the list
  `names` (the name that `node.element_name()` returns). A name that no element has
  matches no node.
- `kinds(kinds)` keeps the nodes whose kind (`node.kind()`) is one of the `NodeKindName`
  values in the list `kinds`. For instance, `kinds([NodeKindName.Chars])` keeps the
  character nodes, those for which `node.is_chars()` is true.

The host compares the nodes, and a node that does not match never reaches the extension:
it costs no call into the host and no memory of the engine. The order of the remaining
nodes is unchanged, and the descendants of a node are visited whether or not the node
matches. A traversal restricted with both methods keeps the nodes that match both.

Restrict the traversal whenever a stage looks for the nodes of a few elements or of one
kind. A stage that tests every node itself makes at least one call into the host per
node, and on a long document these calls take most of the stage's time. For instance,
the check of the `math-mathjax` extension visits the math environments of a tree only:

```js
import { ENVIRONMENT } from "flm:stdlib/features/math";

for (const node of tree.root().descendants().elements([ENVIRONMENT])) { … }
```

**Sequences.** A method that returns a list of nodes (`node.children()`, `node.body()`,
`node.argument_content_nodes_named(name)`, the `content` of a line of a math
environment, …) returns a `Nodes` object. A method that returns staged nodes
(`lw.lower_body(cx, node)`, `lw.lower_arg_named(cx, node, name)`,
`rs.restage_subtree(node)`, …) returns a `StagedNodes` object, and the rows of an
extension's own table (`cx.get(name).ext.items()`) are a `Rows` object. Each is a *sequence*, an ordered
collection with these methods:

- `len()` and `is_empty()` return its length, with no call into the host;
- `get(i)` returns the item at the index `i`, or `null` past the last item;
- `for … of` iterates the items in order, fetching them from the host in groups, and can
  be repeated. Spread and destructuring work as on any iterable:
  `const [first] = node.children()`.

A method whose Rust counterpart returns an `Option` returns `null` or a sequence:
`node.body()` returns `null` for a node without a body.

A sequence is not an array and has no array methods. `[...nodes]` makes an array, with
one object of the engine for each node. Make one for a short list that a handler needs
whole, such as the content of one argument, and iterate the sequence otherwise.

**Passing content on.** A sequence that a handler passes back to the interface crosses
as one object, whatever its length, and its items never become objects of the engine.
Wherever the interface takes several nodes (`chars_text`, `lw.lower_nodes`,
`write_math_run`, …), a handler passes a `Nodes`, or an array whose items are nodes and
`Nodes`, which the host joins in order (a *joined list*). Wherever the interface takes
several staged nodes (`lw.pres`, `Lowering.Emit`, `Restage.Emit`,
`rs.restage_argument_with_content`, …), a handler passes a `StagedNodes`, or an array of
staged nodes and `StagedNodes`. In a tree of `lw.pres_tree`, a child `{ build }` takes one
staged node, a `StagedNodes`, or such an array. For instance, a lowering rule that places
the lowered body of an environment between two texts reads none of its nodes:

```js
return Lowering.Emit([lw.text(cx, "["), lw.lower_nodes(cx, node.body()), lw.text(cx, "]")]);
```

The requirements of each method hold as they do for a list: the nodes given to
`lw.lower_nodes` follow one another in one tree, and a staged node is placed at most
once.

**In a Rust extension.** The guest client of a Rust extension ([A Rust extension compiled
to WebAssembly](#a-rust-extension-compiled-to-webassembly)) has the same objects.
`Walk`, `Descendants` and `Trees` implement `Iterator`; each item is a `Result`, since
fetching a group calls into the host and the call can fail. `elements` takes a list of
names and `kinds` a slice of `NodeKindName`s:
`root.descendants()?.kinds(&[NodeKindName::Chars])?`. `Nodes` and `StagedNodes` have
`len()`, `is_empty()`, `get(i)` and `iter()`. An extension also builds a sequence of its
own, empty (`StagedNodes::default()`) or from a `Vec`, and extends it with `push` (one
item) and `push_all` (another sequence) without any call into the host:

```ignore
let mut content = StagedNodes::default();
content.push(lw.text(cx, "[")?);
content.push_all(&lw.lower_body(cx, node)?);
content.push(lw.text(cx, "]")?);
Ok(Lowering::Emit(content))
```

`to_vec()` fetches every item of a sequence into a `Vec`, one value for each item, as
`[...nodes]` does in JavaScript. A Rust extension compiled into a program has no memory
limit, and its calls into the host cost no JSON; the same code serves both forms.

### What a feature in JavaScript adds to the output

A feature in JavaScript registers lowering rules, style and script definitions and the
tables they read the way a compiled feature does, through the builder `b` and the modules
under `flm:`. The `math-mathjax` extension, which renders mathematics with MathJax, uses
each of the items below (its files are in the folder `extensions/js/math-mathjax/` of the
FLM repository; [mathematics processed by
MathJax](crate::guide::command_line#mathematics-processed-by-mathjax) describes it for an
author).

- **Lowering rules.** `new LoweringRule(name, element, decl, body, mark)` (from
  `flm:core/lowering`), registered with `b.lowering_rule(rule)`, takes its arguments in the
  order of [`LoweringRule`](crate::core::lowering::LoweringRule)'s, with the rule's
  body an object `{ lower(node, cx, lw) { … } }` that answers a `Lowering`. The body runs
  on the thread that lowers, under the extension's limits; an exception in it is the Error
  `flm.ext.handler-failed` at the node, and the node is replaced by an
  `flm.pres.unsupported` stand-in. The extension's rule `math-mathjax.formula.lower.html`
  lowers `flm.math` on the `html` backend.
- **The lowerer.** The body's `lw` offers the methods of
  [`Lowerer`](crate::core::lowering::Lowerer), each taking `cx` first where it stages:
  `lw.lower_arg_named(cx, node, name)` lowers an argument, `lw.lower_nodes(cx, nodes)` a run
  of sibling nodes (the extension lowers the argument of `\text{…}` with it),
  `lw.get(name)` reads a table, and `lw.get_at(name, node)` reads only the items of the
  extension's own table that belong to one node.
- **Presentation as data.** `lw.pres_tree(cx, tree)` stages a whole tree of presentation
  nodes in one call. Each node is `{ element, payload, children }`, with the payload
  written as the element's payload type serializes; `{ text }` is a run of text, and
  `{ build }` places a node staged before, or a sequence of staged nodes. The extension builds the MathML of a formula
  this way, as HTML construct nodes (`flm.pres.html.tag`) with the lowered text of each
  `\text{…}` placed inside its `mtext` element.
- **Style and script definitions.** `b.style_def(new StyleDef(id, parts, docs))` and
  `b.script_def(new ScriptDef(id, parts, docs))` (from `flm:core/registry`) take the
  parts `DefContent.Inline(text)`, `DefContent.Url(address)` and `DefContent.Table(name)`,
  the last one a [part supplied by a
  table](crate::guide::rendering#style-and-script-definitions). Such a table is declared
  with `b.definition_text_table(name, docs)` and holds one text, which a stage writes with
  `out.table(name).push(text)`. The extension's `load-in-browser` mode lists the TeX packages the
  document uses in its MathJax configuration that way.
- **Peer declarations.** `b.peer_backend(name, docs)`, `b.peer_table(name, docs)` and
  `b.peer_element(name, docs)` declare a backend, a table or a presentation element that
  another feature owns ([peer declarations](#peer-declarations)). The extension declares
  the four standard backends, the anchors and counter tables, and the LaTeX family's
  construct elements.
- **The registry digest.** `b.digest_input(text)` gives the UTF-8 bytes of the string
  `text` to the [registry digest](crate::model::digest), as
  [`FeatureBuilder::digest_input`](crate::core::registry::FeatureBuilder::digest_input)
  does for a compiled feature. The extension gives its configuration, written as JSON,
  since the `preamble` and its other settings change the output in ways its declarations
  do not show.
- **A table that refines a capability.** `b.table_refining(name, parent, docs)` declares a
  table whose capability refines `parent`, so that writing it satisfies a demand for the
  parent ([refinement](crate::guide::pipeline#refinement)). The extension's table
  `math-mathjax.rendered`, the MathML of each formula, refines `flm.math.rendered`.
- **The library of mathematics.** The module `flm:stdlib/features/math` offers the `math`
  feature's names (`MATH`, `ENVIRONMENT`, `CONTENT`) and the plain functions of its library
  ([`math`](crate::stdlib::features::math)): `equation_lines`, `line_frames` (each line's
  anchor and number), `stage_tag_content`, the LaTeX parts `group_opening`,
  `environment_opening`, `line_closing` and the others, the line writer `stage_lines`,
  which writes an environment's lines in the recomposed LaTeX, and the newline rule
  `normalize_line_newlines`, which a writer of an environment's lines as text applies to
  each line so that no blank line is left where a `\label` stood on a line of its own;
  `flm:stdlib/features/userdefs` offers `write_math_run`, which writes the content of a
  formula as LaTeX.
- **Engine limits.** The manifest's `extension.js.limits` sets the limits every engine
  instance of the extension is created with, each in place of the host's: `memory_mib`,
  `stack_mib` (below the stack of the threads that run handlers) and `time_s`, per
  handler call. MathJax needs a deeper stack and more memory than the defaults, and one
  call converts every formula of a document, so the extension's manifest writes
  `limits: { stack_mib: 16, memory_mib: 64, time_s: 120 }`: a 120 s time budget per call.
  The memory limit bounds what a handler keeps, not the length of the document it reads:
  the extension's stages restrict their traversals to the elements they look for, and its
  rules pass the content they lower on as sequences ([Traversals and
  sequences](#traversals-and-sequences)).

A feature in JavaScript can also add an output format of its own and rewrite the trees
before they are frozen. Two test extensions of the FLM repository, in the folder
`flm-ext/tests/js/`, show each item below: `typst` writes a document as Typst markup,
and `smartdash` replaces `--` and `---` by dashes.

- **A backend and an output.** `b.backend(new BackendDef(name, native, lowering, emit,
  final_stage))` and `b.output(new OutputDef(name, capability, table, media_type,
  extension))` (from `flm:core/registry`), with the library's lowering stage
  `new LoweringStage(backend)` (from `flm:stdlib/backends/lowering`) and an emit stage
  and a final stage written as stage objects ([Adding an output
  format](#adding-an-output-format)). An output made from the files of another output
  lists that output with `.made_from(name)` on its `OutputDef`. The name of a backend or
  an output is the extension's stem itself or begins with the stem and a dot. `typst` registers the
  backend and the output `typst`, which the `flm` program renders with the workflow `typst` (`-p typst`).
- **The standard tables by name.** `b.table_named(name, type, docs)` declares a table of
  one of the library's types, `StandardTable.LoweredTrees`, `LoweredPieces`, `Regions`
  or `ArtifactSet`; the name `flm.lowered.<backend>` that the library's lowering stage
  writes is accepted for a backend of the extension. A stage reads a table of lowered
  trees as an object (`cx.get(name).lowered`: `trees()`, `tree(id)`, `requires(id)`,
  `rounds(id)`, and `node_at(addr)`, the node at an address of a lowered tree in the form a
  position mark of `flm.output.text`'s projection writes it, `tree#0/5`, or `null`), pushes artifacts into an artifact set as data (`Artifact` and
  `ArtifactId`, from `flm:core/artifact`, each file's content a text, `{ text }` or `{
  base64 }`; `media_type_of(extension)` answers the media type the library knows for a
  file extension), and reads an artifact set as data, each file with the path the host
  writes it at (`cx.get(name).projection`; see [Adding an output
  format](#adding-an-output-format)).
- **The nodes of a lowered tree.** Besides the methods of any node, `node.payload()`
  answers a presentation node's payload as data, and `node.slot_count()`,
  `node.slot_name(index)` and `node.slot_content_nodes(index)` read its slots by
  position (a list's labels and items). `flm:lang/structural` names the structural
  elements (`TEXT`, `GROUP`, `PARBREAK`, …).
- **Presentation elements of your own.** `b.presentation_element(name, docs)` declares
  one whose payload is any data value ([Presentation elements of your
  own](#presentation-elements-of-your-own)). `typst` declares `typst.pres.callout`, which
  its emit stage writes from the payload's field `kind`.
- **Rewrite stages.** `b.rewrite_stage({ decl, needs, restage(node, cx, rs) })`, with
  `RewriteDecl` (from `flm:core/stage`) and `Restage` (from `flm:techy/transform`): the
  library calls `restage` once per node and the handler keeps the node or replaces it
  ([Tables and stages](#tables-and-stages)). `smartdash` registers the rewrite stage
  `smartdash.dash`, which publishes `smartdash.dashed`, and the workflow `smartdash`
  demanding it.

A feature in JavaScript cannot yet give its output regions, so a compose template cannot
assemble that output, nor have the library's pieces stage run for its backend; and it
cannot declare a native-set implication, nor an ordering edge between two stages of other
features (its own stages and rewrite stages order themselves through their needs, `after`
and `before`). It joins a collection, such as the `flm.validated` the standard workflows
demand, with `b.collection_member` (below).

A feature in JavaScript also declares numbered and referenceable constructs, the way the
standard features declare theorems and headings. The two test extensions `exercises` (a
numbered environment `\begin{exercise}…\end{exercise}` with references and a command
`\hint` legal inside it alone) and `myhead` (a numbered heading listed in the table of
contents, whose number is written through a template) use the items below; their files
are in the folders `flm-ext/tests/js/exercises/` and `flm-ext/tests/js/myhead/` of the
FLM repository, and [Number a construct of your
own](#number-a-construct-of-your-own) gives the steps of `exercises` in Rust and in
JavaScript.

- **Aspects answered by handlers.** The aspects
  [`Referenceable`](crate::model::aspects::Referenceable) (the reference points of an
  occurrence) and [`Sectioning`](crate::model::aspects::Sectioning) (its level, whether
  it is listed in the table of contents, and its title there) are objects of the script:
  `Aspect.Referenceable({ points(node) { … } })` and `Aspect.Sectioning({ level(node) {
  … }, in_toc(node) { … }, toc_title(node) { … } })` (from `flm:model/element`), given in
  the element's specification with `new ElementSpec(name).with(aspect)`, or attached to
  an element of another feature with `b.attach(element, aspect)`. `points` answers a list
  of `RefPoint`s, built with the classes of `flm:model/aspects` (`RefPoint`,
  `NumberSource`, `AnchorPolicy`, `ContentRef`, `AcceptedRefTypes`). The stage that asks
  for the aspect calls the handler, on the thread that runs it, with the occurrence's
  node alone. A handler that fails is reported nowhere: the occurrence then has no
  reference point, or the level 0, is not listed, and has no title. The package `intoc`
  of `exercises` attaches a `Sectioning` aspect to the exercises of the package `_`, so
  that the titled exercises are listed in the table of contents.
- **Labels and references.** The module `flm:stdlib/features/refs` offers the
  [`refs`](crate::stdlib::features::refs) feature's names (`ANCHORS`, `SAFE_LABELS`,
  `LABEL_PACKAGE`, …) and its helpers: `label_fields_arg()`, the argument that holds the
  `\label` fields written after a construct; `label_uses(node)` and
  `point_labels(uses)`, which read those fields into a point's labels; `stage_label` and
  `stage_label_group`, which write the labels into the recomposed LaTeX. A rule reads the
  anchors table with `lw.get(ANCHORS)`, which answers `{ anchors }`, whose `id(point)`
  answers the anchor of a reference point (a point is written `{ addr, index }`, with
  `lw.addr()` the address of the node being lowered).
- **Numbering.** The module `flm:stdlib/features/numbering` offers the
  [`numbering`](crate::stdlib::features::numbering) feature's names (`COUNTERS`,
  `COUNTERS_SLOT`, `STYLES_SLOT`, …) and the classes of its declarations (`CounterDecl`,
  `CounterStyleDecl`, `Within`, `PrefixWords`, `FormatOptions`, …). A rule reads the
  counter table with `lw.get(COUNTERS)`, which answers `{ counters }`, whose
  `format(point, options)` answers the segments of the point's number for
  `lw.splice(cx, segment.content)`, and whose `record(point)` answers the point's record,
  or `null` for a point the document did not number.
- **Values contributed as data.** `b.contribute_to(slot, value)`,
  `b.contribute_first_to(slot, value)` and `b.peer_slot(slot, value)` contribute to
  another feature's service slot (see [Services and service
  slots](#services-and-service-slots)) a value written as data. Five standard slots read
  that data as their own value types: a counter and a counter style
  (`flm.numbering.counters`, `flm.numbering.styles`), a parent set
  (`flm.numbering.parent-sets`), a definition piece and a package definition of the
  recomposed LaTeX (`flm.latex.preamble`, `flm.latex.packages`). The value's own name
  (its `name`, or the `id` of a package definition) must begin with the extension's stem
  and a dot. A value written as data for any other standard slot whose values are not
  data, such as the slot of number writers, whose values carry behavior, fails the
  registry build, which names the slot and the two types.
- **The LaTeX constructs.** The module `flm:stdlib/backends/latex` offers the LaTeX
  family's construct elements (`MACRO`, `ENVIRONMENT`, `RAW`, …), their payload classes
  (`LatexMacroPayload`, `LatexEnvironmentPayload`, `LatexRawPayload`, …), the slot names
  `ARG_SLOT`, `BEGIN_SLOT`, `END_SLOT` and the backend's name `RECOMPOSED_BACKEND`; its
  namespaces `latex.preamble` and `latex.packages` hold the definition pieces and
  packages of the style file. A rule writes a LaTeX construct with
  `lw.pres_slots(cx, element, payload, [[slot, staged], …])`. A feature contributes its
  own piece (`new latex.LatexPreambleDef(name, content, docs)` to `latex.preamble.SLOT`),
  and the rule that writes a construct the piece defines requires it, while it lowers
  with `lw.require(id)` ([`Lowerer::require`](crate::core::lowering::Lowerer::require)),
  or when the rule is selected, with
  [`LoweringDecl::selection_requires`](crate::core::lowering::LoweringDecl::selection_requires)
  (the identifier is `latex.preamble.piece_id(name)`); the recomposed LaTeX backend then
  writes the piece into the style file. The `exercises` extension contributes the piece
  `\newtheorem{exercise}{Exercise}` this way.
- **Scoped packages.** `b.scoped_package(new ScopedPackageDef(name, elements, docs))`
  (from `flm:lang/mint`) declares commands that are available only inside the bodies or
  arguments that name the package (`new BodyDef().scoped(name)`,
  `scoped(name)` on an `ArgDef`); see [Scoped packages](#scoped-packages). The command `\hint` of
  `exercises` is declared this way.
- **Collections.** `b.collection_member(collection, capability)` adds a capability the
  feature declares to a collection another feature declares, such as the collection
  `flm.validated` that the standard workflows demand (see [Capabilities, collections,
  ordering and workflows](#capabilities-collections-ordering-and-workflows)).
- **Build hooks.** `b.late_init({ late_init(lang, diags) { … } })` runs once the
  language is built, with the built language and the registry's build diagnostics
  (`diags.push(diagnostic)`); `b.finalizer({ finalize(b) { … } })` runs in the build's
  second round (see [Build hooks](#build-hooks)). The `myhead` extension checks its
  configured title template in a late-initialization hook.
- **Templates and durable objects.** A feature compiles a template against the built
  language and fills it with values it computes: `compile_template_with(spec, lang, new
  TemplateLanguage(lang))` (from `flm:lang/rewrites/userdefs`) compiles a
  `TemplateSpec`, with the language that `lw.lang()`, `xp.lang()` or a
  late-initialization hook gives; `instantiate(node, template, new
  ValueBindings().with(name, tree))` instantiates it as a new tree, giving each extra
  placeholder a tree (a `Tree`, such as a number segment's `content`), and
  `lw.splice(cx, tree)` places that new tree in the rule's output (see [Templates with
  values the feature computes](#templates-with-values-the-feature-computes)). The template language and
  the compiled template are *durable objects*: FLM keeps them for the feature as long as
  the registry is in use, and a script may use them on any thread and in any later call.
  Compiling a second time with an equal specification answers the same object without
  compiling the text again, so a rule may compile its template at every use. The
  `myhead` extension writes its heading's number this way.
- **Computed placeholders.** An expansion hook gives the extra placeholders of its
  definition (`extra_placeholder(name, substitution)` on a `Definition`) values it
  computes at each use. It lists the placeholders of the templates it instantiates:
  `template.placeholders()` answers one `{ written, target, substitution }` per
  placeholder, the target `{ argument: index }`, `"body"` or `{ extra: name }`, and
  `substitution` the text written between the brackets of `#[…]{name}`, trimmed, or
  `null` when there are none; `variant.defaults()` answers the default values of the
  arguments as `[index, template]` pairs, whose placeholders count too. It then fills
  `new ExtraValues()` (from `flm:lang/rewrites/userdefs`) under each name and
  substitution text it found: `template(name, substitution, template)` gives a compiled
  template (one that `compile_template_with` answered, or the variant's template or one
  of its default values), `tree(name, substitution, tree)` a tree (a `Tree`), and
  `no_value(name, substitution)` no value. `values.over(new
  DefinitionBindings(node, variant))` answers the bindings that
  `xp.instantiate(cx, node, variant.template(), bindings)` takes: an extra placeholder
  is given its value from `values`, and the arguments and the body from the use site; a
  name and a substitution text that `values` does not hold make the use an error (see
  [Templates with values the feature
  computes](#templates-with-values-the-feature-computes)).

### Host services

An engine instance reaches nothing outside itself. What an extension needs from outside
(a file beside the document, a file on the network, a program installed on the machine)
it reaches through a *host service*: a named service the program offers to extensions,
which a package declares and a handler calls. The `flm` program offers four:

- `files` reads a file given by a path with its root: a file of the extension's folder,
  of another extension the document uses, of the program's own files, of the document's
  folder, or of the folder in which the program runs. It reaches no network;
- `download` downloads the file at an `https` address, and keeps it in the program's
  cache;
- `cache` reads and stores values in the program's cache;
- `programs` runs a program installed on the machine, which may do anything the user
  running `flm` may, the network included.

A program embedding FLM offers the ones it registers (see [Host services for
extensions](crate::guide::embedding#host-services-for-extensions) in the guide to
embedding FLM); a program built on the host library `flm-host` offers `files` and `cache`
always, `download` when it gives a downloader, and `programs` when it asks for it. No
service offers a clock or random numbers.

**The declaration.** A package lists the services its handlers call under the key `host`
of its package object:

```javascript
ext.package("_", {
  host: ["files"],
  features: { /* … */ },
});
```

A package that declares a service the program does not offer does not load: the error
names the package, the extension and the service, and lists the services the program
offers. The list enters the registry digest, so adding a service to it is a change of the
extension. A handler reaches a declared service only: a name the package did not
declare is refused, even when the program offers it.

**The call.** A stage's context, a citation provider's context and a template module's
context answer `cx.host(name)`: the service, as an object valid for the handler call.
The service `files` is an object with the method `read_text(path)`; any other
service is an object with the method `call(method, args)`, the arguments and the answer
being data. A failure of the service is thrown as an `FlmError` of the kind `host`, whose
text begins with the service and the method (`` `files.read_text`: … ``).

**The service `files`** reads the text of a file at a path with a root, written
`ROOT:PATH`:

- `cx.host("files").read_text("self:data/names.json")` reads a file of the extension's own
  folder (an extension of one file has none);
- `cx.host("files").read_text("ext+NAME:templates/head.html")` reads a file of the
  extension that the use name `NAME` found, as an entry of `use` writes it;
- `cx.host("files").read_text("doc:bib.json")` reads a file of the document's folder: the
  folder of the input file, or the current folder for a document given as text;
- `std:` reads a file of the program's own files, and `cwd:` a file of the folder in which
  the program runs.

A path with no root is refused, and the message gives the form to write. An `https:`
address is refused too: it is read through the host service `download` (below). A module
names a file beside itself with the helper `path` of `flm:host`, which joins a relative
path to the folder of the module that calls it and returns the path under `self:`: in
the module `templates/html/tiny.js`, `path(import.meta, "./head.html")` is
`"self:templates/html/head.html"`. The engine sets the property `path` of `import.meta`
to the module's path inside the extension.

The path is written with `/` between names, and follows the rules of [Paths with a
root](crate::guide::command_line#paths-with-a-root) in the command-line guide. Under
`self:`, `ext+NAME:` and `std:`, the path is relative to the folder and must stay inside
it ([Paths inside an extension](#paths-inside-an-extension)). Under `doc:` and `cwd:`, the
path is read as a path written in the document is ([the command-line
guide](crate::guide::command_line#paths)): relative to the folder or absolute; a `..` may
climb above the folder, and a symbolic link may lead anywhere. The answer is the file's
text, or `null` when there is nothing at the path; a file that is not UTF-8 text is
refused. A file is read when the handler calls, during the build: the program records the
document's files read this way among the files of the build, so the live preview (`flm
watch`) builds the document again when one of them changes. A script receives text only;
the files a template module ships are read by FLM itself, as bytes ([A compose template
written as a module](#a-compose-template-written-as-a-module)).

**The service `programs`** finds a program installed on the machine and runs it in a
fresh temporary folder. The `flm` program offers it to every document; a program embedding
FLM offers it only when it asks for it. Its two methods:

- `cx.host("programs").call("find", { names, folders })` answers the path of a program, or
  `null`. The names are tried in order (`["gs", "gswin64c"]`); for each name, the folders
  of the environment variable `PATH` are searched (on Windows, with each extension of
  `PATHEXT` added to a name that has none), then the folders of `folders`, optional, in
  their order. In a folder of `folders`, `*` stands for any run of characters inside one
  folder name (`/opt/gs*/bin`, `/C:/Program Files/MyUtil*/bin`); where several folders
  match, the one with the highest version comes first, runs of digits being compared as
  numbers (`gs10.02.1` before `gs9.56.1`). A name that holds `/` is a path.
- `cx.host("programs").call("run", { program, args, files, stdin, collect, timeout_ms, cache })`
  makes a fresh temporary folder, writes `files` into it (a map from a relative path to
  `{ text }` or `{ base64 }`, the forms of a file's content in an artifact, base64 being
  written with the standard alphabet and padding), starts `program` (a path, as `find` answers it, or a name
  looked up in `PATH`) with the list of texts `args` in that folder, writes `stdin` to its
  standard input when given, and waits for it at most `timeout_ms` milliseconds (60000 when
  not given). It answers `{ status, timed_out, stdout, stderr, files }`: the exit status
  (`null` when the program was ended by a signal), `timed_out` `false`, the text the
  program wrote on its two outputs, and, for each path of `collect` at which there is a
  file after the run, `{ text }` when the file is UTF-8 text and `{ base64 }` otherwise.
  The folder is then removed. A status other than 0 is an answer like any other. A program
  that runs past its time is stopped, and the answer is `{ status: null, timed_out: true,
  files }`: its output is not waited for, and `files` is read as after any run. A program
  that cannot be found or started is an error naming the extension and the program. A
  path of `files` or `collect` is relative to the folder and written with `/` between
  names; one that is absolute, whose `..` climbs above the folder, or that names the
  folder itself is refused. The optional `cache` gives the run cache folders that
  persist from one run to the next (see [Cache folders of a program](#cache-folders-of-a-program)).

Every path given to the service `programs`, and the path `find` answers, is written as a
path in a document is ([the command-line guide](crate::guide::command_line#paths)): `/`
between names on every system, and on Windows an absolute path begins with its drive
(`/C:/Program Files/gs/bin/gswin64c.exe`); the service converts it where it calls the
system. The arguments `args` are given to the program as they are written.

The service does not keep the result of a run: the program runs at every build, and a
change to a file it reads outside its folder does not make the preview build again. The program is not
confined: it runs with the rights of the user running FLM, and the temporary folder only
gives it a place to work. On Linux, macOS and other Unix systems, a program past its time
is stopped together with the programs it started (LuaLaTeX, started by `latexmk`, for
instance), and so it is when Ctrl+C, `Ctrl+\` (the quit signal), the closing of the
terminal or the signal `SIGTERM` ends the `flm` program; on Windows, only the program that
the service started is stopped at the end of its time.

**The service `download`** downloads the file at an address that begins with
`https://`. Its one method:

- `cx.host("download").call("get", { url })` answers `{ content, media_type, warning }`:
  `content` is `{ text }` when the file is UTF-8 text and `{ base64 }` otherwise (base64
  in the standard alphabet with padding), `media_type` is the media type that the server
  states, or `null`, and `warning`, present only when there is one, is a text for a person
  to read, for instance when the file answered is a kept copy that could not be
  downloaded again.

The program keeps each downloaded file in its cache for seven days, shared by all
documents (the cache `flm.host.download.files`), and answers a kept file without a
request. After that time, it downloads the file again; when that download fails, it
answers the kept copy with a warning once the copy is past its seven days. While the
program runs, an address whose download failed is not requested again for five minutes.
A download waits at most 60 seconds, takes at most 32 MiB and follows at most five
redirects, each to an `https` address. An address that does not begin with `https://`,
and a download that gives no file, are refused, as errors of the kind `host`.

The `flm` program always offers `download`. A program built on `flm-host` offers it only
when it gives a downloader (see [Host services for
extensions](crate::guide::embedding#host-services-for-extensions)); a package that
declares the service does not load in a program that does not offer it.

**Install extensions from trusted sources only.** An extension runs code, and through the
service `programs` it can run any program on the machine with your rights. The folder
`_flmextensions` beside a document comes with the document: building a document received
from someone else runs the extensions in its folder. Building a document can also contact
any server that the document or its packages name: the addresses that its compose
templates download, those that its extensions give to the service `download`, and the
servers of the cited works.

### Caches of an extension

An extension that does costly work, such as typesetting a formula or running LaTeX, can
keep its results in the program's cache, so that a later build does not do the work
again. The extension declares each cache in its package, and its handlers reach the cache
through two host services: `cache`, for *values*, and `programs`, for a *folder* that a
program it runs keeps from one run to the next. The `flm` program keeps the caches in one
folder for all documents ([The cache](crate::guide::command_line#the-cache) in the
command-line guide), and its command `flm cache` lists and removes them.

A cache saves work and never changes its result. A value depends only on its key (and on
the document, for a cache kept per document), so a build gives the same output with an
empty cache and with a full one. A handler therefore gives as the key everything the value
depends on. A cache may also be empty at any build: the program may keep no cache, or
may have removed the value, so a handler that finds nothing does the work as on a first
run.

#### Declaring caches

A package declares its caches under the key `caches` of its package object, a map from
a cache's name to its declaration, beside the services its handlers call:

```javascript
ext.package("_", {
  host: ["cache"],
  caches: {
    "typeset.mathml": {
      version: 1,
      values: { engine: "sqlite" },
      unused_s: 90 * 24 * 60 * 60,
      cost_ms: 20,
      scope: "shared",
    },
  },
  features: { /* … */ },
});
```

A cache's name is made of segments of lowercase ASCII letters, digits, `-` and `_`,
joined by `.` (`typeset.mathml`). The keys of a declaration:

| Key | Value |
|---|---|
| `version` | a whole number, at least 1; each version has data of its own, so a change to how the values are made comes with a new version |
| `values` | a values cache: `engine` (`jsonl`, `files` or `sqlite`; `sqlite` when absent) and `blobs` (whether a value has blobs; `false` when absent) |
| `folder` | a folder cache, an empty map `{}`; one build at a time uses the folder |
| `unused_s` | the values are *stable* (the same if produced again from their key): the time, in seconds, after its last use at which a value, or the folder, is removed; `"unlimited"` for never |
| `lifetime_s` | values only: the values are *volatile* (they could differ if produced again, such as data fetched from a server), and each is due for a refresh after this time, in seconds |
| `expiry` | with `lifetime_s` only, optional: `stale_percent` (the part of the lifetime after which a refresh is preferred, 80 when absent), `jitter_percent` (the largest shift of a value's expiry, which spreads the refreshes of values stored together, 15 when absent), `grace_s` (the time after its expiry during which a value is kept for use when it cannot be produced again; 14 days when absent, `"unlimited"` for never removed by age) |
| `cost_ms` | the estimate of the time, in milliseconds, needed to produce one value, or the folder's content, again; at least 1 |
| `scope` | `shared` (one instance for all documents) or `document` (one instance per document) |

Exactly one of `values` and `folder` is given, and exactly one of `unused_s` and
`lifetime_s`; a folder takes `unused_s`. When the cache must be made smaller, the program
removes first the data that is largest, least recently used and quickest to produce
again, which `cost_ms` estimates. The engine `jsonl` holds every value in memory and
takes no blobs; `files` keeps each value in files of its own; `sqlite` keeps the values
in one database, and the program keeps them with another engine when it offers no SQLite.

A declaration of the wrong shape fails the extension's load, with a message that names the
extension, the package and the cache, and so does a declaration that the program's cache
refuses (a name too long, the engine `jsonl` with blobs). The declarations are not part of
the registry digest, since a cache changes no output. In the program, the cache's name is
`flm.ext.STEM.NAME`, where `STEM` is the extension's stem in lowercase, `@` left out and
`/` written `.` (`flm.ext.math-mathjax.typeset.mathml`). Its data is kept apart for each
extension's identity (the path of its manifest, for an extension found in a folder), so
two extensions of the same name in two folders never share a cache, and an extension
updated in place keeps its caches.

A Rust extension (see [A Rust extension compiled into a
program](#a-rust-extension-compiled-into-a-program)) declares the same caches with
`Package::caches`, which takes pairs of a name and a typed declaration
(`flm_ext::host::CacheDeclaration`).

#### The service `cache`

The service `cache` reads and stores the values of a values cache that the caller's
package declares. Every method takes `cache`, the cache's name; a name that the package
does not declare, or that it declares as a folder, is refused.

- `cx.host("cache").call("get", { cache, key, blobs })` answers `null` when the cache
  holds no value under `key`, else `{ record, blobs, freshness, refresh }`. `blobs`,
  optional, lists the names of the blobs to read with the record.
- `cx.host("cache").call("put", { cache, key, record, blobs, cost_ms, lifetime_s })`
  stores a value and answers `null`. `blobs`, `cost_ms` and `lifetime_s` are optional.
- `cx.host("cache").call("remove", { cache, key })` removes the value under `key` and
  answers `null`.

A key is any JSON value: the service stores the value under a digest of the key's JSON
text, the members of each object taken in the order of their names, so a key may be as
large as the value's inputs. `record` is any JSON value. A *blob* is binary data stored
with the record under a name (1 to 64 characters among the lowercase ASCII letters, the
digits, `-`, `_` and `.`, not beginning with `.`). `blobs` of `put` is a map from a
blob's name to `{ text }` or `{ base64 }`, the forms of a file's content in an artifact,
and `get` answers each blob in one of the two forms: `{ text }` when its bytes are UTF-8
text, `{ base64 }` otherwise. Both forms stand for bytes, so a handler reads a blob in
either form, whichever form it stored it in. `cost_ms` is the time the value took to
produce, for a value whose cost differs from the declaration's.

For a volatile value, `freshness` is `"fresh"`, `"stale"` (a refresh is preferred) or
`"expired"` (a refresh is required), and `refresh` says whether the handler should
produce the value again and store it; for a stable value, `freshness` is `null` and
`refresh` is `false`. `lifetime_s` of `put` gives one volatile value a lifetime other than
the declaration's. A value is never refused because of its age: a handler that cannot
produce a value again, because a server cannot be reached for instance, uses the kept
value, and reports a warning when the value is `"expired"`.

An argument of the wrong shape is refused, as an error of the kind `host`. Nothing else
is: when the program's cache fails, `get` answers `null` and `put` stores nothing, and the
program reports the failure in its own log, never as a problem of the document. During
one build, every call of the extension reaches one session of the cache, so a value
stored earlier in the build is read later in the same build.

For instance, the stage of `math-mathjax` asks the cache for each formula before it
typesets it, and stores the MathML that MathJax returns:

```javascript
const cache = cx.host("cache");
const key = [mathjax.VERSION, config.packages, config.preamble, config.export_commands, display, tex];
const kept = cache.call("get", { cache: "typeset.mathml", key });
let mathml;
if (kept !== null) {
  mathml = kept.record;
} else {
  mathml = mathjax.convert(jax, tex, display);
  cache.call("put", { cache: "typeset.mathml", key, record: mathml });
}
```

#### Cache folders of a program

A program that the service `programs` runs works in a fresh temporary folder at every
run. The argument `cache` of `run` gives it folders that persist from one run to the
next: a map from a relative path in the temporary folder to `{ name, cost_ms }`, where
`name` is a folder cache that the caller's package declares, and `cost_ms`, optional, is
the estimate of the time needed to produce the folder's content again after this run.
The extension `profile-pdf-latex` keeps LaTeX's auxiliary files this way, so that
`latexmk` finds them at the next build of the same document:

```javascript
cx.host("programs").call("run", {
  program: "latexmk",
  args: ["-lualatex", "-auxdir=_aux", "paper.tex"],
  files,
  collect: ["paper.pdf", "_aux/paper.log"],
  cache: { "_aux": { name: "latexmk.aux" } },
});
```

At each path of `cache`, the service puts the cache's folder: a symbolic link on Unix, a
junction on Windows. A path of `files` or `collect` may lie under it, and a file written
there is written into the cache's folder. Two paths of `cache` may not be one path, nor
lie one inside the other. After the run, the service removes the links and the temporary
folder, and never a file of a cache folder. When the cache's folder is not available (the
program keeps no folder caches, another build is using the folder, the link cannot be
made, or it leads to no folder), the path is an empty folder, and the program runs as on a first run. The service
never gives the extension the path of a cache folder: the program reaches it through the
relative path alone.

### A citation provider from a script

The `citations` feature asks its citation providers for the entry of each cited key (see
[the citation providers](crate::guide::embedding#the-citation-providers) in the guide to
embedding FLM). A feature in JavaScript contributes one to the feature's slot
`PROVIDERS_SLOT` (`flm.citations.providers`, from `flm:stdlib/features/citations`) as an
object with methods:

- `name`, a text beginning with the extension's stem and a dot, unique among the
  providers one `register` contributes;
- `answer_all(requests, cx)`, which answers every request of one call, or
  `answer(request, cx)`, which answers one; when the object has `answer` alone, it is
  called once per request.

The providers are asked in turn, each about the keys no earlier provider claimed: those
of the feature placed last in the feature order first, each feature's in the order it
contributed them. A package's provider thus comes before the `flm` program's own (that of
the feature `citations-standard`, which leaves the keys none of its record sources takes)
when the package's feature is placed after `citations-standard`, as a package the
document uses is by default. A request is `{ key }`, the key as the author wrote it. The answer
holds one item per request, in order: `null` when the key is not this provider's, `{
error }` when it is and its entry cannot be given (the text, which the citations feature
reports at the key's citations), or `{ entry, identity, warnings }`. The entry is made by
the context: `cx.build_entry(parts)` builds it from parts (`{ text }`, `{ source }` for
FLM text, `{ emphasized: [parts] }`, `{ strong: [parts] }`, `{ link: { address, content:
[parts] } }`), and `cx.parse_entry(source, origin)` parses FLM text, `origin` naming
where the text comes from. `identity`, optional, says which work the key names: two keys
with one identity are one cited work, with one number. `warnings`, optional, is a list of
texts, each reported as a Warning at the key's first citation.

The extension `bibfile` of FLM's repository (`flm-ext/tests/js/bibfile/`) answers the keys
from a JSON file beside the document, read through the host service `files`:

```javascript
import { PROVIDERS_SLOT } from "flm:stdlib/features/citations";

function provider(file) {
  return {
    name: "bibfile.json",
    answer_all(requests, cx) {
      const text = cx.host("files").read_text(`doc:${file}`);
      if (text === null)
        return requests.map(() => ({ error: `expected bibliography entries in a sibling file \`${file}\`` }));
      const records = JSON.parse(text);
      return requests.map(({ key }) => {
        const record = records[key.toLowerCase()];
        if (record === undefined) return null;
        const parts = [{ text: `${record.author}, ` }, { emphasized: [{ text: record.title }] }, { text: ` (${record.year})` }];
        return { entry: cx.build_entry(parts), identity: key.toLowerCase() };
      });
    },
  };
}

// The package `_` declares `host: ["files"]`; its feature's `register`:
register(b, settings) {
  b.peer_slot(PROVIDERS_SLOT, provider(settings.file ?? "bib.json"));
},
```

Since the file is read when the provider is asked, during the build, a change to it makes
the live preview build the document again, with the same extensions.

When the provider's call fails (an exception, a limit of the engine, an answer of another
shape), every key of the call is answered with an error whose text holds "the citation
provider `NAME` of the feature `F` of the package `P` of the extension `S` failed: …",
which the citations feature reports at the key's citations; no later provider is asked
about those keys.

### A compose template written as a module

A compose template may be a JavaScript module rather than a text for a template engine:
its default export is an object that describes the template, chooses the files it ships
when it is applied, and renders the page.

- `name`: the template's name, which a document chooses (`-t NAME`, or the setting
  `compose: {template: NAME}`). It is not under the stem rule, and it must be unique among
  the compose templates of the packages in use, as every template's name.
- `describe(settings)`: answers `{ accepts, requires, config }`, the template's
  description: the pieces it accepts (`"all"` or a list of piece names), the pieces it
  requires (optional) and the default of each of its own settings (`config`), one for
  each setting that its feature declares and no other. It runs inside the `register` of
  the feature that contributes the module, given that feature's configuration, so a
  default may depend on it.
- `files(data, cx)`, optional: answers the files the template ships, chosen when it is
  applied, each `{ name, extension, media_type, text }` (a text the module computes) or
  `{ name, file, media_type }` (a file at a path with a root, as the service `files`
  reads one, `self:` for a file of the extension's folder and `doc:` for one of the
  document's folder, read by FLM as bytes; in this form `media_type` may be left out when
  the file's extension is one the program knows). The program names the files and writes them beside the page.
- `render(data, cx)`: answers the page, a text. `data` is the template's context: `{ html,
  regions: [[name, text], …], pieces: [{ name, place, text, words }, …], metadata,
  config, artifacts: [[name, path], …] }`, `config` holding the template's settings and
  `artifacts` the path of each shipped file, relative to the page's folder (empty when
  `files` runs). A number of `metadata` or `config` must be a whole number.

The feature that contributes the module declares it under the key `templates` of its
feature object, a map from a module's name to `{ output, settings }`: the output the
module serves, and the JSON Schema of its settings, an object schema each of whose
`properties` is one setting with its type, its `description` and its marks, as the key
`settings` of a template's description, but without `default` (`describe` gives the
defaults). The marks apply to what is written for the template, and a key that the
schema lacks is a warning and does not reach the template. For a setting marked
`merge-object-key-values`, the values that the document's sources write are combined key by
key. The default that `describe` gives for such a setting takes no part in that
combining: it is the setting's value when no source writes the setting, and a source that
writes the setting replaces it whole. A module that the feature does
not declare, and a `config` that lacks a declared setting or holds another key, fail the
feature's registration.

A feature contributes the module to the slot `TEMPLATES_SLOT` (`flm.compose.templates`,
from `flm:stdlib/features/compose`) with `b.peer_slot(TEMPLATES_SLOT, module)`. FLM then
contributes the template the description gives, with a template engine of its own whose
name is made of the package's name and the template's, and which calls `files` and
`render`. A document sets the template's settings as any template's, under the
output's name and then the template's: `compose: {template_config: {OUTPUT: {NAME: …}}}`.
Reading the files a module ships, and reading
its own files with `cx.host("files")`, needs `host: ["files"]` in the package object. A
module names a file beside itself with `path(import.meta, "./head.html")` (see [Host
services](#host-services)). A shipped file at an `https` address is downloaded through the
service `download`, which the package then declares too.

The extension `tinytpl` of FLM's repository (`flm-ext/tests/js/tinytpl/`) ships the module
`tiny`: a heading from its feature's configuration, a stylesheet it computes, a partial it
reads from its own folder, and a banner image when the template's setting `banner` names
one. The setting `banner` is marked as a path (`"x-flm-marks": ["path"]`), so the module
receives it with its root (`doc:logo.png` for `banner: logo.png` in the document's front
matter) and ships it as it is:

```javascript
// templates/html/tiny.js
import { path } from "flm:host";

export default {
  name: "tiny",
  describe(settings) {
    return {
      accepts: "all",
      requires: [],
      config: { heading: settings.heading ?? "Tiny", color: "teal", banner: null },
    };
  },
  files(data, cx) {
    const files = [{ name: "style", extension: "css", media_type: "text/css", text: `h1 { color: ${data.config.color}; }\n` }];
    if (data.config.banner !== null) files.push({ name: "banner", file: data.config.banner });
    return files;
  },
  render(data, cx) {
    const regions = Object.fromEntries(data.regions);
    const artifacts = Object.fromEntries(data.artifacts);
    const head = cx.host("files").read_text(path(import.meta, "./head.html")) ?? "";
    const banner = artifacts.banner === undefined ? "" : `<img src="${artifacts.banner}" alt="">\n`;
    const after = data.pieces.filter((piece) => piece.place === "after-content").map((piece) => piece.text).join("\n");
    return `<!doctype html>\n<html>\n<head>\n${head}<title>${regions.title ?? ""}</title>\n` +
      `<link rel="stylesheet" href="${artifacts.style}">\n${regions.styles ?? ""}\n</head>\n<body>\n` +
      `<h1>${data.config.heading}</h1>\n${banner}${regions.content}\n${after}\n${regions.scripts ?? ""}\n</body>\n</html>\n`;
  },
};
```

```javascript
// main.js
import { TEMPLATES_SLOT } from "flm:stdlib/features/compose";
import tiny from "./templates/html/tiny.js";

// The settings of `tiny`; its `describe` gives their defaults.
const TINY_SETTINGS = {
  type: "object",
  properties: {
    heading: { type: "string", description: "The page's heading." },
    color: { type: "string", description: "The color of the heading." },
    banner: {
      type: ["string", "null"],
      description: "An image shown under the heading: its path, relative to the file in which it is written.",
      "x-flm-marks": ["path"],
    },
  },
};

export default function (ext) {
  ext.package("_", {
    host: ["files"],
    features: {
      tinytpl: {
        title: "Tiny page",
        settings: { config: { docs: "The page's heading.", schema: { type: "object", properties: { heading: { type: "string" } } } } },
        templates: { tiny: { output: "html", settings: TINY_SETTINGS } },
        register(b, settings) { b.peer_slot(TEMPLATES_SLOT, tiny); },
      },
    },
  });
}
```

A document `notes.flm` then writes `use: [tinytpl]`, and `flm render -f html -t tiny -o
notes.html notes.flm` writes the page `notes.html` with `notes-style.css` and, when the
setting `banner` is given, `notes-banner.png` beside it: each file the module ships is
named after the page (the stem that `-o` gives), followed by the name the module gives it.
The partial and the banner are read during the build, so the live preview
builds again when one of them changes.

A failure of `describe` fails the feature's `register`, hence the registry build. A
failure of `files` or `render` (an exception, a limit, an answer of another shape, a
shipped file that is not there) fails the template: the Error
`flm.compose.template-failed`, whose text holds "the template module ‘NAME’ of the feature
‘F’ of the package ‘P’ of the extension ‘S’ failed: …", and the output is not made.

### Two examples

The first example is an extension with one package and one feature that has three
settings, one per binding: `shout_suffix`, in the configuration, which `register` reads;
`min_length`, in the option type `wordcount.counting`, set per render; `report_counts`,
in the option type `wordcount.reporting`, set on the document. It declares the macro
`\shout`, whose replacement an expansion hook computes, and a stage that counts each
tree's words into a table (abridged; `helpers.js` exports `count_words`):

```js
// wordcount/main.js
import { StageDecl, Needs, Effect, Scope } from "flm:core/stage";
import { ArgDef } from "flm:lang/mint";
import { chars_text } from "flm:lang/text";
import { Definition, UserDefinition, Expansion } from "flm:lang/rewrites/userdefs";
import { element_name_under, expand_in_tree_rule_for } from "flm:stdlib/features/userdefs";
import { NodeKindName } from "flm:techy/node";
import { count_words } from "./helpers.js";

const object = (key, type) => ({ type: "object", properties: { [key]: { type } } });
const SETTINGS = {
  config: { docs: "What the macros write.", schema: object("shout_suffix", "string") },
  options: {
    "wordcount.counting": { bind: "render", docs: "How words are counted.", schema: object("min_length", "integer") },
    "wordcount.reporting": { bind: "document", docs: "What the count reports.", schema: object("report_counts", "boolean") },
  },
};

export default function (ext) {
  ext.package("_", {
    features: { wordcount: { title: "Word count", settings: SETTINGS, register } },
  });
}

function register(b, settings) {
  const suffix = settings.shout_suffix ?? "";
  const shout = Definition.macro_("shout", [ArgDef.mandatory("text")]);
  const element = element_name_under("wordcount", shout);
  b.element(new UserDefinition(shout).element_def_with(b.feature(), element, {
    expand(node, cx, xp) {
      const text = chars_text(node.argument_content_nodes_named("text")) ?? "";
      return Expansion.Emit([cx.stage_chars(text.toUpperCase() + suffix)]);
    },
  }));
  b.lowering_rule(expand_in_tree_rule_for(element, shout));
  b.table("wordcount.words", "the number of words of each tree");
  b.capability("wordcount.counted", "the words of each tree counted", null);
  b.collection_member("flm.validated", "wordcount.counted");
  b.stage({
    decl: () => new StageDecl("wordcount.count", Effect.Compute, Scope.PerTree)
      .writes("wordcount.words").provides("wordcount.counted"),
    needs: () => new Needs().option("wordcount.counting").option("wordcount.reporting"),
    run(cx, out) {
      const min = cx.option("wordcount.counting").min_length ?? 1;
      let words = 0;
      for (const node of cx.my_tree().root().descendants().kinds([NodeKindName.Chars])) words += count_words(node.chars(), min);
      out.table("wordcount.words").push({ tree: cx.tree_id(), words });
      if (cx.option("wordcount.reporting").report_counts === true)
        out.diags({ id: "wordcount.count", severity: "note", message: `the tree \`${cx.tree_id()}\` holds ${words} words` });
    },
  });
}
```

A document uses it and sets its three settings in its front matter:

```yaml
flm:
  use: [wordcount]
  features:
    wordcount: {shout_suffix: '!', min_length: 3, report_counts: true}
```

A stage runs when something demands what it writes, as every stage does. The table
`wordcount.words` is demanded by no output, so the stage `wordcount.count` also provides
the capability `wordcount.counted`, and the feature adds that capability to the
collection `flm.validated` with `b.collection_member` (see [Capabilities, collections,
ordering and workflows](#capabilities-collections-ordering-and-workflows)). Every
standard workflow demands `flm.validated`, so every render of a document that uses
`wordcount` runs the count and reports its Notes, as it runs the checks of the compiled
features that joined the collection. A feature written in JavaScript joins a collection
as a compiled feature does: the capability is the feature's own, and must begin with the
extension's stem and a dot; the collection is another feature's.

A stage that writes a table which no collection covers runs when a workflow demands its
table. An extension of the engine `data` can define such a workflow:

```yaml
# counting.yaml
extension:
  description: The HTML page with the word count.
flm:
  use: [wordcount]
  workflows:
    counted:
      extends: html
      demands: [flm.validated, wordcount.words]
```

A document that uses `[wordcount, counting]` and is rendered with `-p counted` runs
every stage that the workflow `html` runs, and the stages that write `wordcount.words`.

The second example is an extension of two packages that share one module. The package
`_` defines `\tpmark`; the package `proofs` uses it (`.#_`) and adds `\tpqed`. A
document that lists `twopack#proofs` gets both packages. The two packages share the
extension's engine instance, so the module `./shared.js` is evaluated once in each
instance, for both (abridged):

```js
// twopack/main.js
import { Definition, UserDefinition } from "flm:lang/rewrites/userdefs";
import { element_name_under, expand_in_tree_rule_for } from "flm:stdlib/features/userdefs";
import { mark } from "./shared.js";

function declare(b, definition) {
  const element = element_name_under("twopack", definition);
  b.element(new UserDefinition(definition).element_def(b.feature(), element));
  b.lowering_rule(expand_in_tree_rule_for(element, definition));
}

export default function (ext) {
  ext.package("_", {
    features: { twopack: { title: "Marks", register(b) { declare(b, Definition.macro_("tpmark", []).content(mark("mark"))); } } },
  });
  ext.package("proofs", {
    uses: [".#_"],
    features: { proofs: { title: "Proofs", register(b) { declare(b, Definition.macro_("tpqed", []).content(mark("qed"))); } } },
  });
}
```

### An extension in WebAssembly

An extension in WebAssembly is a folder whose manifest names the engine `wasm` and its
module, one WebAssembly file inside the extension's folder:

```yaml
# wordcount/flmextension.yaml
extension:
  description: Counts words, collects to-do markers, shouts
  engine: wasm
  wasm:
    module: ./wordcount.wasm
```

`extension.wasm.module` is the module's path, relative to the extension's folder ([Paths
inside an extension](#paths-inside-an-extension)), and
`extension.wasm.limits`, optional, sets the limits of the extension's own instances (below).
The module is the extension's one file of code: it is read once, when the extension is
loaded, and its package objects, features and handlers are what its entry points answer,
as a JavaScript extension's are what its main module declares. The module holds code
alone: the manifest and every other file of the extension (a compose template, a data
file) stand beside it in the folder. A module that holds the files of several extensions
is a *collection*, which a program loads itself and which is refused here ([A crate that
holds several Rust extensions](#a-crate-that-holds-several-rust-extensions)).

**The interface between the host and the module.** Every request of the module goes to
the host through one imported function, `flm.call`, which names the request: a call of a
method of the extension API, the lending of an object the host will call back (a stage, an
expansion hook, a lowering rule's body), a line written to `console`. It exports one entry
function, `flm_entry`, which the host calls with the name of an entry point (`define`,
`packages`, `register`, `run_stage`, `expand`, `lower`, …), the stem of the extension the
call is for, and its arguments, and which routes the call by that name. Both directions
are JSON text in the module's memory, in the shapes the JavaScript binding's values have
(an object of the host as its handle, a number, a text, a list, a map). A second import,
`flm.take`, and the exports `flm_alloc` and `flm_free` move that text in and out of the
module's memory. A Rust extension never
writes this interface itself: the guest client of the next section writes it. The
module documentation of `flm_ext::wasm` states it in full, for a module written in
another language.

**What a module reaches.** Nothing but the host's imports: no file, network, clock,
random source or program. A module that imports anything else is refused when it is
loaded. What it needs from outside it asks of the host services its package declares
under `host` ([Host services](#host-services)), through `flm.call`, as any call of the
extension API.

**Limits.** Every handler call has a budget of *fuel*, about one unit per instruction
the module runs, and every instance a memory limit. The host sets both (by default
1,000,000,000 units and 64 MiB); the manifest's `extension.wasm.limits` sets either for
the extension's own instances, in place of the host's: `memory_mib` (MiB) and `fuel`
(units). A call that runs out of fuel stops, and the handler fails with "… must finish
within its budget of N fuel units". A module that asks for memory past the limit is
refused it; when it then stops, as a Rust module's allocator does, the handler fails
with "… must stay within the memory limit of N bytes". After either, and after any other
trap of the module, the instance is replaced once the call returns. A module whose
initial memory is above its limit does not load. The depth of nested calls inside the
module is bounded by the interpreter and cannot be set. The nodes, trees and rows that a
module reads cross as traversals and sequences, as for JavaScript ([Traversals and
sequences](#traversals-and-sequences)): a reply holds at most one group of items, so the
memory a module needs depends on what it keeps.

**Instances.** Each thread that runs a handler of the extension runs its own instance
of the module, made from the module read at load, and an instance that has not run a
feature's `register` with the configuration at hand runs it again first, as a
JavaScript instance does: a feature's `register` declares the same things under the
same names, in the same order, every time it runs with one configuration. Module state
is therefore no channel between handler calls.

### A Rust extension compiled to WebAssembly

An extension written in Rust that a program loads without having been compiled with it
is a WebAssembly module written against the *guest client*: the module `flm_ext::guest`,
under `flm-ext`'s cargo feature `guest`. The guest client holds one module per module of
the extension API, `flm_ext::guest::core::stage` for `flm_ext::api::core::stage` and so
on, with the same items under the same names. A façade (the feature builder, a stage's
context, a node) is a struct whose methods forward each call to the host and answer a
`Result<_, ExtError>`; the handler traits (`Stage`, `Expand`, `Lower`, …) are the
guest's own, with the API's methods and defaults; plain data (`StageDecl`, `Needs`) is
the API's own type. Everything the sections above show for JavaScript — lowering rules,
backends, rewrite stages, citation providers, template modules, host services — a
module reaches under the same names. The `flm` program runs such extensions: its cargo
feature `wasm` is on by default.

**The macro `extension!`.** The crate's root invokes `flm_ext::guest::extension!` once,
with the function that declares the packages; the macro writes the module's exports and
routes the entry `define` to that function. The function declares each package with
`ext.package(name, Package)`, a `Package` holding its `uses`, its `flm` block, its
`templates`, its `host` services and its features, a `Feature` its `title`, `docs`,
`version`, `settings`, its template modules (`template`) and `register`. The word count of the example above, written in
Rust, abridged to `register` and one stage (`flm-ext` is not a dependency of this
guide's crate, so the example is not compiled):

```ignore
// wordcount/src/lib.rs
use std::sync::Arc;

use flm_ext::ExtError;
use flm_ext::guest::core::data::store::StageOut;
use flm_ext::guest::core::registry::FeatureBuilder;
use flm_ext::guest::core::run::StageCx;
use flm_ext::guest::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use flm_ext::guest::techy::node::NodeKindName;
use flm_ext::guest::{Extension, Feature, Package};
use serde_json::{Value, json};

mod helpers;

const WORDS: &str = "wordcount.words";
const COUNTED: &str = "wordcount.counted";

flm_ext::guest::extension!(extension);

fn extension(ext: &mut Extension) {
    ext.package(
        "_",
        Package::new().feature(
            "wordcount",
            Feature::new().title("Word count").settings(settings()).register(register),
        ),
    );
}

fn register(b: &mut FeatureBuilder, _settings: &Value) -> Result<(), ExtError> {
    b.table(WORDS, "the number of words of each tree")?;
    b.capability(COUNTED, "the words of each tree counted", None)?;
    b.collection_member("flm.validated", COUNTED)?;
    b.stage(Arc::new(Count))?;
    Ok(())
}

struct Count;

impl Stage for Count {
    fn decl(&self) -> StageDecl {
        StageDecl::new("wordcount.count", Effect::Compute, Scope::PerTree)
            .writes(WORDS)
            .provides(COUNTED)
    }

    fn needs(&self) -> Needs {
        Needs::new().option("wordcount.counting")
    }

    fn run(&self, cx: &StageCx, out: &mut StageOut) -> Result<(), ExtError> {
        let min = cx.option("wordcount.counting")?["min_length"].as_u64().unwrap_or(1) as usize;
        let tree = cx.tree_id()?.unwrap_or_default();
        let mut words = 0;
        if let Some(my_tree) = cx.my_tree()? {
            for node in my_tree.root()?.descendants()?.kinds(&[NodeKindName::Chars])? {
                words += helpers::count_words(&node?.chars()?.unwrap_or_default(), min);
            }
        }
        out.table(WORDS)?.push(json!({ "tree": tree, "words": words }))?;
        Ok(())
    }
}

// `settings()` answers the feature's settings declared as data, the JavaScript
// example's `SETTINGS`; `helpers.rs` holds `count_words`.
```

**Building the module.** The crate is of the type `cdylib` (`[lib] crate-type =
["cdylib"]`), depends on `flm-ext` without its default features and with the feature
`guest` alone, and its release profile has `panic = "abort"` (a small module also asks
for `opt-level = "s"`, `lto = true` and `codegen-units = 1`). With the target installed
(`rustup target add wasm32-unknown-unknown`), it is built with

```text
$ cargo build --target wasm32-unknown-unknown --release
```

which writes `target/wasm32-unknown-unknown/release/wordcount.wasm`; that file, copied
beside the manifest, is the extension's module. A handler that returns `Err` fails with
that error, as a compiled feature's handler does; a panic stops the module, and the
handler fails with the panic's message.

**From a crate written against `flm_ext::api`.** A crate written against the extension
API moves to the guest client mechanically: the module paths `flm_ext::api::…` become
`flm_ext::guest::…`, a façade type in a signature becomes the struct of the same name
(`&dyn StageCx` is `&StageCx`, `&dyn Node<'_>` is `&Node`), and a call that crosses to
the host answers a `Result` where the API's answers its value (a `?` more). A list of
nodes or of staged nodes of the API is a sequence in the guest client (`Nodes`,
`StagedNodes`), and an item of a traversal is a `Result` ([Traversals and
sequences](#traversals-and-sequences)). The module
documentation of `flm_ext::guest` states how each item of the API appears in the guest,
and names the few places where the move is not mechanical.

**What shipping a Rust extension this way means:**

- it is one `.wasm` file beside a manifest `engine: wasm`, found on the search path like
  any extension;
- it runs sandboxed: no file, no network, no clock, nothing but the host's imports and
  the host services its package declares;
- it is one file for every platform and every Rust toolchain, with no interface to keep
  stable but the JSON shapes of the extension API;
- every call of the API crosses as JSON text, so a loop over many nodes runs slower than
  the same loop compiled into the program;
- its author builds it with `cargo build --target wasm32-unknown-unknown --release` and a
  release profile with `panic = "abort"`;
- a program never loads a dynamic library as an extension: a Rust extension that is not
  compiled into the program is a WebAssembly module, and the same crate can also be
  compiled into a program (next section).

### A Rust extension compiled into a program

An extension written in Rust against the guest client can also be compiled into a
program, as a Rust library the program links, instead of being loaded as a WebAssembly
module. The program then runs the extension with the engine `native`: the module
`flm_ext::native`, under `flm-ext`'s cargo feature `native`. Nothing else changes for the
extension: it declares its packages, features and handlers as the section above shows,
and a document lists its packages under `use` as it lists any extension's.

**One crate for both forms.** The extension's source is the same in both forms: it is
written against `flm_ext::guest`, its crate depends on `flm-ext` with the feature `guest`
alone, and its root invokes the macro `extension!` once. The guest client alone chooses
how the extension's calls reach FLM, by whether `flm-ext`'s cargo feature `native` is on in
the build:

- without `native`, the crate compiled for `wasm32-unknown-unknown` is a WebAssembly
  module, and every call of the API crosses as JSON text through the module's import (the
  section above);
- with `native`, which a program that carries the engine `native` turns on, the crate is
  a Rust library of that program, built for any target, `wasm32-unknown-unknown`
  included (a program that runs the library in a web browser, for instance); every call
  of the API is a direct, typed call of the extension API (`flm_ext::api`) in the same
  process: the guest client converts the extension's Rust values into the API's, calls
  the API's method, and converts its answer back, with no JSON value written or read.
  FLM's calls of the extension's handlers are direct calls too, their arguments and
  replies Rust values. Only the data that is JSON by nature stays JSON: a feature's
  settings, which its `register` and its template modules' `describe` receive as a
  `serde_json::Value`, and the declarations of the extension's packages.

In both forms, the calls reach the same code on FLM's side: a façade stands for FLM's
object by the same handle, valid for the handler call that received it, and the same
objects of FLM call the extension's handlers.

A crate meant for both forms keeps the default type of its library, which a program
depends on, and builds its WebAssembly form with `cargo rustc --target
wasm32-unknown-unknown --release --crate-type cdylib` (the release profile with
`panic = "abort"` as above).

**Building the WebAssembly form apart from a program.** Within one build, cargo compiles
`flm-ext` once, with one set of features, for every crate of the build. An extension's
WebAssembly module is therefore built in a cargo run where no crate turns on `native`: with
the extension's package selected alone (`cargo rustc -p NAME …`), not in a build of a whole
workspace that also holds a program carrying the engine. A module built in a run where some
crate turns on `native` lacks the functions a module of the engine `wasm` must export
(`flm_entry`, `flm_alloc`, `flm_free`), and the engine refuses it when it loads, with one
message for each function the module lacks, saying which.

**The macro.** On every target, `extension!` writes one public static at the crate's
root, `FLM_EXTENSION` (a `flm_ext::guest::CompiledExtension`), holding the function that
declares the packages and the crate's name and version; for `wasm32`, in a build without
the feature `native`, it also writes the module's exports. A program reaches the extension
through the static. Every extension crate writes a static of the same name, and none
exports a symbol in a build with `native`, so several extension crates link into one
program.

**How a program carries an extension.** A program that compiles an extension in depends
on the extension's crate and on `flm-ext` with the feature `native`. It gives the engine
`native` a *table of code*: a list of rows of the type `flm_ext::guest::NamedExtension`,
each holding the stem that a document's `use` entry gives (`wordcount`) and the crate's
static:

```ignore
use std::sync::Arc;

use flm_ext::guest::NamedExtension;
use flm_ext::native::NativeEngine;

let engine = NativeEngine::new([NamedExtension { stem: "wordcount", compiled: &wordcount::FLM_EXTENSION }]);
let loader = flm_ext::ExtensionLoader::new(sources).with_engine(Arc::new(engine));
```

The engine holds the code alone. One of the program's sources answers the extension's stem
with its manifest, in which `extension.engine` is `native`, and with its other files; the
loader then gives the extension to the engine `native`, which finds the code by the stem.
A manifest that specifies the engine `native` for a stem the engine does not hold is
refused, and the message lists the stems the engine holds. The module documentation of
`flm_ext::native` shows the whole set-up in a compiled example. A program built on the
host library `flm-host` gives the files and the code of its extensions in its request, and
the host library makes the source and the engine ([The extensions a program
offers](crate::guide::embedding#the-extensions-a-program-offers)). The `flm` program
carries the six extensions written in Rust that ship with FLM this way: `flmdoc` ([Writing documentation pages: the extension
`flmdoc`](#writing-documentation-pages-the-extension-flmdoc)), `math-techxt` (the math
processor `techxt`; see [A feature that processes
mathematics](#a-feature-that-processes-mathematics)), `phfpack` ([A Rust extension, end to
end](#a-rust-extension-end-to-end)), `profile-pdf-latex` ([PDF through
LaTeX](crate::guide::command_line#pdf-through-latex)), `profile-tty` ([Text for a
terminal](crate::guide::command_line#text-for-a-terminal)) and `syntax-highlight`. They
are modules of the crate `flm-extensions` ([A crate that holds several Rust
extensions](#a-crate-that-holds-several-rust-extensions)).

**What differs from a WebAssembly module:**

- the extension is the program's own code, with the program's rights: there is no
  sandbox. An extension that reaches the outside through the host services its package
  declares behaves the same in both forms;
- there is no limit: no fuel, no memory limit, so a handler that never returns keeps the
  run from finishing. Nor is the depth of a value bounded: the engines `js` and `wasm` refuse
  a value nested deeper than 127 levels when they read JSON text, and the engine
  `native` reads no text. The traversals and sequences of the guest client ([Traversals
  and sequences](#traversals-and-sequences)) are the same in both forms;
- a JSON value (a `serde_json::Value`) is passed as it is, whether it is an argument of
  a call of the API, the call's answer, or the data a template module's `files` and
  `render` receive: the engines `js` and `wasm` refuse, in each of these, a number that
  is not a whole number or a reserved map key (one beginning with `$`, for instance),
  and the engine `native` passes it. On every engine, the API itself refuses such a
  value where it keeps it as data: an item of an extension's table, a presentation
  node's data payload, a diagnostic's data, the data contributed to a service slot;
- every call of the API is a direct call in the same process, with no JSON value written
  or read, so a loop over many nodes runs without the cost of JSON;
- a panic in a handler, or in FLM while it answers one of the handler's calls, fails the
  handler with the panic's message ("… must run without a panic: MESSAGE"), and the
  thread's instance of the extension is replaced, as a module's instance is after a trap.
  A program built with `panic = "abort"` (the strategy of the target
  `wasm32-unknown-unknown`) stops at the panic instead;
- the objects a feature's `register` hands to FLM (stages, rule bodies, hooks) are Rust
  values, dropped when the engine discards an instance (after a panic, or once the
  extension is no longer in use) and when the thread ends; a panic in their `Drop` fails
  no handler, and only Rust's panic hook reports it (by default on standard error);
- a call of the API from a thread the extension started has no host to answer it, and
  fails with `ExtError::Unsupported`;
- the registry's digest takes the extension's name and version, those its
  `CompiledExtension` holds, not its code, where a module's digest takes the module's
  bytes. A change to the extension that keeps the crate's version leaves the digest
  unchanged, as a change to a feature written in Rust does when the feature keeps its
  version string, unless the program's build identity
  ([`RegistryInputs::build_identity`](crate::core::registry::RegistryInputs::build_identity),
  such as a hash of the program's binary) changes with it.

Each thread runs its own instance of the extension, as for a module: the guest runtime's
state (what `define` declared, what each `register` recorded) belongs to the instance, two
extensions compiled into one program never see each other's, and an instance that has not
run a feature's `register` with the configuration at hand runs it again first.

### A crate that holds several Rust extensions

One crate can hold several extensions written in Rust, each in a module of its own. The
crate `flm-extensions`, which holds every extension shipped with FLM, is built this way.
The crate describes its extensions with a *table of code*: a static slice of rows of the
type `flm_ext::guest::NamedExtension`, each holding an extension's stem (the name a
document's `use` entry gives) and its code, a `flm_ext::guest::CompiledExtension`. Each
module declares the code of its extension as a static, from its declaring function, its
name and its version; the crate's root lists the rows and invokes the macro
`flm_ext::guest::extensions!` once, over the table:

```ignore
// src/lib.rs of the crate
pub mod wordcount;
pub mod todo;

pub static COMPILED_EXTENSIONS: &[flm_ext::guest::NamedExtension] = &[
    flm_ext::guest::NamedExtension { stem: "todo", compiled: &todo::FLM_EXTENSION },
    flm_ext::guest::NamedExtension { stem: "wordcount", compiled: &wordcount::FLM_EXTENSION },
];

flm_ext::guest::extensions!(COMPILED_EXTENSIONS);

// src/wordcount.rs
pub static FLM_EXTENSION: flm_ext::guest::CompiledExtension =
    flm_ext::guest::CompiledExtension::new(define, "wordcount", env!("CARGO_PKG_VERSION"));

fn define(ext: &mut flm_ext::guest::Extension) {
    // the packages of the extension, as in the sections above
}
```

The macro `extension!` of a crate that is one extension does the same for a table of one
row: it declares the static `FLM_EXTENSION` and invokes `extensions!` over that row.

A program that compiles the crate in gives the table of code to the engine `native`
([A Rust extension compiled into a program](#a-rust-extension-compiled-into-a-program)).
Compiled for `wasm32-unknown-unknown` in a cargo run where no crate turns on `flm-ext`'s
feature `native`, the crate is a WebAssembly module, and `extensions!` writes its exports.
The host then calls the module's entry `define` with the stem of the extension it loads,
and the module runs the declaring function of the row of that stem. A module whose table
has one row runs that row for any stem, since the folder that holds the module can be
renamed; a module of several rows that holds no row of the stem reports an error that
lists the stems it holds. Every later entry also gives the stem, so one instance of the
module runs several extensions, each with its own state.

**The two WebAssembly outputs.** A crate of several extensions is built for WebAssembly
in one of two ways.

- *The module of one extension, in a folder.* The extension is a folder found by name on
  the search path, as in [An extension in WebAssembly](#an-extension-in-webassembly): its
  manifest, its other files (compose templates, data files, its `README.md`) and the
  module named by `extension.wasm.module`. The module holds the extension's code alone;
  every file of the extension stands beside it in the folder. A crate that guards each
  module with a cargo feature builds this module with the extension's feature alone.
- *A collection.* One module holds several extensions whole: the code of those written in
  Rust, and the files of every one, in the module's custom section `flmextensions`. The
  macro `flm_ext::collection::record!` writes the record of one file in that section
  (the module documentation of `flm_ext::collection` gives the format). A collection is
  not found by name: a program loads it itself, once, and offers its extensions ([The
  extensions a program offers](crate::guide::embedding#the-extensions-a-program-offers)).
  A module found by name in a folder is refused when it holds the section
  `flmextensions`.

For the crate `flm-extensions`, the script `extensions/rust/build-wasm.sh` of the
repository builds both outputs. `build-wasm.sh [--out DIR] [NAME …]` writes the folder
`DIR/NAME/` of each extension written in Rust that it is given (all of them when no NAME
is given; `DIR` is `target/wasm-extensions/` by default). `build-wasm.sh --collection
FILE NAME …` writes one collection, the file `FILE`, whose name ends in
`.flmextensions.wasm`, holding the extensions given: any shipped extension, of the folder
`data/`, `js/` or `rust/`. The script needs the Rust target `wasm32-unknown-unknown`.

## The standard features as worked examples

Every extension point of this chapter is used by the standard features, so the shortest
way to see one in use is to read the feature that uses it:

| feature | what to read it for |
|---|---|
| [`textstyles`](crate::stdlib::features::textstyles) | the smallest complete feature: one element type with four values, one lowering rule, and a set of style names of its own that the rule maps onto the presentation vocabulary |
| [`literals`](crate::stdlib::features::literals) | a family of commands declared from one list, a macro and a special character sequence in the same element type, a rule that emits a text node, and a rule that emits nothing |
| [`headings`](crate::stdlib::features::headings) | element data built from the feature's configuration (one element value per declared heading kind, written under the names of its commands), three aspects on one element, counters and counter styles contributed as peer contributions, a rule that reads the counter and anchor tables optionally, and the peer declarations of a rule on the recomposed LaTeX |
| [`index`](crate::stdlib::features::index) | one table and one stage, and nothing else |
| [`refpoints`](crate::stdlib::features::refpoints) | one table and one stage, whose table two other features require: the stage asks every node of a document for its reference points (the `Referenceable` aspect), and the other stages read the points from its table |
| [`refs`](crate::stdlib::features::refs) | several stages and tables, an external table, a check added to a collection, two elements that refer to reference points (`\ref` and `\hyperref`) with a general rule and a rule for the recomposed LaTeX each, and content built into a synthesized value that a rule splices |
| [`blocks`](crate::stdlib::features::blocks) | a rewrite stage, a capability with two refinements, an ordering edge declared only when the registry holds the capability it refers to, and a configuration fixed when the registry is built |
| [`math`](crate::stdlib::features::math) | declarations restricted to mathematics mode, a capability declared for another feature to provide, and a library of plain functions that other features' rules call |
| [`math_passthrough`](crate::math_passthrough) | a fallback for names that nothing defines, opaque content, a check stage that provides another feature's capability, and rules on every backend, with rules of their own for the recomposed LaTeX, built with another feature's library (see [A feature that processes mathematics](#a-feature-that-processes-mathematics)) |
| [`verbatim`](crate::stdlib::features::verbatim) | verbatim arguments and verbatim environment bodies |
| [`userdefs`](crate::stdlib::features::userdefs) | author-written definitions, a late-initialization hook that compiles them, and the lowering rules created for each definition |
| [`xnotes`](crate::stdlib::features::xnotes) | an argument that refers to another feature's scoped package, a block role read from an argument's layout, reference points built by one public function that other features use too, a service slot of xnote kinds filled by one public function, public functions that a contributing feature's rule calls to stage its marks, and a piece per xnote kind built by a stage of its own, which another stage replaces when a request prefers it (see [An xnote kind of your own](#an-xnote-kind-of-your-own) and [Building a kind's list your own way](#building-a-kinds-list-your-own-way)) |
| [`cells`](crate::stdlib::features::cells) | an environment in a scoped package of its own and, under a setting, available everywhere too; a block role decided by position; an argument parser of its own; a scoped package that adds one special character; a service slot of declarations that hold no code (see [A cell style of your own](#a-cell-style-of-your-own)); one reader of a presentation payload; a float content handler contributed as a peer contribution |
| [`lowering`](crate::stdlib::backends::lowering::LoweringFeature) | the registration of the presentation vocabulary and of the structural elements' default rules |
| [`text`](crate::stdlib::backends::text::TextBackend) | a backend: its native element set, its stages and tables, its render options, its output and workflow, the shared pieces stage created for it, and its output regions |
| [`CheckWorkflow`](crate::stdlib::CheckWorkflow) | a feature that declares only a collection and a workflow over it |

[`stdlib::add_features`](crate::stdlib::add_features) adds them to a package, and
[`StdlibConfig`](crate::stdlib::StdlibConfig) is the configuration of those that take
one.

The sections below are recipes for the extension points that four standard features
offer to other features: numbering a construct, declaring heading kinds, contributing an
xnote kind, and declaring cell styles.

### A feature that processes mathematics

The [`math`](crate::stdlib::features::math) feature introduces mathematics into the
language (the math groups `\(…\)` and `\[…\]`, the display-math environments, their
equation lines and numbers, the text commands) and processes none of it. A *processing
feature* does that, and needs nothing else of `math`. It does four things:

1. **It says what a command of mathematics is**: a fallback for macros and environments in
   mathematics mode ([`FallbackDef`](crate::lang::mint::FallbackDef)), or elements declared
   with `[Mode::Math]`, or both.
2. **It provides the capability**
   [`flm.math.content`](crate::stdlib::features::math::CONTENT) with a check stage of its
   own, and adds its check to the collection `flm.validated`, which every standard
   workflow demands
   ([`collection_member`](crate::core::registry::FeatureBuilder::collection_member)), so
   that every workflow runs it. The `math` feature declares `flm.math.content` and adds
   it to no collection. A feature written in Rust adds `flm.math.content` itself, as
   `math-passthrough` does; an extension adds to a collection only a capability named
   under its own stem, so its check provides a capability of its own beside
   `flm.math.content` and the extension adds that one (`math-mathjax.check`).
   A feature that renders mathematics inside the pipeline also provides a refinement of
   [`flm.math.rendered`](crate::stdlib::features::math::RENDERED), named in its own
   namespace.
3. **It registers lowering rules** for `flm.math` (the element of a math group,
   [`MATH`](crate::lang::structural::MATH)) and for `flm.math.environment`
   ([`ENVIRONMENT`](crate::stdlib::features::math::ENVIRONMENT)) on each backend it
   serves. The rules build what the `math` feature knows of a formula with the functions of
   its library: [`frame::line_frames`](crate::stdlib::features::math::frame::line_frames)
   gives each equation line with its anchor and its number or tag, and
   [`math::latex`](crate::stdlib::features::math::latex) the LaTeX that opens and closes a
   formula and each line. On a backend where it registers no rule, every math group is
   the Error `flm.math.unprocessed` of the `lowering` feature's rule of last resort
   ([`MathGroupRule`](crate::stdlib::backends::lowering::MathGroupRule)), and every
   display-math environment the same Error of the `math` feature's rule of last resort
   ([`unprocessed`](crate::stdlib::features::math::unprocessed)).
4. **Its tables and stages are its own**: nothing in the registry is reserved for
   mathematics.

A processing feature is the feature of a *math processor*, a package of its own beside
the standard features, which process no mathematics. A registry holds one math
processor: two would each provide `flm.math.content` and each register a default rule
for `flm.math`, which is an error. The host chooses a default processor for its
documents, and a document chooses its own with the key `math` of its front matter: a
processor's name, which stands for the package `math-NAME`, or `false` for none
([the packages a document uses](crate::guide::command_line#the-packages-a-document-uses)).
A processor whose package's name has another form is listed under `use`, with
`math: false`.

In Rust, the library's math processor [`math_passthrough`](crate::math_passthrough) is the
worked example: a package of one feature, which uses no other package (the feature's
declarations state what it needs); two fallbacks, a check stage, three rules marked for
every backend (a math group, an environment, an unknown command of mathematics) and two
for the `latex-recomposed` backend.

**A processor that hands its formulas to a typesetter** needs each formula's TeX as a
string, except where the formula holds document text. The `math` library's writer
([`tex`](crate::stdlib::features::math::tex)) writes it from the formula's nodes:
[`group_tex`](crate::stdlib::features::math::tex::group_tex) for a math group and
[`line_tex`](crate::stdlib::features::math::tex::line_tex) for an equation line, each a
list of parts, a piece of TeX or a *hole* where a text command stands. The holes are left
to the processor, which lowers each text command through FLM's rules, so that a reference
inside `\text{…}` is resolved and its style is the document's, and places the lowered
content where the typesetter's output shows the hole. The writer is the library's so that
every processor reads a formula the same way (the nodes written by their source, a
comment as a space, `\ensuremath{…}` as its argument), whatever language the processor is
written in; the extension API mirrors it in each binding.

**A processor that renders inside the pipeline** renders every formula once, in a stage
of its own, into a table that refines `flm.math.rendered`, and its rules read the table:
the problems are reported once, where they are met, and the rendered form does not depend
on the backend. The `math-techxt` extension, written in Rust and compiled into the `flm`
program, is the example: its stage `math-techxt.render` converts each formula's TeX with
techxt, each hole written as `\text{…}` around one private-use character that techxt
carries through unchanged, and splits the rendered text at those characters; its rules on
`text` and `html` stage the rendered lines with each hole's content in a presentation
element of its own ([Presentation elements of your
own](#presentation-elements-of-your-own)). The rendering stage is in a plan only where a
selected rule reads its table, so its problems are reported on those backends alone; a
check of its own, on every workflow, reports what every backend needs, such as an equation
line that holds no mathematics.

**The library's rules under another feature's names.** A processor that writes its
formulas as LaTeX on the LaTeX backends, as LaTeX typesets them better than any other
rendering, registers the rules of `math-passthrough` there under rule names of its own:
[`math_rule_named`](crate::math_passthrough::math_rule_named) and
[`environment_rule_named`](crate::math_passthrough::environment_rule_named) build the
rules that stage `flm.pres.math-passthrough`, and
[`latex::math_rule_named`](crate::math_passthrough::latex::math_rule_named) and
[`latex::environment_rule_named`](crate::math_passthrough::latex::environment_rule_named)
the rules of `latex-recomposed`, each with the library's body and declaration. The
registering feature owns the rule, so the plan's warning on its unchecked output names
that feature; the documentation of each constructor lists the peer declarations the
feature makes beside it. `math-techxt` registers the four on `latex-rendered` and
`latex-recomposed` and writes no LaTeX rule of its own. The extension API mirrors the
constructors in its three bindings: for an extension written in Rust, compiled to
WebAssembly or into the `flm` program, in the guest client's module
`flm_ext::guest::math_passthrough` and its module `latex`, and for one written in
JavaScript in the modules `flm:math_passthrough` and `flm:math_passthrough/latex`.

In JavaScript, the `math-mathjax` extension is the worked example (see [What a feature in
JavaScript adds to the output](#what-a-feature-in-javascript-adds-to-the-output)). Its
`register` follows the same four steps; abridged:

```js
import { StageDecl, Effect, Scope } from "flm:core/stage";
import { CONTENT, ENVIRONMENT, MATH, equation_lines } from "flm:stdlib/features/math";

export default function (ext) {
  ext.package("_", {
    features: {
      "math-mathjax": {
        register(b, settings) {
          // 1. One element per MathJax command, declared with modes([Mode.Math]).
          declare_commands(b, read_commands(/* … */));
          // 2. The check, which provides flm.math.content and a capability of the
          //    extension's own, which joins flm.validated.
          b.capability("math-mathjax.check", "the mathematics checked by math-mathjax", null);
          b.collection_member("flm.validated", "math-mathjax.check");
          b.stage({
            decl() {
              return new StageDecl("math-mathjax.check", Effect.Check, Scope.PerTree)
                .provides(CONTENT).provides("math-mathjax.check");
            },
            run(cx, out) { /* report every equation line that holds no mathematics */ },
          });
          // 3. The rules of MATH and ENVIRONMENT on html, text and latex-recomposed.
          register_rules(b, settings);
        },
      },
    },
  });
}
```

The package says nothing of `math-passthrough`: the math processors `math-passthrough`,
`math-mathjax` and `math-techxt` are independent of one another, and a document uses one
of them. The `flm` program uses `math-mathjax` by default
([the packages a document
uses](crate::guide::command_line#the-packages-a-document-uses)).

### Number a construct of your own

A feature gives its construct a number (shown beside the construct and in every
reference to it) through the [`numbering`](crate::stdlib::features::numbering) feature,
which numbers every reference point that states a number source. A counter
([`CounterDecl`](crate::stdlib::features::numbering::CounterDecl)) is a dotted name under which things are counted in document order, declared by a feature together
with the counter it is numbered within; a counter style
([`CounterStyleDecl`](crate::stdlib::features::numbering::CounterStyleDecl)) says how a
counter value is shown
([counters and counter
styles](crate::guide::concepts_overview#counters-and-counter-styles)). The numbering
feature declares no command and no lowering rule: the feature that owns the construct
declares the counter, states the number source and shows the number. It takes four steps:

1. **Declare a counter style and a counter.** Build a
   [`CounterStyleDecl`](crate::stdlib::features::numbering::CounterStyleDecl) and a
   [`CounterDecl`](crate::stdlib::features::numbering::CounterDecl), whose names are
   dotted and begin with your own prefix, and contribute each with
   [`peer_slot`](crate::core::registry::FeatureBuilder::peer_slot) to the numbering
   feature's service slots `flm.numbering.styles`
   ([`STYLES_SLOT`](crate::stdlib::features::numbering::STYLES_SLOT)) and
   `flm.numbering.counters`
   ([`COUNTERS_SLOT`](crate::stdlib::features::numbering::COUNTERS_SLOT)). The counter
   declares its default counter style, and may be numbered within another counter
   ([`CounterDecl::within`](crate::stdlib::features::numbering::CounterDecl::within),
   with a [`Within`](crate::stdlib::features::numbering::Within)). Because these are
   peer contributions, a registry without the numbering feature drops them, with one Note
   per service slot, and your feature still registers.
2. **State a number source on the reference point.** Your element's
   [`Referenceable`](crate::model::aspects::Referenceable) aspect returns a
   [`RefPoint`](crate::model::aspects::RefPoint) whose
   [`number`](crate::model::aspects::RefPoint::number) is a
   [`NumberSource`](crate::model::aspects::NumberSource): the counter, the counter style,
   and the levels of the counter the point advances (`[0]` for a plain number). Leave the
   number source out for an occurrence that is not to be numbered (a starred form, or a
   setting of your feature's configuration); the numbering feature has no setting of its
   own that turns numbering off.
3. **Show the number in the lowering rule.** The numbering feature writes its counter
   table `flm.counters` ([`COUNTERS`](crate::stdlib::features::numbering::COUNTERS), a
   [`Counters`](crate::stdlib::features::numbering::Counters)). Declare it as a peer
   table ([`peer_table`](crate::core::registry::FeatureBuilder::peer_table)), and declare
   that the rule reads it optionally
   ([`LoweringDecl::reads_opt`](crate::core::lowering::LoweringDecl::reads_opt)). In the
   rule, [`Counters::format`](crate::stdlib::features::numbering::Counters::format)
   writes the number of the point ([`PointId`](crate::model::aspects::PointId): the
   node's address and the point's index among its points), and returns `None` for a
   point the document did not number. Stage each segment
   ([`Segment`](crate::stdlib::features::numbering::Segment)) it returns with
   [`Lowerer::splice`](crate::core::lowering::Lowerer::splice). Where the numbering
   feature is registered, the optional read becomes a required one, and the plan
   schedules the numbering stage. Where it is not, the rule reads no table and shows the
   construct without a number.
4. **Include the `refpoints` feature in the registry.** The numbering stage reads the
   reference points from the table `flm.refpoints` of the
   [`refpoints`](crate::stdlib::features::refpoints) feature, one of the standard
   features. A registry assembled from single features must list it, or every plan
   that schedules the numbering stage fails.

A reference to the point (`\ref`) then shows the number without anything more from your
feature: the `refs` feature reads the counter table for the target's number. A document
changes the numbering through its numbering options
([`NumberingOptions`](crate::stdlib::features::numbering::NumberingOptions)): which
counter a counter is numbered within, and the value it has before it is first advanced.
In the following example, a `\step{…}` command is numbered `(1)`, `(2)`, … by default;
the document gives the counter the value 10 before its first advance, so the two steps
are numbered `(11)` and `(12)`:

```rust
use std::sync::Arc;

use flm_core::techy::core::node::{BuildId, NodeRef};

use flm_core::model::aspects::{
    AcceptedRefTypes, AnchorPolicy, NumberSource, PointId, RefPoint, Referenceable,
};
use flm_core::model::element::ElementSpec;
use flm_core::model::names::RefKind;
use flm_core::model::options::OptionValues;
use flm_core::core::lowering::{
    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use flm_core::core::registry::{
    BuildError, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry, RegistryBuilder, RegistryInputs,
};
use flm_core::lang::Flm;
use flm_core::lang::mint::{ArgDef, ElementDef, SyntaxDef};
use flm_core::stdlib::features::numbering::{
    CounterDecl, CounterStyleDecl, Counters, Delimiters, FormatOptions, NumberingOptions,
    COUNTERS, COUNTERS_SLOT, STYLES_SLOT,
};

/// The data and the `Referenceable` aspect of the element a `\step` node carries. Its
/// only reference point states the number source.
#[derive(Debug)]
struct Step;

impl Referenceable for Step {
    fn points(&self, _node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
        vec![RefPoint {
            kind: RefKind::from("step"),
            labels: Vec::new(),
            malformed: Vec::new(),
            computed: 0,
            anchor: AnchorPolicy::Auto { prefix: "step".to_string() },
            // The construct counts in `example.step`, is shown in
            // `example.style.step`, and advances the number itself (level 0)
            // at every occurrence.
            number: Some(NumberSource {
                counter: "example.step".into(),
                instances: Vec::new(),
                style: "example.style.step".into(),
                advance: vec![0],
                number_format: None,
            }),
            content: None,
            accepts: AcceptedRefTypes::Any,
        }]
    }
}

/// The rule: it writes the point's number, then the text the author wrote.
#[derive(Debug)]
struct StepRule;

impl Lower for StepRule {
    fn lower(
        &self,
        node: NodeRef<'_, Flm>,
        cx: &mut LowerCx<'_>,
        lw: &mut dyn Lowerer,
    ) -> Result<Lowering, LowerError> {
        let point = PointId { addr: lw.addr(), index: 0 };
        // The number of this point, in the counter style its record carries.
        // The segments are taken out of the table before they are spliced,
        // because splicing needs the `Lowerer` mutably.
        let written = lw
            .get(COUNTERS)?
            .and_then(|counters: &Counters| counters.format(point, &FormatOptions::new()))
            .transpose()
            .map_err(|error| LowerError::structure(error.to_string()))?
            .unwrap_or_default();
        let mut out: Vec<BuildId> = Vec::new();
        for segment in &written {
            out.extend(lw.splice(cx, segment.content())?);
        }
        if !out.is_empty() {
            out.push(lw.text(cx, " ")?);
        }
        out.extend(lw.lower_children(cx, &node)?);
        Ok(Lowering::Emit(out))
    }
}

struct Steps;

impl FlmFeature for Steps {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new("steps", "Numbered steps")
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        let owner = b.feature().clone();

        // Step 1. The counter style, `(3)`, and the counter, numbered within
        // nothing.
        let mut style = CounterStyleDecl::new("example.style.step");
        style.delimiters = Delimiters::new("(", ")");
        b.peer_slot::<CounterStyleDecl>(STYLES_SLOT, Arc::new(style))?;
        b.peer_slot::<CounterDecl>(
            COUNTERS_SLOT,
            Arc::new(CounterDecl::new("example.step", "example.style.step").docs("The steps.")),
        )?;

        // Step 2. The element, whose `Referenceable` aspect states the number
        // source.
        let value = Arc::new(Step);
        let element = Arc::new(
            ElementSpec::new("example.step")
                .with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
                .with_value(value),
        );
        b.element(
            ElementDef::new(
                owner,
                ["step"],
                SyntaxDef::Macro { args: vec![ArgDef::mandatory("text")] },
                element,
            )
            .docs("Writes one numbered step."),
        )?;

        // Step 3. The counter table belongs to the numbering feature, which
        // may be absent: a peer table, read optionally.
        b.peer_table::<Counters>(
            COUNTERS.name(),
            "The counter values, read to show a step's number.",
        )?;
        b.lowering_rule(
            LoweringRule::new(
                "example.step.lower",
                "example.step",
                LoweringDecl::new().reads_opt(COUNTERS),
                Arc::new(StepRule),
                DefaultMark::Everywhere,
            )
            .docs("a step lowers to its number, a space, and the text the author wrote"),
        )?;
        Ok(())
    }
}

// Step 4. The standard features include the `refpoints` feature, which the
// numbering stage requires.
let mut builder = RegistryBuilder::new();
builder.use_package(flm_core::stdlib::add_features(PackageEntry::new("std"), flm_core::stdlib::StdlibConfig::new()));
builder.use_package(flm_core::math_passthrough::package());
builder.feature(Arc::new(Steps));
let registry = builder.build(&RegistryInputs::new())?;

# use flm_core::model::doc::{Doc, DocContent, FragmentLayout};
# use flm_core::core::plan::{Overrides, Plan};
# use flm_core::core::run::{Externals, Run, RunOptions};
# use flm_core::lang::{FlmOrigin, FlmSource, ParseOptions, parse_fragment};
# use flm_core::stdlib::backends::text::{self, TEXT_OUTPUT};
let source = Arc::new(
    FlmSource::new("\\step{Mix.} \\step{Bake.}").with_origin(FlmOrigin::none()),
);
let fragment =
    parse_fragment(registry.lang(), source, FragmentLayout::default(), &ParseOptions::default())?;
let mut content = DocContent::new();
content.place(Arc::new(fragment));

// The document gives the counter the value 10 before its first advance.
let options = OptionValues::new().with(NumberingOptions::new().initial("example.step", 10));
let plan = Arc::new(Plan::for_workflow(&registry, text::WORKFLOW, &Overrides::none())?);
let mut run = Run::new(Arc::new(Doc::with_options(content, options)), plan, Externals::none())?;
run.execute(&RunOptions::new())?;

assert_eq!(run.table(TEXT_OUTPUT)?.expect("written").text, "(11) Mix. (12) Bake.\n");
# Ok::<(), Box<dyn std::error::Error>>(())
```

**The same steps in JavaScript.** A feature of an [extension written in
JavaScript](#an-extension-in-javascript) takes the same four steps through the modules
under `flm:`. The test extension `exercises` (the folder `flm-ext/tests/js/exercises/` of
the FLM repository) declares a numbered environment `\begin{exercise}[title]…\end{exercise}`
with `\label` fields, and writes a heading line "Exercise 3 (title)" before the body
(abridged: the extension also declares the command `\hint`, legal inside an exercise
alone, and a LaTeX rule; the files hold the whole):

```js
// exercises/main.js
import { LoweringRule, LoweringDecl, DefaultMark, Lowering } from "flm:core/lowering";
import { ArgDef, BodyDef, ElementDef, SyntaxDef } from "flm:lang/mint";
import { ElementSpec, Aspect } from "flm:model/element";
import { BlockRole, RefPoint, NumberSource, AnchorPolicy, ContentRef, AcceptedRefTypes } from "flm:model/aspects";
import * as refs from "flm:stdlib/features/refs";
import { COUNTERS, COUNTERS_SLOT, STYLES_SLOT, CounterDecl, CounterStyleDecl, FormatOptions, PrefixWords }
  from "flm:stdlib/features/numbering";
import { BLOCK, SPAN } from "flm:stdlib/backends/pres";

const EXERCISE = "exercises.exercise";          // the element
const COUNTER = "exercises.exercise";           // the counter
const STYLE = "exercises.style.exercise";       // its counter style

// Step 2. The reference point of an exercise: its labels, an anchor, and the number
// source naming the counter and the style.
function points(node) {
  const [labels, malformed] = refs.point_labels(refs.label_uses(node));
  return [new RefPoint({
    kind: "exercise",
    labels, malformed, computed: 0,
    anchor: labels.length ? AnchorPolicy.FromFirstLabel : AnchorPolicy.Auto({ prefix: "exercise" }),
    number: new NumberSource({ counter: COUNTER, style: STYLE, advance: [0] }),
    content: null,
    accepts: AcceptedRefTypes.these(["ex"]),
  })];
}

// Step 3. The heading line: the number the counter table writes, then the title.
function heading(node, cx, lw) {
  const point = { addr: lw.addr(), index: 0 };
  const children = [lw.text(cx, "Exercise ")];
  const counters = lw.get(COUNTERS)?.counters ?? null;
  const segments = counters?.format(point, new FormatOptions().without_word().without_delimiters()) ?? [];
  for (const segment of segments) children.push(lw.splice(cx, segment.content));
  if (node.argument_is_provided("title"))
    children.push(lw.text(cx, " ("), lw.lower_arg_named(cx, node, "title"), lw.text(cx, ")"));
  return lw.pres(cx, SPAN, { role: "exercises.heading" }, children);
}

export default function (ext) {
  ext.package("_", {
    // Step 4. The `refpoints` feature is one of the standard features, which a
    // document gets from the host's package `std`.
    features: {
      exercises: {
        title: "Exercises",
        register(b) {
          // Step 1. The counter style, whose words `\ref` writes before the number,
          // and the counter, contributed as data.
          const style = new CounterStyleDecl(STYLE);
          style.prefix_words = new PrefixWords("Exercise~", "Exercises~");
          b.peer_slot(STYLES_SLOT, style);
          b.peer_slot(COUNTERS_SLOT, new CounterDecl(COUNTER, STYLE).docs("The exercises."));
          // Step 2. The element, whose `Referenceable` aspect is an object of the script.
          b.element(new ElementDef(b.feature(), ["exercise"],
            SyntaxDef.Environment([ArgDef.optional("title"), refs.label_fields_arg()], new BodyDef().blocks()),
            new ElementSpec(EXERCISE)
              .with(Aspect.BlockRoleAspect(BlockRole.Block))
              .with(Aspect.Referenceable({ points })),
          ).docs("Writes a numbered exercise, with an optional title; a label of the exercise has the label type `ex`."));
          // Step 3. The counter table and the anchors table, read optionally.
          b.peer_table(COUNTERS, "The counter values, read for an exercise's number.");
          b.peer_table(refs.ANCHORS, "The anchors, read for an exercise's anchor.");
          b.lowering_rule(new LoweringRule("exercises.exercise.lower.default", EXERCISE,
            new LoweringDecl().reads_opt(COUNTERS).reads_opt(refs.ANCHORS).produces(BLOCK).produces(SPAN),
            { lower(node, cx, lw) {
                const anchor = lw.get(refs.ANCHORS)?.anchors.id({ addr: lw.addr(), index: 0 }) ?? null;
                const content = [heading(node, cx, lw), lw.lower_body(cx, node)];
                return Lowering.Emit([lw.pres(cx, BLOCK, { role: EXERCISE, anchor }, content)]);
            } },
            DefaultMark.OnBackends(["html", "text"]),
          ).docs("An exercise lowers to a block: its heading line, then its body."));
        },
      },
    },
  });
  // A second package lists the titled exercises in the table of contents, at level 3,
  // under their titles: a `Sectioning` aspect attached to the first package's element.
  ext.package("intoc", {
    uses: [".#_"],
    features: {
      intoc: {
        register(b) {
          b.attach(EXERCISE, Aspect.Sectioning({
            level(node) { return 3; },
            in_toc(node) { return node.argument_is_provided("title"); },
            toc_title(node) { return ContentRef.ArgumentNamed("title"); },
          }));
        },
      },
    },
  });
}
```

A reference to an exercise then writes the counter style's words before the number:
`\ref{ex:first}` writes "Exercise 1" in the text output, and `\ref[noprefix]{ex:second}`
writes "2". The extension's LaTeX rule writes an exercise into the recomposed LaTeX as
the environment `exercise` that its definition piece `\newtheorem{exercise}{Exercise}`
declares, with the labels and references written by the commands of the recomposed
LaTeX's style file:

```latex
\begin{exercise}[A title]\flmLabels{\label{ref1}}
Solve it. Hint: Think of the first case.
\end{exercise}

See \flmRef{ref1} and \flmRef[noprefix]{ref2}.
```

The [numbering guide](crate::guide::numbering) describes each part in full: what a
counter declaration holds and the checks the registry build makes on it ([declaring a
counter](crate::guide::numbering#declaring-a-counter)), what a counter style is made of,
how a counter is numbered within another
([numbering within another counter](crate::guide::numbering#numbering-within-another-counter)),
the levels a point advances and the errors of a point that cannot be numbered ([numbering
a construct: the number
source](crate::guide::numbering#numbering-a-construct-the-number-source)), the numbering
options of a document, a construct numbered afresh inside each occurrence of an enclosing
construct ([scoped instances](crate::guide::numbering#scoped-instances)), and the other
ways a rule writes a number ([showing a number from a lowering
rule](crate::guide::numbering#showing-a-number-from-a-lowering-rule)). A feature that
needs a form the declarations cannot express contributes a within-joiner of its own
([numbering within another
counter](crate::guide::numbering#numbering-within-another-counter)) or a number writer of
its own ([the number writer](crate::guide::numbering#the-number-writer)). The [`headings`](crate::stdlib::features::headings) feature is a
complete example inside the library: it declares a counter and a counter style per
numbered heading kind as peer contributions, and its rule reads the counter table
optionally.

### Heading kinds and commands of your own

The `headings` feature builds its heading kinds and heading commands from its
configuration, so a host adds its own without writing a feature. A **heading kind**
([`HeadingDecl`](crate::stdlib::features::headings::HeadingDecl)) is a declared heading
(section, subsection, …) with a name, a level and its numbering. A **heading command**
([`HeadingCommand`](crate::stdlib::features::headings::HeadingCommand)) is a macro that
writes a heading of one kind, with default key-values of its own. Both go in a
[`HeadingsConfig`](crate::stdlib::features::headings::HeadingsConfig), which a host
gives in [`StdlibConfig::headings`](crate::stdlib::StdlibConfig::headings); the
configuration is fixed when the registry is built and
is an input of the registry digest.

```rust
use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
use flm_core::model::options::OptionValues;
use flm_core::stdlib::features::headings::latex::HeadingsLatexOptions;
use flm_core::stdlib::features::headings::{HeadingCommand, HeadingDecl, HeadingsConfig};
use flm_core::stdlib::features::numbering::NumberTemplate;
use flm_core::stdlib::{self, StdlibConfig};

// The five shipped kinds; an `appendix` kind, whose number (where the
// configuration numbers headings of its level) is written A, B, C in a counter
// of its own; and `\quietsection`, which writes a section left out of the
// contents unless an occurrence says `toc=true`.
let mut kinds = HeadingsConfig::new().headings;
kinds.push(HeadingDecl::new("appendix", 1).number_format(NumberTemplate::formats("#{Alph}")));
let headings = HeadingsConfig::new()
    .headings(kinds)
    .command(HeadingCommand::new("quietsection", "section").default_value("toc", "false"));

let mut builder = RegistryBuilder::new();
builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new().headings(headings)));
let registry = builder.build(&RegistryInputs::new())?;
// Six kinds: six values of the element `flm.heading`.
assert_eq!(registry.elements_named(flm_core::stdlib::features::headings::HEADING).len(), 6);

// In LaTeX, `\appendix` is the switch into the appendices, not a sectioning
// command, so the recomposed LaTeX is asked to write an `appendix` as `\section`.
let render_options =
    OptionValues::new().with(HeadingsLatexOptions::new().command("appendix", "section"));
# let _ = render_options;
# Ok::<(), flm_core::core::registry::RegistryBuildError>(())
```

[`HeadingsConfig::headings`](crate::stdlib::features::headings::HeadingsConfig::headings)
gives each kind a command of its own name, and
[`command`](crate::stdlib::features::headings::HeadingsConfig::command) adds one more.
A kind may also be written by no command at all, when the program creates its headings
itself (in a stage, for instance): its value of `flm.heading` is then registered with no
name, and no document can write it. Which kinds are numbered is the configuration's numbering depth
([`HeadingNumbering`](crate::stdlib::features::headings::HeadingNumbering)); by default,
no kind is numbered.

Every kind declared this way is listed in the table of contents that the
[`toc`](crate::stdlib::features::toc) feature builds, at its level, like the shipped
kinds: unless the kind is declared
[`skip_toc`](crate::stdlib::features::headings::HeadingDecl::skip_toc), an occurrence
says `toc=false`, or the level is deeper than the feature's setting `depth`. An entry
shows the occurrence's alternative title, written with the key `alt=`, and its title
otherwise ([the star and the
key-values](crate::guide::language_syntax#the-star-and-the-key-values)). A heading kind
that a feature declares with an element of its own, rather than through
[`HeadingDecl`](crate::stdlib::features::headings::HeadingDecl), is listed when its
element carries the [`Sectioning`](crate::model::aspects::Sectioning) aspect, which
answers the level, whether the occurrence is listed, and what its entry shows.

The LaTeX command a kind is recomposed as, and the HTML tag it is written with, are
render options: the headings feature's
[`HeadingsLatexOptions`](crate::stdlib::features::headings::latex::HeadingsLatexOptions)
and the HTML backend's
[`HtmlRenderOptions::heading_tags`](crate::stdlib::backends::html::HtmlRenderOptions::heading_tags).
They default to the kind's name and to the tag of its level. A kind whose name is not a
LaTeX sectioning command, such as `appendix`, must be mapped to one, since the recomposed
LaTeX runs the command it is given with the title. The recomposed LaTeX leaves what is
written before a heading's title (the number and its joining text) to the LaTeX document
class.

What is written before the title of a numbered heading, on the other backends, is the
kind's **heading title template**,
[`HeadingDecl::title_number_format`](crate::stdlib::features::headings::HeadingDecl::title_number_format):
a text in the template language ([the template language shared by
features](crate::guide::concepts_overview#the-template-language-shared-by-features)) that
states how the number joins the title, `#{number}. ` by default. In it:

- `#{number}` is the number as the kind's counter style writes it (`1.2`);
- `#[bare]{number}` is the kind's own number without the numbers of its parent counters
  (`2`);
- `#[Roman]{number}` is the kind's own number in another number format, with the parent
  counters' numbers written as usual (`1.II`);
- everything else is content: a joining text or a word.

```rust
use flm_core::stdlib::features::headings::HeadingDecl;

// `Chapter 1: Introduction`, with a no-break space after the word.
let chapter = HeadingDecl::new("chapter", 1).title_number_format("Chapter~#{number}: ");
# let _ = chapter;
```

The template states structure, not styling. How the number looks is decided by a
stylesheet, which selects the role `flm.heading.number` that the number carries, or by a
lowering rule of the host that replaces the rule of the element `flm.heading.number`,
which holds the number. A template that does not parse, that uses a placeholder other
than `number`, or that gives `number` a key it does not take, fails the registry build
with an error that gives the kind.

### An xnote kind of your own

An xnote is a piece of text set apart from the running text, marked where it belongs and
shown elsewhere or in place (a footnote, an endnote, a side note), and an xnote kind is
one way of being an xnote ([`xnotes`](crate::stdlib::features::xnotes)). The xnote kinds
that an author writes with a command of their own are the `xnotes` feature's
configuration ([`XnotesConfig`](crate::stdlib::features::xnotes::XnotesConfig)). A
feature that creates xnotes itself (for example, a feature of addenda that makes one
xnote per addendum) contributes an xnote kind with no command, and goes through the same
four steps as the `xnotes` feature's own `\footnote`:

1. **The service slot of xnote kinds.** In its `register` method, the feature calls
   [`contribute_kind`](crate::stdlib::features::xnotes::contribute_kind) with its
   [`XnoteKind`](crate::stdlib::features::xnotes::XnoteKind). That one function makes
   every declaration an xnote kind needs: the kind, into the service slot
   `flm.xnotes.kinds`; a numbered kind's counter and its two counter styles; and the
   kind's list, that is, its element, its piece table, the piece's declaration, the
   builder that writes it ([`ListBuilder`](crate::stdlib::features::xnotes::ListBuilder))
   and the rule that lowers it ([`ListRule`](crate::stdlib::features::xnotes::ListRule)).
   It also makes the peer declarations these need, so the feature declares none of them
   itself (declaring one again does no harm: the registry merges a repeated identical
   peer declaration into the first). The feature therefore builds and renders in a
   registry without the `xnotes` feature, where its xnotes are not collected and no list
   is placed.
2. **The aspect.** The feature's own element implements
   [`XnoteSource`](crate::stdlib::features::xnotes::XnoteSource), which returns, for a
   node, its xnotes: the xnote kind of each, and its content. The content is always a
   node region, one of the node's arguments or content slots, given by position
   ([`NodeRegion`](crate::core::lowering::NodeRegion);
   [`NodeRegion::argument_named`](crate::core::lowering::NodeRegion::argument_named)
   finds an argument's position from its name). The kind's list shows that region by
   lowering it where the list entry is placed, never a copy of it, so the content is
   lowered once, in the list, as the document's own content. The region always belongs
   to a node of the document: an xnote whose content the feature builds itself cannot be
   declared today.
3. **The reference points.** The element's
   [`Referenceable`](crate::model::aspects::Referenceable) aspect returns the points that
   [`ref_points`](crate::stdlib::features::xnotes::ref_points) gives, after its own
   points if it has any: the xnote and its mark, numbered, labeled and given anchors as a
   `\footnote`'s are. The `xnotes` feature's collect stage (the stage that writes the table
   [`flm.xnotes`](crate::stdlib::features::xnotes::XNOTES)) finds xnotes by these points'
   reference kinds, never by element, so every node of the element becomes a record of the table
   [`flm.xnotes`](crate::stdlib::features::xnotes::XNOTES), like every `\footnote`.
4. **The content apart from the text.** The element implements
   [`ApartFromText`](crate::model::aspects::ApartFromText) and returns the regions its
   xnotes are made from, so that their words are not read as part of the text around the
   node: a heading whose title holds the node is identified by the title's own words
   ([`plain_text_of`](crate::lang::text::plain_text_of)), as for a `\footnote`. It takes
   the regions from its own `XnoteSource` implementation through
   [`regions_apart_from_text`](crate::stdlib::features::xnotes::regions_apart_from_text),
   so that the regions are stated once. The arguments of an element that does not
   implement the aspect are read as words of that text.

```rust
use std::sync::Arc;

use flm_core::core::lowering::NodeRegion;
use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry};
use flm_core::core::registry::{RegistryBuilder, RegistryInputs};
use flm_core::lang::Flm;
use flm_core::lang::mint::{ArgDef, ElementDef, SyntaxDef};
use flm_core::model::aspects::{ApartFromText, ContentRef, RefPoint, Referenceable};
use flm_core::model::element::ElementSpec;
use flm_core::stdlib::features::numbering::PrefixWords;
use flm_core::stdlib::features::xnotes::{
    self, contribute_kind, ref_points, XnoteKind, XnoteOf, XnoteSource,
};
use flm_core::stdlib::{add_features, StdlibConfig};
use flm_core::techy::core::node::NodeRef;

/// `\myaddendum{text}`: one xnote of the kind `addendum`, whose content is the
/// argument `text`.
struct Addendum(Arc<XnoteKind>);

impl XnoteSource for Addendum {
    fn xnotes(&self, node: &NodeRef<'_, Flm>) -> Vec<XnoteOf> {
        NodeRegion::argument_named(node, "text")
            .map(|content| XnoteOf { kind: self.0.name.clone(), content })
            .into_iter()
            .collect()
    }
}

impl Referenceable for Addendum {
    fn points(&self, _node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
        ref_points(&self.0, &[], None)
    }
}

impl ApartFromText for Addendum {
    fn apart_from_text(&self, node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
        xnotes::regions_apart_from_text(node)
    }
}

struct Addenda;

impl FlmFeature for Addenda {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new("example-addenda", "Addenda")
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        let kind = Arc::new(
            XnoteKind::numbered("addendum", PrefixWords::new("Add.~", "Adds.~")).label_type("add"),
        );
        contribute_kind(b, Arc::clone(&kind))?;
        let value = Arc::new(Addendum(kind));
        b.element(ElementDef::new(
            b.feature().clone(),
            ["myaddendum"],
            SyntaxDef::Macro { args: vec![ArgDef::mandatory("text")] },
            Arc::new(
                ElementSpec::new("example.addendum")
                    .with::<dyn XnoteSource>(Arc::clone(&value) as Arc<dyn XnoteSource>)
                    .with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
                    .with::<dyn ApartFromText>(value as Arc<dyn ApartFromText>),
            ),
        ))
    }
}

let mut builder = RegistryBuilder::new();
builder.use_package(add_features(PackageEntry::new("std"), StdlibConfig::new()));
builder.feature(Arc::new(Addenda));
let registry = builder.build(&RegistryInputs::new())?;
assert_eq!(
    registry.services().services_named::<XnoteKind>(xnotes::KINDS_SLOT).count(),
    2, // `footnote`, then `addendum`
);
# Ok::<(), flm_core::core::registry::RegistryBuildError>(())
```

A kind with no command is written by no author: `contribute_kind` declares no command,
and the `xnotes` feature declares commands only for the kinds of its own configuration.
Two features that contribute kinds of one name make the registry build fail.

The `xnotes` feature's own lowering rule writes the mark of a `\footnote` through public
functions, which a contributing feature's rule calls to write the xnotes of its own
element in the same way:

- [`stage_mark`](crate::stdlib::features::xnotes::stage_mark), for a listed xnote kind,
  is given the node, the kind and the xnote's position among the node's xnotes of that
  kind (`0` for an element carrying one), and writes the mark alone;
- [`stage_in_place`](crate::stdlib::features::xnotes::stage_in_place), for an in-place
  xnote kind, is also given how the brackets around an in-place xnote are written
  ([`Brackets`](crate::stdlib::features::xnotes::Brackets)).

A rule that calls `stage_mark` declares that it reads `flm.xnotes` and produces
`flm.pres.span` and `flm.pres.link`; a rule that calls `stage_in_place` declares that it
reads `flm.xnotes` and produces `flm.pres.span`, `flm.pres.block` and `flm.pres.par`.
Either may read `flm.counters` and `flm.anchors` optionally: without the first, the mark
has no number; without the second, it has no anchor and no link. Each function's
documentation lists these requirements. The feature writes nothing for its list: the kind's
builder collects the kind's xnotes from `flm.xnotes` together with the footnotes', and
writes one list entry per xnote, holding a content pointer to the region the aspect gives
(never a copy of the content). A content pointer is the payload of a synthesized node
that shows, where the node is placed, content written elsewhere in the tree without
copying it ([`ContentPointer`](crate::stdlib::backends::lowering::ContentPointer)). The
kind's list rule writes the list after the content, under the kind's title, in a list of
its own after the lists of the kinds declared before it, and lowers each region where its
entry is placed.

In content shown a second time (a heading's title that a reference shows), an element
whose [`InCopy`](crate::model::aspects::InCopy) aspect returns
[`copied_as`](crate::stdlib::features::xnotes::copied_as) with the kinds of its xnotes
is shown as its marks, as a `\footnote` is. An element that does not is copied as
written; its node in the copy is not a node of the document, and is reported as holding
no recorded xnote.

### Several xnotes on one node

An element may carry more than one xnote on one node: a command that writes two footnotes
at one place, `\twonotes{first}{second}`, or an element that carries an xnote of each of
two kinds. It goes through the same four steps as an element carrying one, once per
xnote:

- its [`XnoteSource`](crate::stdlib::features::xnotes::XnoteSource) aspect returns one
  [`XnoteOf`](crate::stdlib::features::xnotes::XnoteOf) per xnote, and its
  [`Referenceable`](crate::model::aspects::Referenceable) aspect calls
  [`ref_points`](crate::stdlib::features::xnotes::ref_points) once per xnote, in the
  same order. The two results are paired by order, kind by kind: the node's second pair
  of points of a kind is the xnote whose content is the second `XnoteOf` of that kind. A
  node whose two results hold different numbers of xnotes of a kind is reported as the
  Error [`flm.xnotes.unpaired`](crate::stdlib::features::xnotes::Unpaired);
- the element decides which labels belong to which xnote: each `ref_points` call takes
  the labels of its own xnote (read, for example, from an argument of that xnote), as the
  one xnote of `\footnote[\label{fn:x}]{…}` takes the labels of its optional argument;
- its lowering rule calls
  [`stage_mark`](crate::stdlib::features::xnotes::stage_mark) (or
  [`stage_in_place`](crate::stdlib::features::xnotes::stage_in_place)) once per xnote,
  with the xnote's position among the node's xnotes of its kind (`0`, then `1`), and
  places what each call returns where it wants: the marks side by side, or apart. Its
  rule on the recomposed LaTeX calls
  [`stage_latex`](crate::stdlib::features::xnotes::stage_latex) once per xnote, with the
  xnote's labels, and each xnote is written as a command of its own;
- its [`InCopy`](crate::model::aspects::InCopy) aspect returns
  [`copied_as`](crate::stdlib::features::xnotes::copied_as) with the kinds of its
  xnotes: in content shown a second time, such as a heading's title that a reference
  shows, the node is written as the marks of all its xnotes, side by side, in order.

Each xnote is numbered, listed in its kind's list with its own content, and linked to and
from its own mark, as if each had been written on a node of its own.

```rust
use std::sync::Arc;

use flm_core::core::lowering::{
    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
    NodeRegion,
};
use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry};
use flm_core::core::registry::{RegistryBuilder, RegistryInputs};
use flm_core::lang::copy::ValueContent;
use flm_core::lang::Flm;
use flm_core::lang::mint::{ArgDef, ElementDef, SyntaxDef};
use flm_core::model::aspects::{
    ApartFromText, BlockRole, BlockRoleAspect, ContentRef, CopiedAs, InCopy, InlineSpacing,
    RefPoint, Referenceable,
};
use flm_core::model::element::ElementSpec;
use flm_core::stdlib::backends::pres;
use flm_core::stdlib::features::numbering::COUNTERS;
use flm_core::stdlib::features::refs::ANCHORS;
use flm_core::stdlib::features::xnotes::{self, XnoteKind, XnoteOf, XnoteSource, XNOTES};
use flm_core::stdlib::{add_features, StdlibConfig};
use flm_core::techy::core::node::NodeRef;

/// `\twonotes{first}{second}`: two footnotes on one node, whose contents are
/// the two arguments.
struct TwoNotes(Arc<XnoteKind>);

const ARGS: [&str; 2] = ["first", "second"];

impl XnoteSource for TwoNotes {
    fn xnotes(&self, node: &NodeRef<'_, Flm>) -> Vec<XnoteOf> {
        ARGS.iter()
            .filter_map(|arg| NodeRegion::argument_named(node, arg))
            .map(|content| XnoteOf { kind: self.0.name.clone(), content })
            .collect()
    }
}

impl Referenceable for TwoNotes {
    fn points(&self, _node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
        // One call per xnote, in the order the `XnoteSource` aspect returns
        // them; no labels.
        ARGS.iter().flat_map(|_| xnotes::ref_points(&self.0, &[], None)).collect()
    }
}

impl ApartFromText for TwoNotes {
    fn apart_from_text(&self, node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
        xnotes::regions_apart_from_text(node)
    }
}

impl InCopy for TwoNotes {
    fn in_copy(&self, node: &NodeRef<'_, Flm>, purpose: ValueContent) -> CopiedAs {
        xnotes::copied_as(node, purpose, vec![Arc::clone(&self.0)])
    }
}

/// The rule: the two marks, side by side.
struct TwoMarks(Arc<XnoteKind>);

impl Lower for TwoMarks {
    fn lower(
        &self,
        node: NodeRef<'_, Flm>,
        cx: &mut LowerCx<'_>,
        lw: &mut dyn Lowerer,
    ) -> Result<Lowering, LowerError> {
        let mut marks = xnotes::stage_mark(cx, lw, &node, &self.0, 0)?;
        marks.extend(xnotes::stage_mark(cx, lw, &node, &self.0, 1)?);
        Ok(Lowering::Emit(marks))
    }
}

struct TwoNotesFeature;

impl FlmFeature for TwoNotesFeature {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new("example-two-notes", "Two notes")
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        // The kind the `xnotes` feature configures by default.
        let kind = Arc::new(XnoteKind::footnote());
        let value = Arc::new(TwoNotes(Arc::clone(&kind)));
        b.element(ElementDef::new(
            b.feature().clone(),
            ["twonotes"],
            SyntaxDef::Macro { args: ARGS.iter().map(|arg| ArgDef::mandatory(*arg)).collect() },
            Arc::new(
                ElementSpec::new("example.two-notes")
                    .with::<dyn BlockRoleAspect>(Arc::new(
                        flm_core::model::aspects::FixedBlockRole(BlockRole::Inline(InlineSpacing {
                            absorb_before: true,
                            absorb_after: false,
                        })),
                    ))
                    .with::<dyn XnoteSource>(Arc::clone(&value) as Arc<dyn XnoteSource>)
                    .with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
                    .with::<dyn ApartFromText>(Arc::clone(&value) as Arc<dyn ApartFromText>)
                    .with::<dyn InCopy>(value as Arc<dyn InCopy>),
            ),
        ))?;
        b.lowering_rule(LoweringRule::new(
            "example.two-notes.lower",
            "example.two-notes",
            LoweringDecl::new()
                .reads(XNOTES)
                .reads_opt(COUNTERS)
                .reads_opt(ANCHORS)
                .produces(pres::SPAN)
                .produces(pres::LINK),
            Arc::new(TwoMarks(kind)),
            DefaultMark::Everywhere,
        ))
    }
}

let mut builder = RegistryBuilder::new();
builder.use_package(add_features(PackageEntry::new("std"), StdlibConfig::new()));
builder.use_package(flm_core::math_passthrough::package());
builder.feature(Arc::new(TwoNotesFeature));
let registry = builder.build(&RegistryInputs::new())?;

# use flm_core::model::doc::{Doc, DocContent, FragmentLayout};
# use flm_core::core::plan::{Overrides, Plan};
# use flm_core::core::run::{Externals, Run, RunOptions};
# use flm_core::lang::{FlmOrigin, ParseOptions, parse_fragment};
# use flm_core::stdlib::backends::text::{self, TEXT_OUTPUT};
# use flm_core::techy::source::Source;
let source = Arc::new(
    Source::new("A claim.\\twonotes{First.}{Second.} More.\\footnote{Third.}")
        .with_origin(FlmOrigin::none()),
);
let fragment =
    parse_fragment(registry.lang(), source, FragmentLayout::default(), &ParseOptions::default())?;
let mut content = DocContent::new();
content.place(Arc::new(fragment));
let plan = Arc::new(Plan::for_workflow(&registry, text::WORKFLOW, &Overrides::none())?);
let mut run = Run::new(Arc::new(Doc::new(content)), plan, Externals::none())?;
run.execute(&RunOptions::new())?;
assert_eq!(
    run.table(TEXT_OUTPUT)?.expect("written").text,
    "A claim.\u{b9}\u{b2} More.\u{b3}\n\nFootnotes\n---------\n\n\
     \u{b9} First.\n\n\u{b2} Second.\n\n\u{b3} Third.\n",
);
# Ok::<(), Box<dyn std::error::Error>>(())
```

### Building a kind's list your own way

The list of an xnote kind is what its piece table holds
([`piece_table`](crate::stdlib::features::xnotes::piece_table),
`flm.xnotes.list.<kind>`), and the kind's standard builder is one stage that writes it.
The list is a piece ([`Piece`](crate::core::piece::Piece)), built once by its builder
stage into that table and rendered by each backend with its own rules.

To build one kind's list differently (a list with only the labeled footnotes, a list of
the lists feature's elements, a sentence), a feature registers a stage of `Document`
scope that writes that table from what it declares that it reads (the table of xnotes
[`flm.xnotes`](crate::stdlib::features::xnotes::XNOTES), the frozen trees, or more), and
a request prefers that stage:
[`Overrides::prefer`](crate::core::plan::Overrides::prefer), or
[`WorkflowDef::prefer`](crate::core::registry::WorkflowDef::prefer) in a workflow of the
feature's own. Without a preference, the plan refuses to choose between the two stages
([`PlanError::Contested`](crate::core::plan::PlanError::Contested), which lists both): a
replacement is used only when it is asked for. The lists of the other kinds are not
affected. The replacement's piece may hold any elements that the plan's rules lower; the
kind's list element and entry element keep their rules, which find each entry's xnote
among its kind's records by the node's address and the node region its content pointer
designates.

To show the xnotes' content, a replacement points at it, as the standard builder does,
and never copies it: a copy is a synthesized value, in which a labeled point is refused
and a point has no number and no anchor. Each entry of the kind's list element
([`ENTRY`](crate::stdlib::features::xnotes::ENTRY)) holds one node of the content
pointer element [`CONTENT_POINTER`](crate::stdlib::features::xnotes::CONTENT_POINTER),
whose payload [`ContentPointer`](crate::stdlib::backends::lowering::ContentPointer)
designates the xnote's node (the address of its record's point in
[`flm.xnotes`](crate::stdlib::features::xnotes::XNOTES)) and the region its
[`XnoteSource`](crate::stdlib::features::xnotes::XnoteSource) aspect gives. A
[`SynthesizedPiece`](crate::lang::copy::SynthesizedPiece) carrying that payload, built
into the value by
[`copy_pieces_into_value`](crate::lang::copy::copy_pieces_into_value), is such a node.
The list rule lowers the region where the entry is placed, through
[`Lowerer::lower_region`](crate::core::lowering::Lowerer::lower_region), as the
document's own content, and gives the entry the xnote's mark as its label and the xnote's
identifier. **Point at each xnote once**: the region is lowered wherever a pointer
designates it, and nothing checks that it is lowered only once. An entry that holds no
pointer has no mark and no identifier.

```rust
use std::sync::Arc;

use flm_core::core::data::store::StageOut;
use flm_core::core::piece::Piece;
use flm_core::core::plan::{Overrides, Plan, PlanCx, PlanError};
use flm_core::core::registry::{
    BuildError, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry, RegistryBuilder, RegistryInputs,
};
use flm_core::core::run::StageCx;
use flm_core::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use flm_core::lang::{parse_fragment, FlmOrigin, FlmSource, ParseOptions};
use flm_core::model::doc::FragmentLayout;
use flm_core::stdlib::backends::text;
use flm_core::stdlib::features::xnotes::{self, XNOTES};
use flm_core::stdlib::{add_features, StdlibConfig};

/// Writes the footnotes' list as one sentence counting them.
struct CountFootnotes;

impl Stage for CountFootnotes {
    fn decl(&self) -> StageDecl {
        StageDecl::new("mypkg.xnotes.build", Effect::Compute, Scope::Document)
            .writes(xnotes::piece_table("footnote"))
            .docs("the footnotes' list, as a count")
    }

    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
        Needs::new().reads(XNOTES)
    }

    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
        let count = match cx.get(XNOTES) {
            Ok(Some(table)) => table.of_kind("footnote").len(),
            _ => return,
        };
        let source = Arc::new(
            FlmSource::new(format!("{count} footnotes.")).with_origin(FlmOrigin::none()),
        );
        let options = ParseOptions::default();
        let Ok(value) = parse_fragment(cx.registry().lang(), source, FragmentLayout::default(), &options)
        else { return };
        if let Ok(table) = out.table(&xnotes::piece_table("footnote")) {
            *table = Piece::new(Arc::clone(value.tree()));
        }
    }
}

struct MyNotes;

impl FlmFeature for MyNotes {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new("mypkg", "My notes")
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        b.stage(Arc::new(CountFootnotes))
    }
}

let mut builder = RegistryBuilder::new();
builder.use_package(add_features(PackageEntry::new("std"), StdlibConfig::new()));
builder.use_package(flm_core::math_passthrough::package());
builder.feature(Arc::new(MyNotes));
let registry = Arc::new(builder.build(&RegistryInputs::new())?);

// Asked for: the override builds the list, the standard builder is not
// scheduled.
let prefer = Overrides { prefer: vec!["mypkg.xnotes.build".into()], ..Overrides::none() };
let plan = Plan::for_workflow(&registry, text::WORKFLOW, &prefer).expect("a plan");
assert!(plan.stage_names().iter().any(|stage| stage.as_str() == "mypkg.xnotes.build"));
assert!(!plan.stage_names().iter().any(|stage| stage.as_str() == "flm.xnotes.build-list.footnote"));

// Not asked for: the plan refuses to choose between the two stages that write the list.
let contested = Plan::for_workflow(&registry, text::WORKFLOW, &Overrides::none());
assert!(matches!(contested, Err(PlanError::Contested { .. })));
# Ok::<(), Box<dyn std::error::Error>>(())
```

To change how the list *looks* rather than what it holds, register another lowering rule
for the kind's list element `flm.xnotes.<kind>.list`, marked
[`DefaultMark::Never`](crate::core::lowering::DefaultMark::Never), and select it in the
backend's rule selection, as for any element; the two kinds of replacement can be
combined. To leave a kind's list out of one render, exclude its piece through
[`PiecesRenderOptions`](crate::stdlib::backends::pieces::PiecesRenderOptions).

For the HTML backend, `contribute_kind` registers, per kind, the rule of the kind's list
element on that backend, which writes the list with a link back from each entry to its
mark. For a listed kind, the contributing feature's own element needs no rule of its own
on HTML: its general rule's mark serves the page too. For an in-place kind, a rule of its
own marked
[`DefaultMark::OnBackends`](crate::core::lowering::DefaultMark::OnBackends)`(["html"])`
calls `stage_in_place` with `Brackets::Drawn` and requires the stylesheet
[`flm.xnotes.style`](crate::stdlib::features::xnotes::STYLE), which draws the brackets
on the page, as the `xnotes` feature's own rule does.

On the recomposed LaTeX, the contributing feature's rule for that backend calls
[`stage_latex`](crate::stdlib::features::xnotes::stage_latex), given the node, the kind,
the xnote's position and its labels. The function writes
`\flmXN<kind>[<labels>]{<content>}`, a LaTeX hook (a macro the recomposed LaTeX writes
and the style file defines with a plain default, which a user redefines in the document's
preamble; [`preamble`](crate::stdlib::backends::latex::preamble)), and requires the
kind's definition in the style file, which `contribute_kind` contributes. The rule
declares that it produces the LaTeX family's macro and raw construct elements, that it
reads the table of safe labels optionally, and that it reads the backend's render
options. `contribute_kind` also registers, per kind, the rule of the kind's list element
on that backend, which writes nothing, and makes peer declarations of the backend, the
two construct elements and the table of safe labels on behalf of the contributing
feature. That feature, including its own rule that calls `stage_latex`, therefore builds
in a registry without the LaTeX features, with its LaTeX rules set aside, without
declaring anything for the LaTeX backend itself.

### A cell style of your own

A cell of a table of cells carries style tokens, as in `\cell<total>{…}`, and every
token refers by name to a cell style
([`CellStyle`](crate::stdlib::features::cells::CellStyle)), a declaration contributed to
the `cells` feature's service slot `flm.cells.styles`
([`STYLES_SLOT`](crate::stdlib::features::cells::STYLES_SLOT)). The `cells` feature
contributes its own cell styles (`align{…}`, `head{…}`, `rule{…}`; their short forms
`l`, `c`, `r`, `H`, `rH`, `lvert`, `rvert`; and the backgrounds `green`, `blue`,
`yellow`, `red`), and any feature may contribute more. A token that no cell style
declares is an error in the document, which catches a misspelled style, and also a
document that uses a host's style in a registry without the host's feature.

A cell style says what its token states about the cell, as one of four **effects**
([`Effect`](crate::stdlib::features::cells::Effect)), each a fact that holds regardless
of the output format:

- the cell's alignment;
- that the cell heads its column or its row;
- a rule (a line) at one of the cell's edges;
- a **custom style**, which the cell carries by its name.

A cell style of yours is usually a custom style; it may also state one of the other
three effects, as a short form of a shipped token does. Each backend writes a custom
style in a form of its own: the HTML backend writes the attribute
`data-flm-style-<name>` on the cell's element, the recomposed LaTeX writes the table
command `\flmCellsSet{<name>}` at the start of the cell's text, and plain text shows
nothing. Your definitions for each backend give the name its meaning (a stylesheet rule
that selects the attribute; the keys that a LaTeX definition piece registers under the
name), and the cell style's requirements, per backend
([`CellStyle::requires`](crate::stdlib::features::cells::CellStyle::requires)), make the
page or the style file hold those definitions exactly where a cell uses the style:

```rust
use std::sync::Arc;
use flm_core::core::registry::{
    BuildError, DefContent, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry, RegistryBuilder,
    RegistryInputs, StyleDef,
};
use flm_core::model::names::Name;
use flm_core::stdlib::backends::latex::{LatexPreambleDef, preamble};
use flm_core::stdlib::backends::{html, latex_recomposed};
use flm_core::stdlib::features::cells::{CellStyle, LATEX_PIECE, STYLES_SLOT};
use flm_core::stdlib::{self, StdlibConfig};

struct HostStyles;

impl FlmFeature for HostStyles {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new("host", "The host's cell styles")
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        // The host's definitions: a style definition for HTML, and a
        // definition piece for the recomposed LaTeX registering each style's
        // `tabularray` cell keys, written after the `cells` feature's piece,
        // which defines `\flmCellsStyleKeys`.
        b.style_def(StyleDef {
            id: Name::from("host.cells.style"),
            // The host's stylesheet rules, which select `.flm-pres-cells
            // [data-flm-style-total]` and the attributes of the other styles.
            content: vec![DefContent::Inline(String::from("/* host.cells.style */\n"))],
            docs: String::from("the host's cell styles"),
        })?;
        let piece = LatexPreambleDef::new(
            "host-cells",
            "\\flmCellsStyleKeys{total}{cmd=\\bfseries}\n\\flmCellsStyleKeys{pending}{bg=lightgray}\n",
            "the `tabularray` keys of the host's cell styles",
        )
        .requires([LATEX_PIECE]);
        // A peer contribution, as the styles below: the feature builds
        // without the LaTeX backend too.
        b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(piece))?;
        let host_piece = preamble::piece_id("host-cells");
        let styles = [
            // Given its meaning by the host's style definition on HTML and by
            // the keys the host's definition piece registers for `total` on the
            // recomposed LaTeX.
            CellStyle::custom("total", "a cell that holds a total")
                .requires(html::BACKEND, ["host.cells.style"])
                .requires(latex_recomposed::BACKEND, [host_piece.clone()]),
            // The same two requirements, for the keys registered for `pending`.
            CellStyle::custom("pending", "a value not yet confirmed")
                .requires(html::BACKEND, ["host.cells.style"])
                .requires(latex_recomposed::BACKEND, [host_piece]),
            // A style a stylesheet alone reads: nothing to require elsewhere.
            CellStyle::custom("warn", "a cell to notice").requires(html::BACKEND, ["host.cells.style"]),
        ];
        for style in styles {
            // A peer contribution: the feature builds without `cells` too.
            b.peer_slot::<CellStyle>(STYLES_SLOT, Arc::new(style))?;
        }
        Ok(())
    }
}

let mut builder = RegistryBuilder::new();
builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
builder.feature(Arc::new(HostStyles));
let registry = builder.build(&RegistryInputs::new())?;
# let _ = registry;
# Ok::<(), flm_core::core::registry::RegistryBuildError>(())
```

The identifiers a cell style requires designate definitions that your feature registers
for that backend: the style definition `host.cells.style` (see [Style and script
definitions](#style-and-script-definitions)) and the definition piece
`flm.latex.def.host-cells`. A definition piece is a unit of LaTeX definitions that a
feature registers under an identifier `flm.latex.def.<name>`, together with the
identifiers it needs in turn
([`LatexPreambleDef`](crate::stdlib::backends::latex::LatexPreambleDef)). On the
recomposed LaTeX, a cell carrying `total` and `pending` begins
`\flmCellsSet{total}\flmCellsSet{pending}`, and each table command applies the keys
registered under its name; of two styles that set `cmd=`, the later one applies.

On the rendered LaTeX, a cell's styles are written by name in the key `styles` of its
spec, and the keys of a style are registered with `\flmxDefineCellStyle{<name>}{<tblr
cell keys>}` (`\flmxDefineCellStyle{total}{font=\bfseries}`), in a definition piece of
yours that requires the core of the contract
([`CORE_CHUNK`](crate::stdlib::backends::latex_rendered::contract::CORE_CHUNK)); the cell
style requires that piece for the backend `latex-rendered`
(`.requires(latex_rendered::BACKEND, [piece_id])`), as above for the recomposed LaTeX
([Definition pieces for the rendered LaTeX](#definition-pieces-for-the-rendered-latex)).

A cell style carries no code, so it cannot change a cell's content or the table's model
(an alignment on a decimal point, for instance, cannot be expressed). It cannot redeclare
a shipped token either: that is a registry build error. To give `green` another color,
set the custom property `--flm-cells-green` (defined by the `cells` feature's style
definition) in a stylesheet of your own on HTML, or, in LaTeX, define `\flmCellsKeysgreen` (the keys registered for `green`) or the color
`flmCellsColorgreen` before the style file is loaded. A token takes a value in braces only
where its cell style is of the structural form, as the `cells` feature's own three
(`align`, `head`, `rule`) are; a value on a custom style is an error.

## A Rust extension, end to end

The extension `phfpack`, which ships with FLM, is written in Rust as a third party writes
an extension: against the guest client `flm_ext::guest` alone (see [A Rust extension
compiled to WebAssembly](#a-rust-extension-compiled-to-webassembly)). It is one of the
extensions of the crate `flm-extensions`, which holds every extension shipped with FLM
([A crate that holds several Rust extensions](#a-crate-that-holds-several-rust-extensions)):
its folder `extensions/rust/phfpack/` holds its manifest and its `README.md`, and its code
under `src/` is the module `flm_extensions::phfpack`, compiled under the cargo feature
`phfpack`. The code uses no item of the crate outside its own module, and no crate of the
repository but `flm-ext` with the cargo feature `guest`; it also uses `serde`, `serde_json`
and `schemars`, with which it reads and describes its settings. The extension provides one
package, the default package `_`, which a document uses with `use: [phfpack]`. The package
holds one feature, `phfqit`, which declares notation macros for quantum information (such
as `\ket{\psi}` and `\braket{\phi}{\psi}`), whose delimiters are drawn at the size a use
asks for, and quantity macros such as entropies. Each macro is a *user definition*, a
macro defined by substitution: a name, an argument syntax and a template ([author
definitions](crate::guide::language_syntax#author-definitions)). An expansion hook of the
feature's own replaces every use of a macro by its template before any output is written.

The paragraphs below follow the extension from the declaration of its package to the two
forms in which a program runs it. The crate's own documentation (its `src/lib.rs`) lists
every macro an author can write, and the items of the guest client that each step uses.

**The package and the feature.** The module declares the static `FLM_EXTENSION`, the
extension's row of code ([A crate that holds several Rust
extensions](#a-crate-that-holds-several-rust-extensions)), with the function `define`,
which declares the package `_`. The package uses no other
package. Its `flm` block states the feature order `math-mathjax < phfqit`: where
the extension `math-mathjax` is in use, the macros that MathJax also defines (`\Re`,
`\Im`) take the definitions of `phfqit`. The package holds the feature `phfqit`, with its
title, its documentation (abridged here), its settings, its configuration reader and its
`register` function:

```ignore
pub static FLM_EXTENSION: flm_ext::guest::CompiledExtension =
    flm_ext::guest::CompiledExtension::new(define, "phfpack", env!("CARGO_PKG_VERSION"));

fn define(ext: &mut Extension) {
    ext.package(
        "_",
        Package::new().flm(json!({ "feature_order": ["math-mathjax < phfqit"] })).feature(
            feature::FEATURE,
            Feature::new()
                .title("Quantum-information notation")
                .docs("Notation macros for quantum information: …")
                .settings(feature::settings())
                .read(settings::read)
                .register(feature::register),
        ),
    );
}
```

**The macros as data.** The built-in macros are the rows of the crate's module `tables`.
A row gives a macro's name, its arguments, the number of leading arguments that the
numbered placeholders skip (`#1` is the first argument after them), its template, its
parsing modes and the default values of its optional arguments. Each argument of a row is
a size slot (an argument through which a use asks for a size; see the size slots below) or
an argument code ([An argument's syntax in settings](#an-arguments-syntax-in-settings)).
The row of `\abs` is built by the function `delimited`, which makes `#1` the first
argument after the three size slots:

```ignore
/// The three size slots of a delimited macro, then one braced argument.
const SIZED_1: &[RowArg] = &[Size(Backtick), Size(Star), Size(Bracket), Code("{")];

delimited("abs", SIZED_1, r"#[{\lvert}]{DelimLeft}{#1}#[{\rvert}]{DelimRight}"),
```

Each row becomes a value of the guest's `Definition`, the mirror of
[`Definition`](crate::lang::rewrites::userdefs::Definition). A row's argument code is read
with the guest's `ArgDef::from_code`, or with `ArgDef::named_from_code` for an argument
that the template refers to by its name, in `register`, which answers the error of a code
that is not one; a size slot is declared by its standard kind. Every
definition also declares four *computed placeholders* with
`Definition::extra_placeholder`: names whose content the feature computes at each use,
which take a substitution argument (`#[…]{name}`). `#[\lvert]{DelimLeft}`,
`#[\vert]{DelimMiddle}` and `#[\rvert]{DelimRight}` write the delimiter between the
brackets at the size the use asks for; `#[spaceKets.Bar]{config}` writes a named value of
the settings (here the spacing around the bar of `\braket`).

A macro that a document declares in the feature's settings, under the key
`macro_definitions`, becomes the same kind of value. Its arguments are written under
`args` in the forms of a user definition's arguments ([Arguments](#arguments)): one text
whose characters are argument codes, or a list whose entries are each an argument code,
an argument's map, or the name of a size slot (`SizeArgBacktick`, `SizeArgStar` or
`SizeArgOptArg`). An argument's map gives the argument's syntax either as a code
(`code: "r()"`) or as a structured syntax
(`syntax: delimited-group, delimiters: ["(", ")"]`), beside the argument's other keys.
A delimited macro writes its arguments under `delimited_args`, as one text or as a list
of codes and maps: the three size slots come first without being written, and the
numbered placeholders count from the first argument after them, as in a row built by
`delimited`. The crate's settings types hold each argument as the guest's
`lang::mint::ArgDef`, the mirror of [`ArgDef`](crate::lang::mint::ArgDef): `serde` reads
it in the data form of [`ArgData`](crate::lang::mint::ArgData), with the library's own
reading, and its JSON schema is that form's, which lists the argument codes and the
standard kinds. They hold the list of `delimited_args` as the guest's
`lang::mint::ArgListData`, the mirror of
[`ArgListData`](crate::lang::mint::ArgListData), read in that list's shapes and described
with its schema. A size slot is declared as a row's is, and the hook reads it as it reads
the slots of a row. A declaration whose `content` gives one template for running text and
one for formulas becomes one definition per parsing mode.

**The size slots.** A use of a delimited macro asks for the size of its delimiters in one
of three ways: a size command after a backtick (``\abs`\Big{x}``), a star (`\abs*{x}`,
delimiters as tall as the content), or a size command in brackets (`\abs[\Big]{x}`). The
size commands are `\big`, `\Big`, `\bigg` and `\Bigg`. Each way is one argument of a
standard kind ([Arguments](#arguments)), declared by that kind:

```ignore
pub fn arg(self) -> ArgDef {
    ArgDef::new(match self {
        SlotKind::Backtick => ArgStdKind::Embellishments { markers: vec!['`'] },
        SlotKind::Star => ArgStdKind::Star,
        SlotKind::Bracket => ArgStdKind::Optional,
        SlotKind::Marker(i) => ArgStdKind::Marker { marker: SIZE_COMMANDS[i].to_string() },
    })
}
```

- `Embellishments` (the code ``e{`}``) is the
  [embellishment argument](crate::lang::mint::ArgStdKind::Embellishments) whose one marker
  is the backtick. The parser matches a marker against the characters as they are
  written, so the backtick matches even in a formula, where the feature declares it as the
  trigger of the backtick form (below). The size is the expression that follows the
  marker: a command such as `\Big`, or the star.
- `Star` (the code `*`) is the star, and `Optional` (`[`) an optional argument in
  brackets.
- `Marker` (the code `t{\Big}`) is an optional
  [marker argument](crate::lang::mint::ArgStdKind::Marker) spelled as a size command; only
  the backtick form declares such arguments.

At a use, the hook finds the slot that the use writes with the guest's
`Node::argument_content_nodes(index)`, which answers `Some` for an argument the use writes,
and reads the size's text with `span_content`: after a backtick, the text of the children
of the group that the embellishment argument holds for its marker; in brackets, the text
between the brackets. A text that is neither a size command nor the star, or a size given
in two ways, is the Error `phfpack.phfqit.bad-size` at the use.

The *backtick form*, such as `` `\Big(a+b) `` in a formula, writes a group between its own
delimiters at the size written right after the backtick. It is a special character
sequence (characters that trigger a definition, here the backtick alone), declared for
formulas only, since a backtick in running text is a quotation mark. Its size follows the
backtick with no marker between them, so no embellishment argument can read it. Its row
therefore declares one optional marker argument per size command, then the star, then the
group in braces, brackets, parentheses or angle brackets:

```ignore
pub const BACKTICK: &[Row] = &[Row {
    kind: RowKind::Specials,
    name: "`",
    args: &[
        Size(Marker(3)),
        Size(Marker(1)),
        Size(Marker(2)),
        Size(Marker(0)),
        Size(Star),
        Named(MAIN_DELIMITED_ARGUMENT, "AnyDelimited"),
    ],
    offset: 0,
    template: "#{DelimLeft}#{MainDelimitedArgument}#{DelimRight}",
    modes: DefinitionModes::Math,
    defaults: &[],
}];
```

`Marker(i)` is the marker argument of the size command at index `i` of `\big`, `\Big`,
`\bigg`, `\Bigg`, so the row declares `t{\Bigg}`, `t{\Big}`, `t{\bigg}` and `t{\big}`, in
this order. A marker matches the characters written after the backtick as they are, so a
marker that begins another (`\Big` begins `\Bigg`) comes after it. A size that is none of
these (`` `\huge(x) ``) matches no marker, and the parser reports that the group which
must follow the backtick is missing. The template writes `#{DelimLeft}` and
`#{DelimRight}` without a substitution argument: the feature then writes the delimiters
that correspond to the one opening the group (`\langle` and `\rangle` for `<`).

**Elements and lowering rules.** The function `register` receives the feature builder `b`
and the feature's configuration. It declares one element and one lowering rule per macro,
in a fixed order: the rows in the order of the tables, except each row that a declared
macro of the same name replaces, then the declared macros in the order of their names. It
then passes the settings to the registry digest (see below):

```ignore
pub fn register(b: &mut FeatureBuilder, settings: &Value) -> Result<(), ExtError> {
    let data = PhfqitData::from_settings(settings).map_err(settings::refused)?;
    let digest = data.digest_bytes();
    let config = PhfqitConfig::from_data(data).map_err(settings::refused)?;
    let owner = b.feature()?;
    let values = Arc::new(config.values.clone());
    for m in macros(config) {
        let definition = m.definition.expand(ExpandPolicy::Always);
        let element = element_name_under(PREFIX, &definition)?;
        // The rule covers the element on every backend and schedules the
        // `userdefs` feature's stage that expands the `always` definitions,
        // which makes that feature necessary.
        b.lowering_rule(expand_in_tree_rule_for(&element, &definition)?)?;
        let hook: Arc<dyn Expand> = Arc::new(MacroHook { slots: m.slots, values: Arc::clone(&values) });
        let value = UserDefinition::new(definition)?;
        b.element(value.element_def_with(&owner, &element, hook)?)?;
    }
    b.digest_input(&digest)
}
```

For each macro:

- The definition takes the expansion policy `always`. The element's name is the one that
  the guest's `stdlib::features::userdefs::element_name_under`, the mirror of
  [`element_name_under`](crate::stdlib::features::userdefs::element_name_under), derives
  with the prefix `phfpack.phfqit` (`phfpack.phfqit.macro.ket` for `\ket`).
- The lowering rule is the one that the guest's `expand_in_tree_rule_for`, the mirror of
  [`expand_in_tree_rule_for`](crate::stdlib::features::userdefs::expand_in_tree_rule_for),
  builds. The rule requires the trees table
  [`ALWAYS_EXPANDED`](crate::stdlib::features::userdefs::ALWAYS_EXPANDED), which the
  `userdefs` feature's rewrite stage for `always` definitions writes. Every plan that
  lowers one of the macros therefore runs that stage, which replaces each use by its
  template before any output is written, and a registry without the `userdefs` feature
  does not build.
- The element declaration is the one that the guest's `UserDefinition::element_def_with`,
  the mirror of
  [`UserDefinition::element_def_with`](crate::lang::rewrites::userdefs::UserDefinition::element_def_with),
  builds with the feature's own expansion hook `MacroHook`, an implementation of the
  guest's trait `Expand` that holds the macro's size slots and the named values of the
  settings. `owner`, the name of the feature, comes from `b.feature()`.

The feature registers no build hook to compile its templates: the extension interface
compiles the templates of every definition that an extension registers once the language
is built, as the `userdefs` feature compiles an author's user definitions.

**Placeholders computed at each use.** The hook `MacroHook` expands every use of every
macro of the feature. Its method `expand` receives the use's node, the context of the
expansion `cx` and the expander `xp` (the guest's `ExpandCx` and `Expander`), and takes
these steps:

1. It finds the use's definition with `cx.definition()`, since a handle that `register`
   held is valid only during that call. It then asks the definition for its *variant* for
   the use's parsing mode, the template and default values compiled for that mode, with
   `UserDefinition::variant_for_use`, the mirror of
   [`UserDefinition::variant_for_use`](crate::lang::rewrites::userdefs::UserDefinition::variant_for_use).
   Where the definition has no variant for that mode, the answer is the library's
   condition `flm.userdefs.bad-definition`, which the hook reports at the use with
   `xp.recover`, under that identifier.
2. It reads the size the use asks for (see the size slots above).
3. It lists the computed placeholders that the variant's template and default values
   write, each as a name and the text of its substitution argument.
   `CompiledTemplate::placeholders` answers each placeholder of a template with its target
   (an argument, the body, or the name of a computed placeholder) and the text of its
   substitution argument; `ModeVariant::defaults`, the mirror of
   [`ModeVariant::defaults`](crate::lang::rewrites::userdefs::ModeVariant::defaults),
   answers the compiled default values, whose placeholders count too:

   ```ignore
   let template = variant.template()?;
   let mut written = BTreeSet::new();
   let defaults = variant.defaults()?.into_iter().map(|(_, default)| default);
   for compiled in std::iter::once(template).chain(defaults) {
       for reference in compiled.placeholders()? {
           if let PlaceholderTarget::Extra(name) = reference.target {
               written.insert((name, reference.substitution));
           }
       }
   }
   ```

4. It writes the text of each placeholder it listed: for a delimiter placeholder, the
   delimiter at the use's size (`\Bigl \langle` for the left `\langle` at the size
   `\Big`); for `config`, the named value of the settings that the substitution argument
   gives. A named value that the settings do not hold is the Error
   `phfpack.phfqit.unknown-value` at the use.
5. It compiles each text in the use's parsing mode with the guest's
   `compile_template_with`, the mirror of
   [`compile_template_with`](crate::lang::rewrites::userdefs::compile_template_with),
   against the built language of the expansion (`xp.lang()`) and the feature's
   `TemplateLanguage`. The compiled template is kept by the extension interface for the
   feature while the registry is in use, and compiling an equal specification again
   answers it without compiling the text a second time, so a second use at the same size
   compiles nothing. A text that does not compile in the use's parsing mode (a delimiter
   at a size command, in running text) is left out; the library then reports its
   placeholder as an Error at the use (`flm.userdefs.bad-placeholder`):

   ```ignore
   match compile_template_with(&spec, &self.lang, language) {
       Ok(template) => Ok(Some(template)),
       Err(ExtError::Core { kind, .. }) if kind == COMPILE_TEMPLATE => Ok(None),
       Err(error) => Err(error),
   }
   ```

6. It gives each compiled text to its placeholder with the guest's `ExtraValues`, the
   mirror of [`ExtraValues`](crate::lang::rewrites::userdefs::ExtraValues), under the
   placeholder's name and substitution text
   (`values.template(name, substitution.as_deref(), compiled)`). It lays these values over
   the bindings of the use's arguments, the guest's `DefinitionBindings`, the mirror of
   [`DefinitionBindings`](crate::lang::rewrites::userdefs::DefinitionBindings), and
   instantiates the template. Every other placeholder (`#1`, a named argument, a default
   value) therefore means in the feature's templates what it means in an author's user
   definition:

   ```ignore
   let bindings = values.over(&DefinitionBindings::new(node, &variant)?)?;
   Ok(Expansion::Emit(xp.instantiate(cx, node, &template, &bindings)?))
   ```

**Settings as data.** The feature declares its settings as data, the value that the
function `settings` answers and that `Feature::settings` takes:

```ignore
pub fn settings() -> Value {
    json!({
        "config": {
            "schema": settings::schema(),
            "docs": "The macros declared in addition to the built-in ones (`macro_definitions`), and the named \
                     values the macros' templates read (`spaceKets`, `spaceOKets`, `space`). Fixed when the \
                     registry is built: it cannot vary per document or per render.",
        },
    })
}
```

- `config` is the feature's configuration: the JSON schema of the crate's own settings
  types, which they derive with `schemars` (`settings::schema`), and its documentation.
- `settings::schema` writes the marks on the nodes of that schema, in `x-flm-marks`.
  Each of the four keys carries `merge-object-key-values` and
  `remove-key-when-value-is-false`: it is combined entry by entry, so that a document that
  sets `spaceKets.Bar` keeps the default of `spaceKets.RLAngle`. Its default entries are
  the `default` that `schemars` writes on its node. The templates and default values of a
  declared macro (`content` and `defaults` of `MacroFields`) and the named values
  (`spaceKets.*`, `spaceOKets.*`, `space.*`) carry `markup`: they are written in FLM
  markup.

The feature also declares its configuration reader, `Feature::read(settings::read)`: a
function that receives the configuration written and answers the configuration
`register` receives, or the value at fault as a `ReadError`, its path below the feature's
name and the condition it violates. `settings::read` reads the configuration into the
crate's settings types one key at a time (`PhfqitData::from_settings`), each declaration
under `macro_definitions` with `serde`, converts each declaration
(`PhfqitConfig::from_data`), and answers the configuration unchanged.

The library registers these settings as it registers a compiled feature's
([`SettingsDecl::config_data_read`](crate::core::settings::SettingsDecl::config_data_read)),
which reads the marks and the default entries from the nodes of the schema. A document
therefore writes them under `flm`, `features`, `phfqit`, and `flm schema`, given a
document that uses the package, describes them. The reader runs whenever the program reads
the settings of a document that uses the package, with `{}` when the settings write
nothing under `phfqit`: a value it cannot read is reported there, with the place in the
front matter where it was written, and its path (the value of `phfqit.spaceKets.Bar`
must be a text; the value of `phfqit.macro_definitions.abs.args`, for a declaration).
`register` receives the final configuration, combined from every source of settings, as
a JSON value, and reads it the same way.

**The registry digest.** The named values and the templates of the declared macros change
what the feature writes in ways the feature's declarations do not show (see [the registry
digest](crate::model::digest)), so `register` passes the settings to the digest with the
guest's `FeatureBuilder::digest_input`, the mirror of
[`FeatureBuilder::digest_input`](crate::core::registry::FeatureBuilder::digest_input).
The bytes are those of `PhfqitData::digest_bytes`: the settings as data, in a binary form
in which every list and every text is preceded by its count, a little-endian 64-bit
number, and the keys of every map are in their sorted order, so that the bytes do not
depend on the order in which a document writes the keys. `digest_input` takes the bytes as
they are.

**The two forms.** The same source has the two forms that [A Rust extension compiled into
a program](#a-rust-extension-compiled-into-a-program) describes:

- **Compiled into the `flm` program.** With the cargo feature `phfpack` on, the crate
  `flm-extensions` holds the extension in its table of files `EXTENSIONS` (its manifest
  and its `README.md`) and in its table of code `COMPILED_EXTENSIONS`, whose row is:

  ```ignore
  flm_ext::guest::NamedExtension { stem: "phfpack", compiled: &crate::phfpack::FLM_EXTENSION }
  ```

  The `flm` program's cargo feature `bundled-extensions` (on by default) turns on every
  extension of `flm-extensions` and gives both tables to the host library ([The
  extensions a program offers](crate::guide::embedding#the-extensions-a-program-offers)).
  The program runs the extension with the engine `native`, and finds it by the name
  `phfpack` after every folder of its search path ([Where extensions are looked
  for](crate::guide::command_line#where-extensions-are-looked-for)). A program built
  without `bundled-extensions` does not carry it. The extension's tests load it as a
  program does: an `ExtensionLoader` with a `NativeEngine` that holds the row, and a
  `MemorySource` that answers the name `phfpack` with the manifest
  `{extension: {engine: native}}` (`tests/common/mod.rs` of the extension's folder).
- **A WebAssembly module.** The script `extensions/rust/build-wasm.sh phfpack` builds the
  crate `flm-extensions` with the feature `phfpack` alone, in a cargo run of its own, and
  writes the folder `target/wasm-extensions/phfpack/`, which holds the manifest (`engine:
  wasm`, `wasm: {module: phfpack.wasm}`), the extension's `README.md` and the module
  `phfpack.wasm`. `flm render --extensions-dir target/wasm-extensions paper.flm` then
  reads the module in place of the extension compiled into the program.

## See also

- [Stages, capabilities, and plans](crate::guide::pipeline): how the plan that runs your
  stage is derived.
- [Rendering: backends and outputs](crate::guide::rendering): lowering rules, the
  presentation vocabulary, and the standard backends.
- [The document model](crate::guide::document_model): elements, nodes and the frozen
  trees your stage reads.
- [Numbering](crate::guide::numbering): counters, counter styles and the numbering
  feature, in full.
- [Embedding flm-core](crate::guide::embedding): building a registry and running it from
  your own program.
- [Features and packages](crate::guide::concepts_overview#features-and-packages): the
  concept entry, with the API items in one list.
- [The AI guide on extending FLM](crate::guide::ai_guide_extending): the same material in
  a form written for an AI agent, with further recipes.