citationberg/
lib.rs

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
/*!
A library for parsing CSL styles.

Citationberg deserializes CSL styles from XML into Rust structs. It supports
[CSL 1.0.2](https://docs.citationstyles.org/en/stable/specification.html).

This crate is not a CSL processor, so you are free to choose whatever data
model and data types you need for your bibliographic needs. If you need to
render citations, you can use
[Hayagriva](https://github.com/typst/hayagriva) which uses this crate under
the hood.

Parse your style like this:

```rust
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::fs;
use citationberg::Style;

let string = fs::read_to_string("tests/independent/ieee.csl")?;
let style = citationberg::Style::from_xml(&string)?;

let Style::Independent(independent) = style else {
    panic!("IEEE is an independent style");
};

assert_eq!(independent.info.title.value, "IEEE");
# Ok(())
# }
```

You can also parse a [`DependentStyle`] or a [`IndependentStyle`] directly.
*/

#![deny(missing_docs)]
#![deny(unsafe_code)]

#[cfg(feature = "json")]
pub mod json;
pub mod taxonomy;

mod util;

use std::fmt::{self, Debug};
use std::iter::repeat;
use std::num::{NonZeroI16, NonZeroUsize};

use quick_xml::de::{Deserializer, SliceReader};
use serde::{Deserialize, Serialize};
use taxonomy::{
    DateVariable, Kind, Locator, NameVariable, NumberOrPageVariable, NumberVariable,
    OtherTerm, Term, Variable,
};

use self::util::*;

/// Result type for functions that serialize and deserialize XML.
pub type XmlResult<T> = Result<T, XmlError>;

/// Error type for functions that serialize and deserialize XML.
pub type XmlError = quick_xml::de::DeError;

const EVENT_BUFFER_SIZE: Option<NonZeroUsize> = NonZeroUsize::new(4096);

/// Allow every struct with formatting properties to convert to a `Formatting`.
pub trait ToFormatting {
    /// Obtain a `Formatting`.
    fn to_formatting(&self) -> Formatting;
}

macro_rules! to_formatting {
    ($name:ty, self) => {
        impl ToFormatting for $name {
            fn to_formatting(&self) -> Formatting {
                Formatting {
                    font_style: self.font_style,
                    font_variant: self.font_variant,
                    font_weight: self.font_weight,
                    text_decoration: self.text_decoration,
                    vertical_align: self.vertical_align,
                }
            }
        }
    };
    ($name:ty) => {
        impl ToFormatting for $name {
            fn to_formatting(&self) -> Formatting {
                self.formatting.clone()
            }
        }
    };
}

/// Allow every struct with affix properties to convert to a `Affixes`.
pub trait ToAffixes {
    /// Obtain the `Affixes`.
    fn to_affixes(&self) -> Affixes;
}

macro_rules! to_affixes {
    ($name:ty, self) => {
        impl ToAffixes for $name {
            fn to_affixes(&self) -> Affixes {
                Affixes {
                    prefix: self.prefix.clone(),
                    suffix: self.suffix.clone(),
                }
            }
        }
    };
    ($name:ty) => {
        impl ToAffixes for $name {
            fn to_affixes(&self) -> Affixes {
                self.affixes.clone()
            }
        }
    };
}

/// A CSL style.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
struct RawStyle {
    /// The style's metadata.
    pub info: StyleInfo,
    /// The locale used if the user didn't specify one.
    /// Overrides the default locale of the parent style.
    #[serde(rename = "@default-locale")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_locale: Option<LocaleCode>,
    /// The CSL version the style is compatible with.
    #[serde(rename = "@version")]
    pub version: String,
    /// How notes or in-text citations are displayed. Must be present in
    /// independent styles.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub citation: Option<Citation>,
    /// How bibliographies are displayed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bibliography: Option<Bibliography>,
    /// The style's settings. Must be present in dependent styles.
    #[serde(flatten)]
    pub independent_settings: Option<IndependentStyleSettings>,
    /// Reusable formatting rules.
    #[serde(rename = "macro", default)]
    pub macros: Vec<CslMacro>,
    /// Override localized strings.
    #[serde(default)]
    pub locale: Vec<Locale>,
}

impl RawStyle {
    /// Retrieve the link to the parent style for dependent styles.
    pub fn parent_link(&self) -> Option<&InfoLink> {
        self.info
            .link
            .iter()
            .find(|link| link.rel == InfoLinkRel::IndependentParent)
    }
}

impl From<IndependentStyle> for RawStyle {
    fn from(value: IndependentStyle) -> Self {
        Self {
            info: value.info,
            default_locale: value.default_locale,
            version: value.version,
            citation: Some(value.citation),
            bibliography: value.bibliography,
            independent_settings: Some(value.settings),
            macros: value.macros,
            locale: value.locale,
        }
    }
}

impl From<DependentStyle> for RawStyle {
    fn from(value: DependentStyle) -> Self {
        Self {
            info: value.info,
            default_locale: value.default_locale,
            version: value.version,
            citation: None,
            bibliography: None,
            independent_settings: None,
            macros: Vec::new(),
            locale: Vec::new(),
        }
    }
}

impl From<Style> for RawStyle {
    fn from(value: Style) -> Self {
        match value {
            Style::Independent(i) => i.into(),
            Style::Dependent(d) => d.into(),
        }
    }
}

/// An independent CSL style.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct IndependentStyle {
    /// The style's metadata.
    pub info: StyleInfo,
    /// The locale used if the user didn't specify one.
    pub default_locale: Option<LocaleCode>,
    /// The CSL version the style is compatible with.
    pub version: String,
    /// How notes or in-text citations are displayed.
    pub citation: Citation,
    /// How bibliographies are displayed.
    pub bibliography: Option<Bibliography>,
    /// The style's settings. Must be present in dependent styles.
    pub settings: IndependentStyleSettings,
    /// Reusable formatting rules.
    pub macros: Vec<CslMacro>,
    /// Override localized strings.
    pub locale: Vec<Locale>,
}

impl IndependentStyle {
    /// Create a style from an XML string.
    pub fn from_xml(xml: &str) -> XmlResult<Self> {
        let de = &mut deserializer(xml);
        IndependentStyle::deserialize(de)
    }

    /// Remove all non-required data that does not influence the style's
    /// formatting.
    pub fn purge(&mut self, level: PurgeLevel) {
        self.info.purge(level);
    }
}

/// How much metadata to remove from the style.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum PurgeLevel {
    /// Retain some basic metadata.
    Basic,
    /// Purge all metadata.
    Full,
}

impl<'de> Deserialize<'de> for IndependentStyle {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        let raw_style = RawStyle::deserialize(deserializer)?;
        let style: Style = raw_style.try_into().map_err(serde::de::Error::custom)?;

        match style {
            Style::Independent(i) => Ok(i),
            Style::Dependent(_) => Err(serde::de::Error::custom(
                "expected an independent style but got a dependent style",
            )),
        }
    }
}

/// A dependent CSL style.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct DependentStyle {
    /// The style's metadata.
    pub info: StyleInfo,
    /// The locale used if the user didn't specify one.
    /// Overrides the default locale of the parent style.
    pub default_locale: Option<LocaleCode>,
    /// The CSL version the style is compatible with.
    pub version: String,
    /// The link to the parent style.
    pub parent_link: InfoLink,
}

impl DependentStyle {
    /// Create a style from an XML string.
    pub fn from_xml(xml: &str) -> XmlResult<Self> {
        let de = &mut deserializer(xml);
        DependentStyle::deserialize(de)
    }

    /// Remove all non-required data that does not influence the style's
    /// formatting.
    pub fn purge(&mut self, level: PurgeLevel) {
        self.info.purge(level);
    }
}

impl<'de> Deserialize<'de> for DependentStyle {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        let raw_style = RawStyle::deserialize(deserializer)?;
        let style: Style = raw_style.try_into().map_err(serde::de::Error::custom)?;

        match style {
            Style::Dependent(d) => Ok(d),
            Style::Independent(_) => Err(serde::de::Error::custom(
                "expected a dependent style but got an independent style",
            )),
        }
    }
}

/// A CSL style.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[allow(clippy::large_enum_variant)]
pub enum Style {
    /// An independent style.
    Independent(IndependentStyle),
    /// A dependent style.
    Dependent(DependentStyle),
}

impl Style {
    /// Create a style from an XML string.
    pub fn from_xml(xml: &str) -> XmlResult<Self> {
        let de = &mut deserializer(xml);
        Style::deserialize(de)
    }

    /// Write the style to an XML string.
    pub fn to_xml(&self) -> XmlResult<String> {
        let mut buf = String::new();
        let ser = quick_xml::se::Serializer::with_root(&mut buf, Some("style"))?;
        self.serialize(ser)?;
        Ok(buf)
    }

    /// Remove all non-required data that does not influence the style's
    /// formatting.
    pub fn purge(&mut self, level: PurgeLevel) {
        match self {
            Self::Independent(i) => i.purge(level),
            Self::Dependent(d) => d.purge(level),
        }
    }

    /// Get the style's metadata.
    pub fn info(&self) -> &StyleInfo {
        match self {
            Self::Independent(i) => &i.info,
            Self::Dependent(d) => &d.info,
        }
    }
}

impl<'de> Deserialize<'de> for Style {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        let raw_style = RawStyle::deserialize(deserializer)?;
        raw_style.try_into().map_err(serde::de::Error::custom)
    }
}

impl Serialize for Style {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        RawStyle::from(self.clone()).serialize(serializer)
    }
}

impl TryFrom<RawStyle> for Style {
    type Error = StyleValidationError;

    fn try_from(value: RawStyle) -> Result<Self, Self::Error> {
        let has_bibliography = value.bibliography.is_some();
        if let Some(citation) = value.citation {
            if let Some(settings) = value.independent_settings {
                Ok(Self::Independent(IndependentStyle {
                    info: value.info,
                    default_locale: value.default_locale,
                    version: value.version,
                    citation,
                    bibliography: value.bibliography,
                    settings,
                    macros: value.macros,
                    locale: value.locale,
                }))
            } else {
                Err(StyleValidationError::MissingClassAttr)
            }
        } else if has_bibliography {
            Err(StyleValidationError::MissingCitation)
        } else if let Some(parent_link) = value.parent_link().cloned() {
            Ok(Self::Dependent(DependentStyle {
                info: value.info,
                default_locale: value.default_locale,
                version: value.version,
                parent_link,
            }))
        } else {
            Err(StyleValidationError::MissingParent)
        }
    }
}

/// An error that occurred while validating a style.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum StyleValidationError {
    /// The CSL style did have a `cs:bibliography` child but not a
    /// `cs:citation`.
    MissingCitation,
    /// A dependent style was missing the `independent-parent` link.
    MissingParent,
    /// An independent style was missing the `class` attribute on `cs:style`
    MissingClassAttr,
}

impl fmt::Display for StyleValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::MissingCitation => "root element is missing `cs:citation` child despite having a `cs:bibliography`",
            Self::MissingParent => "`cs:link` tag with `independent-parent` as a `rel` attribute is missing but no `cs:citation` was defined",
            Self::MissingClassAttr => "`cs:style` tag is missing the `class` attribute",
        })
    }
}

fn deserializer(xml: &str) -> Deserializer<SliceReader<'_>> {
    let mut style_deserializer = Deserializer::from_str(xml);
    style_deserializer.event_buffer_size(EVENT_BUFFER_SIZE);
    style_deserializer
}

/// A style with its own formatting rules.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct IndependentStyleSettings {
    /// How the citations are displayed.
    #[serde(rename = "@class")]
    pub class: StyleClass,
    /// Whether to use a hyphen when initializing a name.
    ///
    /// Defaults to `true`.
    #[serde(
        rename = "@initialize-with-hyphen",
        default = "IndependentStyleSettings::default_initialize_with_hyphen",
        deserialize_with = "deserialize_bool"
    )]
    pub initialize_with_hyphen: bool,
    /// Specifies how to reformat page ranges.
    #[serde(rename = "@page-range-format")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_range_format: Option<PageRangeFormat>,
    /// How to treat the non-dropping name particle when printing names.
    #[serde(rename = "@demote-non-dropping-particle", default)]
    pub demote_non_dropping_particle: DemoteNonDroppingParticle,
    /// Options for the names within. Only defined for dependent styles.
    #[serde(flatten)]
    pub options: InheritableNameOptions,
}

impl IndependentStyleSettings {
    /// Return the default value for `initialize_with_hyphen`.
    pub const fn default_initialize_with_hyphen() -> bool {
        true
    }
}

/// An RFC 1766 language code.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct LocaleCode(pub String);

impl<'a> LocaleCode {
    /// Get the US English locale.
    pub fn en_us() -> Self {
        Self("en-US".to_string())
    }

    /// Get the base language code.
    pub fn parse_base(&self) -> Option<BaseLanguage> {
        let mut parts = self.0.split('-').take(2);
        let first = parts.next()?;

        match first {
            "i" | "I" => {
                let second = parts.next()?;
                if second.is_empty() {
                    return None;
                }

                Some(BaseLanguage::Iana(second.to_string()))
            }
            "x" | "X" => {
                let second = parts.next()?;
                if second.len() > 8 || second.is_empty() {
                    return None;
                }

                let mut code = [0; 8];
                code[..second.len()].copy_from_slice(second.as_bytes());
                Some(BaseLanguage::Unregistered(code))
            }
            _ if first.len() == 2 => {
                let mut code = [0; 2];
                code.copy_from_slice(first.as_bytes());
                Some(BaseLanguage::Iso639_1(code))
            }
            _ => None,
        }
    }

    /// Get the language's extensions.
    pub fn extensions(&'a self) -> impl Iterator<Item = &'a str> + 'a {
        self.0
            .split('-')
            .enumerate()
            .filter_map(|(i, e)| {
                if i == 0 && ["x", "X", "i", "I"].contains(&e) {
                    None
                } else {
                    Some(e)
                }
            })
            .skip(1)
    }

    /// Check whether the language is English.
    pub fn is_english(&self) -> bool {
        let en = "en";
        let hyphen = "-";
        self.0.starts_with(en)
            && (self.0.len() == 2
                || self.0.get(en.len()..en.len() + hyphen.len()) == Some(hyphen))
    }

    /// Get the fallback locale for a locale.
    pub fn fallback(&self) -> Option<LocaleCode> {
        match self.parse_base()? {
            BaseLanguage::Iso639_1(code) => match &code {
                b"af" => Some("af-ZA"),
                b"bg" => Some("bg-BG"),
                b"ca" => Some("ca-AD"),
                b"cs" => Some("cs-CZ"),
                b"da" => Some("da-DK"),
                b"de" => Some("de-DE"),
                b"el" => Some("el-GR"),
                b"en" => Some("en-US"),
                b"es" => Some("es-ES"),
                b"et" => Some("et-EE"),
                b"fa" => Some("fa-IR"),
                b"fi" => Some("fi-FI"),
                b"fr" => Some("fr-FR"),
                b"he" => Some("he-IL"),
                b"hr" => Some("hr-HR"),
                b"hu" => Some("hu-HU"),
                b"is" => Some("is-IS"),
                b"it" => Some("it-IT"),
                b"ja" => Some("ja-JP"),
                b"km" => Some("km-KH"),
                b"ko" => Some("ko-KR"),
                b"lt" => Some("lt-LT"),
                b"lv" => Some("lv-LV"),
                b"mn" => Some("mn-MN"),
                b"nb" => Some("nb-NO"),
                b"nl" => Some("nl-NL"),
                b"nn" => Some("nn-NO"),
                b"pl" => Some("pl-PL"),
                b"pt" => Some("pt-PT"),
                b"ro" => Some("ro-RO"),
                b"ru" => Some("ru-RU"),
                b"sk" => Some("sk-SK"),
                b"sl" => Some("sl-SI"),
                b"sr" => Some("sr-RS"),
                b"sv" => Some("sv-SE"),
                b"th" => Some("th-TH"),
                b"tr" => Some("tr-TR"),
                b"uk" => Some("uk-UA"),
                b"vi" => Some("vi-VN"),
                b"zh" => Some("zh-CN"),
                _ => None,
            }
            .map(ToString::to_string)
            .map(LocaleCode)
            .filter(|f| f != self),
            _ => None,
        }
    }
}

impl fmt::Display for LocaleCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// The base language in a [`LocaleCode`].
pub enum BaseLanguage {
    /// A language code.
    Iso639_1([u8; 2]),
    /// An IANA language code.
    Iana(String),
    /// An unregistered / experimental language code.
    Unregistered([u8; 8]),
}

impl BaseLanguage {
    /// Get the language code.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Iso639_1(code) => std::str::from_utf8(code).unwrap(),
            Self::Iana(code) => code,
            Self::Unregistered(code) => std::str::from_utf8(code).unwrap(),
        }
    }
}

/// How the citations are displayed.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum StyleClass {
    /// Citations are inlined in the text.
    InText,
    /// Citations are displayed in foot- or endnotes.
    Note,
}

/// How to reformat page ranges.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PageRangeFormat {
    /// ā€œ321ā€“28ā€
    /// Aliases: `chicago` until CSL 1.1
    // Rename needed because the number is not used as word boundary by heck.
    #[serde(alias = "chicago")]
    #[serde(rename = "chicago-15")]
    Chicago15,
    /// ā€œ321ā€“28ā€
    #[serde(rename = "chicago-16")]
    Chicago16,
    /// ā€œ321ā€“328ā€
    #[default]
    Expanded,
    /// ā€œ321ā€“8ā€
    Minimal,
    /// ā€œ321ā€“28ā€
    MinimalTwo,
}

impl PageRangeFormat {
    /// Use a page range format to format a range of pages.
    ///
    /// Closely follows the [Haskell implementation of pandoc](https://hackage.haskell.org/package/citeproc-0.8.1/docs/src/Citeproc.Eval.html#pageRange).
    pub fn format(
        self,
        buf: &mut impl fmt::Write,
        start: &str,
        end: &str,
        separator: Option<&str>,
    ) -> Result<(), fmt::Error> {
        let separator = separator.unwrap_or("ā€“");
        let start = start.trim();
        let end = end.trim();

        // Split into the maximal suffix that is all digits (`x`|`y`),
        // and the prefix.
        let (start_pre, x) = split_max_digit_suffix(start);
        let (end_pre, y) = split_max_digit_suffix(end);

        if start_pre == end_pre {
            let pref = start_pre;
            let x_len = x.len();
            let y_len = y.len();
            // If `y` is shorter, it is a shorthand notation, e.g., `101-7`.
            let y = if x_len <= y_len {
                y.to_string()
            } else {
                // Expand `y` to include the missing starting digits from `x`.
                let mut s = x[..(x_len - y_len)].to_string();
                s.push_str(y);
                s
            };

            // Write what stays the same early
            write!(buf, "{pref}{x}{separator}")?;

            // https://docs.citationstyles.org/en/stable/specification.html#appendix-v-page-range-formats
            match self {
                PageRangeFormat::Chicago15 | PageRangeFormat::Chicago16
                    if x_len < 3 || x.ends_with("00") =>
                {
                    // For `x` < 100 or multiples of 100, write all digits.
                    write!(buf, "{y}")
                }
                PageRangeFormat::Chicago15 | PageRangeFormat::Chicago16
                    if x[x_len - 2..].starts_with('0') =>
                {
                    // For 1 < `x` % 100 < 10, use changed part only.
                    minimal(buf, 1, x, &y)
                }
                PageRangeFormat::Chicago15
                    if x_len == 4 && changed_digits(x, &y) >= 3 =>
                {
                    // If `x` has 4 digits and 3 change, write all digits.
                    write!(buf, "{y}")
                }
                PageRangeFormat::Chicago15 | PageRangeFormat::Chicago16 => {
                    // Otherwise (for Chicago), write at least 2 digits.
                    minimal(buf, 2, x, &y)
                }
                PageRangeFormat::Expanded => write!(buf, "{pref}{y}"),
                PageRangeFormat::Minimal => minimal(buf, 1, x, &y),
                PageRangeFormat::MinimalTwo => minimal(buf, 2, x, &y),
            }
        } else {
            // Prefix is different, write entire range.
            write!(buf, "{start}{separator}{end}")
        }
    }
}

/// Calculates how many digits are different between `x` and `y`, starting from the back.
///
/// Returns as soon as two digits differ. (In that part we differ from the Haskell version. I think this makes more sense.)
fn changed_digits(x: &str, y: &str) -> usize {
    let x = if x.len() < y.len() {
        let mut s = String::from_iter(repeat(' ').take(y.len() - x.len()));
        s.push_str(x);
        s
    } else {
        x.to_string()
    };
    debug_assert!(x.len() == y.len());
    let xs = x.chars().rev();
    let ys = y.chars().rev();

    for (i, (c, d)) in xs.zip(ys).enumerate() {
        if c == d {
            return i;
        }
    }

    x.len()
}

/// Writes the minimal digits that have changed from `x` to `y`---but at minimum `thresh` digits---to `buf`.
fn minimal(
    buf: &mut impl fmt::Write,
    thresh: usize,
    x: &str,
    y: &str,
) -> Result<(), fmt::Error> {
    if y.len() > x.len() {
        // y is no abbrev. write it
        return write!(buf, "{y}");
    }

    let mut xs = String::new();
    let mut ys = String::new();
    for (c, d) in x.chars().zip(y.chars()).skip_while(|(c, d)| c == d) {
        xs.push(c);
        ys.push(d);
    }

    if ys.len() < thresh && y.len() >= thresh {
        write!(buf, "{}", &y[(y.len() - thresh)..])
    } else {
        write!(buf, "{ys}")
    }
}

/// Split `s` into the maximal suffix that is only digits and a prefix.
fn split_max_digit_suffix(s: &str) -> (&str, &str) {
    let suffix_len = s.chars().rev().take_while(|c| c.is_ascii_digit()).count();
    let idx = s.len() - suffix_len;
    (&s[..idx], &s[idx..])
}

/// How to treat the non-dropping name particle when printing names.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DemoteNonDroppingParticle {
    /// Treat as part of the first name.
    Never,
    /// Treat as part of the first name except when sorting.
    SortOnly,
    /// Treat as part of the family name.
    #[default]
    DisplayAndSort,
}

/// Citation style metadata
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct StyleInfo {
    /// The authors of the style
    #[serde(rename = "author")]
    #[serde(default)]
    pub authors: Vec<StyleAttribution>,
    /// Contributors to the style
    #[serde(rename = "contributor")]
    #[serde(default)]
    pub contibutors: Vec<StyleAttribution>,
    /// Which format the citations are in.
    #[serde(default)]
    pub category: Vec<StyleCategory>,
    /// Which academic field the style is used in.
    #[serde(default)]
    pub field: Vec<Field>,
    /// A unique identifier for the style. May be a URL or an UUID.
    pub id: String,
    /// The ISSN for the source of the style's publication.
    #[serde(default)]
    pub issn: Vec<String>,
    /// The eISSN for the source of the style's publication.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub eissn: Option<String>,
    /// The ISSN-L for the source of the style's publication.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issnl: Option<String>,
    /// Links with more information about the style.
    #[serde(default)]
    pub link: Vec<InfoLink>,
    /// When the style was initially published.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub published: Option<Timestamp>,
    /// Under which license the style is published.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rights: Option<License>,
    /// A short description of the style.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<LocalString>,
    /// The title of the style.
    pub title: LocalString,
    /// A shortened version of the title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title_short: Option<LocalString>,
    /// When the style was last updated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated: Option<Timestamp>,
}

impl StyleInfo {
    /// Remove all non-required fields.
    pub fn purge(&mut self, level: PurgeLevel) {
        self.field.clear();
        self.issn.clear();
        self.eissn = None;
        self.issnl = None;
        self.published = None;
        self.summary = None;
        self.updated = None;

        match level {
            PurgeLevel::Basic => {
                for person in self.authors.iter_mut().chain(self.contibutors.iter_mut()) {
                    person.email = None;
                    person.uri = None;
                }
                self.link.retain(|i| {
                    matches!(i.rel, InfoLinkRel::IndependentParent | InfoLinkRel::Zelf)
                });
            }
            PurgeLevel::Full => {
                self.authors.clear();
                self.contibutors.clear();
                self.link.retain(|i| i.rel == InfoLinkRel::IndependentParent);
                self.rights = None;
            }
        }
    }
}

/// A string annotated with a locale.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct LocalString {
    /// The string's locale.
    #[serde(rename = "@lang")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lang: Option<LocaleCode>,
    /// The string's value.
    #[serde(rename = "$value", default)]
    pub value: String,
}

/// A person affiliated with the style.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct StyleAttribution {
    /// The person's name.
    pub name: String,
    /// The person's email address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// A URI for the person.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uri: Option<String>,
}

/// Which category this style belongs in.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(untagged)]
pub enum StyleCategory {
    /// Which format the citations are in. May only appear once as a child of `category`.
    CitationFormat {
        /// Which format the citations are in.
        #[serde(rename = "@citation-format")]
        format: CitationFormat,
    },
    /// Which academic field the style is used in. May appear multiple times as a child of `category`.
    Field {
        /// Which academic field the style is used in.
        #[serde(rename = "@field")]
        field: Field,
    },
}

/// What type of in-text citation is used.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CitationFormat {
    /// ā€œā€¦ (Doe, 1999)ā€
    AuthorDate,
    /// ā€œā€¦ (Doe)ā€
    Author,
    /// ā€œā€¦ \[1\]ā€
    Numeric,
    /// ā€œā€¦ \[doe99\]ā€
    Label,
    /// The citation appears as a foot- or endnote.
    Note,
}

/// In which academic field the style is used.
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Field {
    Anthropology,
    Astronomy,
    Biology,
    Botany,
    Chemistry,
    Communications,
    Engineering,
    /// Used for generic styles like Harvard and APA.
    #[serde(rename = "generic-base")]
    GenericBase,
    Geography,
    Geology,
    History,
    Humanities,
    Law,
    Linguistics,
    Literature,
    Math,
    Medicine,
    Philosophy,
    Physics,
    PoliticalScience,
    Psychology,
    Science,
    SocialScience,
    Sociology,
    Theology,
    Zoology,
}

/// A link with more information about the style.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct InfoLink {
    /// The link's URL.
    #[serde(rename = "@href")]
    pub href: String,
    /// How the link relates to the style.
    #[serde(rename = "@rel")]
    pub rel: InfoLinkRel,
    /// A human-readable description of the link.
    #[serde(rename = "$value")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The link's locale.
    #[serde(rename = "@xml:lang")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<LocaleCode>,
}

/// How a link relates to the style.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum InfoLinkRel {
    /// Website of the style.
    #[serde(rename = "self")]
    Zelf,
    /// URL from which the style is derived. Must not appear in dependent styles.
    Template,
    /// URL of the style's documentation.
    Documentation,
    /// Parent of a dependent style. Must appear in dependent styles.
    IndependentParent,
}

/// An ISO 8601 chapter 5.4 timestamp.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Timestamp {
    /// The timestamp's value.
    #[serde(rename = "$text")]
    pub raw: String,
}

/// A license description.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct License {
    /// The license's name.
    #[serde(rename = "$text")]
    pub name: String,
    /// The license's URL.
    #[serde(rename = "@license")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub license: Option<String>,
    /// The license string's locale.
    #[serde(rename = "@xml:lang")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lang: Option<LocaleCode>,
}

/// Formatting instructions for in-text or note citations.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Citation {
    /// How items are sorted within the citation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<Sort>,
    /// The citation's formatting rules.
    pub layout: Layout,
    /// Expand names that are ambiguous in short form.
    ///
    /// Default: `false`
    #[serde(
        rename = "@disambiguate-add-givenname",
        default,
        deserialize_with = "deserialize_bool"
    )]
    pub disambiguate_add_givenname: bool,
    /// When to expand names that are ambiguous in short form.
    #[serde(rename = "@givenname-disambiguation-rule", default)]
    pub givenname_disambiguation_rule: DisambiguationRule,
    /// Disambiguate by adding more names that would otherwise be hidden by et al.
    ///
    /// Default: `false`
    #[serde(
        rename = "@disambiguate-add-names",
        default,
        deserialize_with = "deserialize_bool"
    )]
    pub disambiguate_add_names: bool,
    /// Disambiguate by adding an alphabetical suffix to the year.
    ///
    /// Default: `false`
    #[serde(
        rename = "@disambiguate-add-year-suffix",
        default,
        deserialize_with = "deserialize_bool"
    )]
    pub disambiguate_add_year_suffix: bool,
    /// Group items in cite by name.
    #[serde(rename = "@cite-group-delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cite_group_delimiter: Option<String>,
    /// How to collapse cites with similar items.
    #[serde(rename = "@collapse")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collapse: Option<Collapse>,
    /// Delimiter between year suffixes.
    #[serde(rename = "@year-suffix-delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub year_suffix_delimiter: Option<String>,
    /// Delimiter after a collapsed cite group.
    #[serde(rename = "@after-collapse-delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after_collapse_delimiter: Option<String>,
    /// When near-note-distance is true.
    ///
    /// Default: `5`
    #[serde(
        rename = "@near-note-distance",
        default = "Citation::default_near_note_distance",
        deserialize_with = "deserialize_u32"
    )]
    pub near_note_distance: u32,
    /// Options for the names within.
    #[serde(flatten)]
    pub name_options: InheritableNameOptions,
}

impl Citation {
    /// Return the default value for `cite_group_delimiter` if implicitly needed
    /// due to presence of a `collapse` attribute.
    pub const DEFAULT_CITE_GROUP_DELIMITER: &'static str = ", ";

    /// Return a citation with default settings and the given layout.
    pub fn with_layout(layout: Layout) -> Self {
        Self {
            sort: None,
            layout,
            disambiguate_add_givenname: false,
            givenname_disambiguation_rule: DisambiguationRule::default(),
            disambiguate_add_names: false,
            disambiguate_add_year_suffix: false,
            cite_group_delimiter: None,
            collapse: None,
            year_suffix_delimiter: None,
            after_collapse_delimiter: None,
            near_note_distance: Self::default_near_note_distance(),
            name_options: Default::default(),
        }
    }

    /// Return the `year_suffix_delimiter`.
    pub fn get_year_suffix_delimiter(&self) -> &str {
        self.year_suffix_delimiter
            .as_deref()
            .or(self.layout.delimiter.as_deref())
            .unwrap_or_default()
    }

    /// Return the `after_collapse_delimiter`.
    pub fn get_after_collapse_delimiter(&self) -> &str {
        self.after_collapse_delimiter
            .as_deref()
            .or(self.layout.delimiter.as_deref())
            .unwrap_or_default()
    }

    /// Return the default `near_note_distance`.
    pub const fn default_near_note_distance() -> u32 {
        5
    }
}

/// When to expand names that are ambiguous in short form.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DisambiguationRule {
    /// Expand to disambiguate both cites and names.
    AllNames,
    /// Expand to disambiguate cites and names but only use initials.
    AllNamesWithInitials,
    /// Same as `AllNames` but only disambiguate the first person in a citation.
    PrimaryName,
    /// Same as `AllNamesWithInitials` but only disambiguate the first person in a citation.
    PrimaryNameWithInitials,
    /// Expand to disambiguate cites but not names.
    #[default]
    ByCite,
}

impl DisambiguationRule {
    /// Whether this rule allows full first names or only initials.
    pub fn allows_full_first_names(self) -> bool {
        match self {
            Self::AllNames | Self::PrimaryName | Self::ByCite => true,
            Self::AllNamesWithInitials | Self::PrimaryNameWithInitials => false,
        }
    }

    /// Whether this rule allows looking beyond the first name.
    pub fn allows_multiple_names(self) -> bool {
        match self {
            Self::AllNames | Self::AllNamesWithInitials | Self::ByCite => true,
            Self::PrimaryName | Self::PrimaryNameWithInitials => false,
        }
    }
}

/// How to collapse cites with similar items.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Collapse {
    /// Collapse items with increasing ranges for numeric styles.
    CitationNumber,
    /// Collapse items with the same authors and different years by omitting the author.
    Year,
    /// Same as `Year`, but equal years are omitted as well.
    YearSuffix,
    /// Same as `YearSuffix`, but also collapse the suffixes into a range.
    YearSuffixRanged,
}

/// Formatting instructions for the bibliography.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Bibliography {
    /// How items are sorted within the citation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<Sort>,
    /// The citation's formatting rules.
    pub layout: Layout,
    /// Render the bibliography in a hanging indent.
    ///
    /// Default: `false`
    #[serde(rename = "@hanging-indent", default, deserialize_with = "deserialize_bool")]
    pub hanging_indent: bool,
    /// When set, the second field is aligned.
    #[serde(rename = "@second-field-align")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub second_field_align: Option<SecondFieldAlign>,
    /// The line spacing within the bibliography as a multiple of regular line spacing.
    #[serde(rename = "@line-spacing", default = "Bibliography::default_line_spacing")]
    pub line_spacing: NonZeroI16,
    /// Extra space between entries as a multiple of line height.
    #[serde(rename = "@entry-spacing", default = "Bibliography::default_entry_spacing")]
    pub entry_spacing: i16,
    /// When set, subsequent identical names are replaced with this.
    #[serde(rename = "@subsequent-author-substitute")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subsequent_author_substitute: Option<String>,
    /// How to replace subsequent identical names.
    #[serde(rename = "@subsequent-author-substitute-rule", default)]
    pub subsequent_author_substitute_rule: SubsequentAuthorSubstituteRule,
    /// Options for the names within.
    #[serde(flatten)]
    pub name_options: InheritableNameOptions,
}

impl Bibliography {
    /// Return a bibliography with default settings and the given layout.
    pub fn with_layout(layout: Layout) -> Self {
        Self {
            sort: None,
            layout,
            hanging_indent: false,
            second_field_align: None,
            line_spacing: Self::default_line_spacing(),
            entry_spacing: Self::default_entry_spacing(),
            subsequent_author_substitute: None,
            subsequent_author_substitute_rule: Default::default(),
            name_options: Default::default(),
        }
    }

    /// Return the default `line_spacing`.
    fn default_line_spacing() -> NonZeroI16 {
        NonZeroI16::new(1).unwrap()
    }

    /// Return the default `entry_spacing`.
    const fn default_entry_spacing() -> i16 {
        1
    }
}

/// How to position the first field if the second field is aligned in a bibliography.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SecondFieldAlign {
    /// Put the first field in the margin and align with the margin.
    Margin,
    /// Flush the first field with the margin.
    Flush,
}

/// How to replace subsequent identical names in a bibliography.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SubsequentAuthorSubstituteRule {
    /// When all names match, replace.
    #[default]
    CompleteAll,
    /// When all names match, replace each name.
    CompleteEach,
    /// Each matching name is replaced.
    PartialEach,
    /// Only the first matching name is replaced.
    PartialFirst,
}

/// How to sort elements in a bibliography or citation.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Sort {
    /// The ordered list of sorting keys.
    #[serde(rename = "key")]
    pub keys: Vec<SortKey>,
}

/// A sorting key.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(untagged)]
pub enum SortKey {
    /// Sort by the value of a variable.
    Variable {
        /// The variable to sort by.
        #[serde(rename = "@variable")]
        variable: Variable,
        /// In which direction to sort.
        #[serde(rename = "@sort", default)]
        sort_direction: SortDirection,
    },
    /// Sort by the output of a macro.
    MacroName {
        /// The name of the macro.
        #[serde(rename = "@macro")]
        name: String,
        /// Override `[InheritedNameOptions::et_al_min]` and
        /// `[InheritedNameOptions::et_al_subsequent_min]` for macros.
        #[serde(
            rename = "@names-min",
            deserialize_with = "deserialize_u32_option",
            default
        )]
        #[serde(skip_serializing_if = "Option::is_none")]
        names_min: Option<u32>,
        /// Override `[InheritedNameOptions::et_al_use_first]` and
        /// `[InheritedNameOptions::et_al_subsequent_use_first]` for macros.
        #[serde(
            rename = "@names-use-first",
            deserialize_with = "deserialize_u32_option",
            default
        )]
        #[serde(skip_serializing_if = "Option::is_none")]
        names_use_first: Option<u32>,
        /// Override `[InheritedNameOptions::et_al_use_last]` for macros.
        #[serde(
            rename = "@names-use-last",
            deserialize_with = "deserialize_bool_option",
            default
        )]
        #[serde(skip_serializing_if = "Option::is_none")]
        names_use_last: Option<bool>,
        /// In which direction to sort.
        #[serde(rename = "@sort", default)]
        sort_direction: SortDirection,
    },
}

impl From<Variable> for SortKey {
    fn from(value: Variable) -> Self {
        Self::Variable {
            variable: value,
            sort_direction: SortDirection::default(),
        }
    }
}

impl SortKey {
    /// Retrieve the sort direction.
    pub const fn sort_direction(&self) -> SortDirection {
        match self {
            Self::Variable { sort_direction, .. } => *sort_direction,
            Self::MacroName { sort_direction, .. } => *sort_direction,
        }
    }
}

/// The direction to sort in.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SortDirection {
    /// Sort in ascending order.
    #[default]
    Ascending,
    /// Sort in descending order.
    Descending,
}

/// A formatting rule.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Layout {
    /// Parts of the rule.
    #[serde(rename = "$value")]
    pub elements: Vec<LayoutRenderingElement>,
    // Formatting and affixes fields are rolled into this because
    // #[serde(flatten)] doesn't work with $value fields.
    /// Set the font style.
    #[serde(rename = "@font-style")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_style: Option<FontStyle>,
    /// Choose normal or small caps.
    #[serde(rename = "@font-variant")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_variant: Option<FontVariant>,
    /// Set the font weight.
    #[serde(rename = "@font-weight")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_weight: Option<FontWeight>,
    /// Choose underlining.
    #[serde(rename = "@text-decoration")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_decoration: Option<TextDecoration>,
    /// Choose vertical alignment.
    #[serde(rename = "@vertical-align")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vertical_align: Option<VerticalAlign>,
    /// The prefix.
    #[serde(rename = "@prefix")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    /// The suffix.
    #[serde(rename = "@suffix")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,
    /// Delimit pieces of the output.
    #[serde(rename = "@delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter: Option<String>,
}

to_formatting!(Layout, self);
to_affixes!(Layout, self);

impl Layout {
    /// Return a layout.
    pub fn new(
        elements: Vec<LayoutRenderingElement>,
        formatting: Formatting,
        affixes: Option<Affixes>,
        delimiter: Option<String>,
    ) -> Self {
        let (prefix, suffix) = if let Some(affixes) = affixes {
            (affixes.prefix, affixes.suffix)
        } else {
            (None, None)
        };

        Self {
            elements,
            font_style: formatting.font_style,
            font_variant: formatting.font_variant,
            font_weight: formatting.font_weight,
            text_decoration: formatting.text_decoration,
            vertical_align: formatting.vertical_align,
            prefix,
            suffix,
            delimiter,
        }
    }

    /// Return a layout with default settings and the given elements.
    pub fn with_elements(elements: Vec<LayoutRenderingElement>) -> Self {
        Self::new(elements, Formatting::default(), None, None)
    }

    /// Find the child element that will render the given variable.
    pub fn find_variable_element(
        &self,
        variable: Variable,
        macros: &[CslMacro],
    ) -> Option<LayoutRenderingElement> {
        self.elements
            .iter()
            .find_map(|e| e.find_variable_element(variable, macros))
    }
}

/// Possible parts of a formatting rule.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum LayoutRenderingElement {
    /// Insert a term or variable.
    Text(Text),
    /// Format a date.
    Date(Date),
    /// Format a number.
    Number(Number),
    /// Format a list of names.
    Names(Names),
    /// Prints a label for a variable.
    Label(Label),
    /// Container for rendering elements.
    Group(Group),
    /// Conditional rendering.
    Choose(Choose),
}

impl LayoutRenderingElement {
    /// Find the child element that will render the given variable.
    pub fn find_variable_element(
        &self,
        variable: Variable,
        macros: &[CslMacro],
    ) -> Option<Self> {
        match self {
            Self::Text(t) => t.find_variable_element(variable, macros),
            Self::Choose(c) => c.find_variable_element(variable, macros),
            Self::Date(d) => {
                if d.variable.map(Variable::Date) == Some(variable) {
                    Some(self.clone())
                } else {
                    None
                }
            }
            Self::Number(n) => {
                if Variable::Number(n.variable) == variable {
                    Some(self.clone())
                } else {
                    None
                }
            }
            Self::Names(n) => {
                if n.variable.iter().any(|v| Variable::Name(*v) == variable) {
                    Some(self.clone())
                } else {
                    None
                }
            }
            Self::Group(g) => g
                .children
                .iter()
                .find_map(|e| e.find_variable_element(variable, macros)),
            Self::Label(_) => None,
        }
    }
}

/// Rendering elements.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RenderingElement {
    /// A layout element.
    Layout(Layout),
    /// Other rendering elements.
    Other(LayoutRenderingElement),
}

/// Print a term or variable.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Text {
    /// The term or variable to print.
    #[serde(flatten)]
    pub target: TextTarget,
    /// Override formatting style.
    #[serde(flatten)]
    pub formatting: Formatting,
    /// Add prefix and suffix.
    #[serde(flatten)]
    pub affixes: Affixes,
    /// Set layout level.
    #[serde(rename = "@display")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display: Option<Display>,
    /// Whether to wrap this text in quotes.
    ///
    /// Default: `false`
    #[serde(rename = "@quotes", default, deserialize_with = "deserialize_bool")]
    pub quotes: bool,
    /// Remove periods from the output.
    ///
    /// Default: `false`
    #[serde(rename = "@strip-periods", default, deserialize_with = "deserialize_bool")]
    pub strip_periods: bool,
    /// Transform the text case.
    #[serde(rename = "@text-case")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_case: Option<TextCase>,
}

impl Text {
    /// Return a text with default settings and the given target.
    pub fn with_target(target: impl Into<TextTarget>) -> Self {
        Self {
            target: target.into(),
            formatting: Default::default(),
            affixes: Default::default(),
            display: None,
            quotes: false,
            strip_periods: false,
            text_case: None,
        }
    }

    /// Find the child element that will render the given variable.
    pub fn find_variable_element(
        &self,
        variable: Variable,
        macros: &[CslMacro],
    ) -> Option<LayoutRenderingElement> {
        match &self.target {
            TextTarget::Variable { var, .. } => {
                if *var == variable {
                    Some(LayoutRenderingElement::Text(self.clone()))
                } else {
                    None
                }
            }
            TextTarget::Macro { name } => {
                if let Some(m) = macros.iter().find(|m| m.name == *name) {
                    m.children
                        .iter()
                        .find_map(|e| e.find_variable_element(variable, macros))
                } else {
                    None
                }
            }
            TextTarget::Term { .. } => None,
            TextTarget::Value { .. } => None,
        }
    }
}

to_formatting!(Text);
to_affixes!(Text);

/// Various kinds of text targets.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TextTarget {
    /// Prints the value of a variable.
    Variable {
        #[serde(rename = "@variable")]
        /// The variable to print.
        var: Variable,
        #[serde(rename = "@form", default)]
        /// The form of the variable.
        form: LongShortForm,
    },
    /// Prints the text output of a macro.
    Macro {
        #[serde(rename = "@macro")]
        /// The name of the macro.
        name: String,
    },
    /// Prints a localized term.
    Term {
        /// The term to print.
        #[serde(rename = "@term")]
        term: Term,
        /// The form of the term.
        #[serde(rename = "@form", default)]
        form: TermForm,
        /// Whether the term is pluralized.
        #[serde(rename = "@plural", default, deserialize_with = "deserialize_bool")]
        plural: bool,
    },
    /// Prints a given string.
    Value {
        #[serde(rename = "@value")]
        /// The string to print.
        val: String,
    },
}

impl From<Variable> for TextTarget {
    fn from(value: Variable) -> Self {
        Self::Variable { var: value, form: LongShortForm::default() }
    }
}

impl From<Term> for TextTarget {
    fn from(value: Term) -> Self {
        Self::Term {
            term: value,
            form: TermForm::default(),
            plural: bool::default(),
        }
    }
}

/// Formats a date.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Date {
    /// The date to format.
    #[serde(rename = "@variable")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variable: Option<DateVariable>,
    /// How the localized date should be formatted.
    #[serde(rename = "@form")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub form: Option<DateForm>,
    /// Which parts of the localized date should be included.
    #[serde(rename = "@date-parts")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parts: Option<DateParts>,
    /// Override the default date parts. Also specifies the order of the parts
    /// if `form` is `None`.
    #[serde(default)]
    pub date_part: Vec<DatePart>,
    /// Override formatting style.
    #[serde(flatten)]
    pub formatting: Formatting,
    /// Add prefix and suffix. Ignored when this defines a localized date format.
    #[serde(flatten)]
    pub affixes: Affixes,
    /// Delimit pieces of the output. Ignored when this defines a localized date format.
    #[serde(rename = "@delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter: Option<String>,
    /// Set layout level.
    #[serde(rename = "@display")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display: Option<Display>,
    /// Transform the text case.
    #[serde(rename = "@text-case")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_case: Option<TextCase>,
}

to_formatting!(Date);
to_affixes!(Date);

impl Date {
    /// Whether this is a localized or a standalone date.
    pub const fn is_localized(&self) -> bool {
        self.form.is_some()
    }
}

/// Localized date formats.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DateForm {
    /// ā€œ12-15-2005ā€
    Numeric,
    /// ā€œDecember 15, 2005ā€
    Text,
}

/// Which parts of a date should be included.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[allow(missing_docs)]
#[serde(rename_all = "kebab-case")]
pub enum DateParts {
    Year,
    YearMonth,
    #[default]
    YearMonthDay,
}

impl DateParts {
    /// Check if the date shall contain a month.
    pub const fn has_month(self) -> bool {
        matches!(self, Self::YearMonth | Self::YearMonthDay)
    }

    /// Check if the date shall contain a day.
    pub const fn has_day(self) -> bool {
        matches!(self, Self::YearMonthDay)
    }
}

/// Override the default date parts.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct DatePart {
    /// Kind of the date part.
    #[serde(rename = "@name")]
    pub name: DatePartName,
    /// Form of the date part.
    #[serde(rename = "@form")]
    #[serde(skip_serializing_if = "Option::is_none")]
    form: Option<DateAnyForm>,
    /// The string used to delimit two date parts.
    #[serde(rename = "@range-delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range_delimiter: Option<String>,
    /// Override formatting style.
    #[serde(flatten)]
    pub formatting: Formatting,
    /// Add prefix and suffix. Ignored when this defines a localized date format.
    #[serde(flatten)]
    pub affixes: Affixes,
    /// Remove periods from the date part.
    ///
    /// Default: `false`
    #[serde(rename = "@strip-periods", default, deserialize_with = "deserialize_bool")]
    pub strip_periods: bool,
    /// Transform the text case.
    #[serde(rename = "@text-case")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_case: Option<TextCase>,
}

to_formatting!(DatePart);
to_affixes!(DatePart);

impl DatePart {
    /// Retrieve the default delimiter for the date part.
    pub const DEFAULT_DELIMITER: &'static str = "ā€“";

    /// Retrieve the form.
    pub fn form(&self) -> DateStrongAnyForm {
        DateStrongAnyForm::for_name(self.name, self.form)
    }
}

/// The kind of a date part with its `form` attribute.
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DatePartName {
    Day,
    Month,
    Year,
}

/// Any allowable date part format.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DateAnyForm {
    /// ā€œ1ā€
    Numeric,
    /// ā€œ01ā€
    NumericLeadingZeros,
    /// ā€œ1stā€
    Ordinal,
    /// ā€œJanuaryā€
    Long,
    /// ā€œJan.ā€
    Short,
}

/// Strongly typed date part formats.
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum DateStrongAnyForm {
    Day(DateDayForm),
    Month(DateMonthForm),
    Year(LongShortForm),
}

impl DateStrongAnyForm {
    /// Get a strongly typed date form for a name. Must return `Some` for valid
    /// CSL files.
    pub fn for_name(name: DatePartName, form: Option<DateAnyForm>) -> Self {
        match name {
            DatePartName::Day => {
                Self::Day(form.map(DateAnyForm::form_for_day).unwrap_or_default())
            }
            DatePartName::Month => {
                Self::Month(form.map(DateAnyForm::form_for_month).unwrap_or_default())
            }
            DatePartName::Year => {
                Self::Year(form.map(DateAnyForm::form_for_year).unwrap_or_default())
            }
        }
    }
}

impl DateAnyForm {
    /// Retrieve the form for a day.
    pub fn form_for_day(self) -> DateDayForm {
        match self {
            Self::NumericLeadingZeros => DateDayForm::NumericLeadingZeros,
            Self::Ordinal => DateDayForm::Ordinal,
            _ => DateDayForm::default(),
        }
    }

    /// Retrieve the form for a month.
    pub fn form_for_month(self) -> DateMonthForm {
        match self {
            Self::Short => DateMonthForm::Short,
            Self::Numeric => DateMonthForm::Numeric,
            Self::NumericLeadingZeros => DateMonthForm::NumericLeadingZeros,
            _ => DateMonthForm::default(),
        }
    }

    /// Retrieve the form for a year.
    pub fn form_for_year(self) -> LongShortForm {
        match self {
            Self::Short => LongShortForm::Short,
            _ => LongShortForm::default(),
        }
    }
}

/// How a day is formatted.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DateDayForm {
    /// ā€œ1ā€
    #[default]
    Numeric,
    /// ā€œ01ā€
    NumericLeadingZeros,
    /// ā€œ1stā€
    Ordinal,
}

/// How a month is formatted.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DateMonthForm {
    /// ā€œJanuaryā€
    #[default]
    Long,
    /// ā€œJan.ā€
    Short,
    /// ā€œ1ā€
    Numeric,
    /// ā€œ01ā€
    NumericLeadingZeros,
}

/// Whether to format something in long or short form.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum LongShortForm {
    #[default]
    Long,
    Short,
}

/// Renders a number.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Number {
    /// The variable whose value is used.
    #[serde(rename = "@variable")]
    pub variable: NumberVariable,
    /// How the number is formatted.
    #[serde(rename = "@form", default)]
    pub form: NumberForm,
    /// Override formatting style.
    #[serde(flatten)]
    pub formatting: Formatting,
    /// Add prefix and suffix.
    #[serde(flatten)]
    pub affixes: Affixes,
    /// Set layout level.
    #[serde(rename = "@display")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display: Option<Display>,
    /// Transform the text case.
    #[serde(rename = "@text-case")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_case: Option<TextCase>,
}

to_formatting!(Number);
to_affixes!(Number);

/// How a number is formatted.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum NumberForm {
    /// ā€œ1ā€
    #[default]
    Numeric,
    /// ā€œ1stā€
    Ordinal,
    /// ā€œfirstā€
    LongOrdinal,
    /// ā€œIā€
    Roman,
}

/// Renders a list of names.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Names {
    /// The variable whose value is used.
    #[serde(rename = "@variable", default)]
    pub variable: Vec<NameVariable>,
    /// Child elements.
    #[serde(rename = "$value", default)]
    pub children: Vec<NamesChild>,
    /// Delimiter between names.
    #[serde(rename = "@delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    delimiter: Option<String>,

    /// Delimiter between second-to-last and last name.
    #[serde(rename = "@and")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub and: Option<NameAnd>,
    /// Delimiter before et al.
    #[serde(rename = "@delimiter-precedes-et-al")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter_precedes_et_al: Option<DelimiterBehavior>,
    /// Whether to use the delimiter before the last name.
    #[serde(rename = "@delimiter-precedes-last")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter_precedes_last: Option<DelimiterBehavior>,
    /// Minimum number of names to use et al.
    #[serde(rename = "@et-al-min", deserialize_with = "deserialize_u32_option", default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_min: Option<u32>,
    /// Maximum number of names to use before et al.
    #[serde(
        rename = "@et-al-use-first",
        deserialize_with = "deserialize_u32_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_use_first: Option<u32>,
    /// Minimum number of names to use et al. for repeated citations.
    #[serde(
        rename = "@et-al-subsequent-min",
        deserialize_with = "deserialize_u32_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_subsequent_min: Option<u32>,
    /// Maximum number of names to use before et al. for repeated citations.
    #[serde(
        rename = "@et-al-subsequent-use-first",
        deserialize_with = "deserialize_u32_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_subsequent_use_first: Option<u32>,
    /// Whether to use the last name in the author list when there are at least
    /// `et_al_min` names.
    #[serde(
        rename = "@et-al-use-last",
        deserialize_with = "deserialize_bool_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_use_last: Option<bool>,
    /// Which name parts to display for personal names.
    #[serde(rename = "@name-form")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_form: Option<NameForm>,
    /// Whether to initialize the first name if `initialize-with` is Some.
    #[serde(
        rename = "@initialize",
        deserialize_with = "deserialize_bool_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initialize: Option<bool>,
    /// String to initialize the first name with.
    #[serde(rename = "@initialize-with")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initialize_with: Option<String>,
    /// Whether to turn the name around.
    #[serde(rename = "@name-as-sort-order")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_as_sort_order: Option<NameAsSortOrder>,
    /// Delimiter between given name and first name. Only used if
    /// `name-as-sort-order` is Some.
    #[serde(rename = "@sort-separator")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_separator: Option<String>,

    /// Set the font style.
    #[serde(rename = "@font-style")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_style: Option<FontStyle>,
    /// Choose normal or small caps.
    #[serde(rename = "@font-variant")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_variant: Option<FontVariant>,
    /// Set the font weight.
    #[serde(rename = "@font-weight")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_weight: Option<FontWeight>,
    /// Choose underlining.
    #[serde(rename = "@text-decoration")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_decoration: Option<TextDecoration>,
    /// Choose vertical alignment.
    #[serde(rename = "@vertical-align")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vertical_align: Option<VerticalAlign>,

    /// The prefix.
    #[serde(rename = "@prefix")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    /// The suffix.
    #[serde(rename = "@suffix")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,

    /// Set layout level.
    #[serde(rename = "@display")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display: Option<Display>,
}

impl Names {
    /// Return names with default settings and the given variables.
    pub fn with_variables(variables: Vec<NameVariable>) -> Self {
        Self {
            variable: variables,
            children: Vec::default(),
            delimiter: None,

            and: None,
            delimiter_precedes_et_al: None,
            delimiter_precedes_last: None,
            et_al_min: None,
            et_al_use_first: None,
            et_al_subsequent_min: None,
            et_al_subsequent_use_first: None,
            et_al_use_last: None,
            name_form: None,
            initialize: None,
            initialize_with: None,
            name_as_sort_order: None,
            sort_separator: None,

            font_style: None,
            font_variant: None,
            font_weight: None,
            text_decoration: None,
            vertical_align: None,

            prefix: None,
            suffix: None,

            display: None,
        }
    }

    /// Return the delimiter given some name options.
    pub fn delimiter<'a>(&'a self, name_options: &'a InheritableNameOptions) -> &'a str {
        self.delimiter
            .as_deref()
            .or(name_options.name_delimiter.as_deref())
            .unwrap_or_default()
    }

    /// Return the name element.
    pub fn name(&self) -> Option<&Name> {
        self.children.iter().find_map(|c| match c {
            NamesChild::Name(n) => Some(n),
            _ => None,
        })
    }

    /// Return the et-al element.
    pub fn et_al(&self) -> Option<&EtAl> {
        self.children.iter().find_map(|c| match c {
            NamesChild::EtAl(e) => Some(e),
            _ => None,
        })
    }

    /// Return the label element.
    pub fn label(&self) -> Option<(&VariablelessLabel, NameLabelPosition)> {
        let mut pos = NameLabelPosition::BeforeName;
        self.children.iter().find_map(|c| match c {
            NamesChild::Label(l) => Some((l, pos)),
            NamesChild::Name(_) => {
                pos = NameLabelPosition::AfterName;
                None
            }
            _ => None,
        })
    }

    /// Return the substitute element.
    pub fn substitute(&self) -> Option<&Substitute> {
        self.children.iter().find_map(|c| match c {
            NamesChild::Substitute(s) => Some(s),
            _ => None,
        })
    }

    /// Return the inheritable name options.
    pub fn options(&self) -> InheritableNameOptions {
        InheritableNameOptions {
            and: self.and,
            delimiter_precedes_et_al: self.delimiter_precedes_et_al,
            delimiter_precedes_last: self.delimiter_precedes_last,
            et_al_min: self.et_al_min,
            et_al_use_first: self.et_al_use_first,
            et_al_subsequent_min: self.et_al_subsequent_min,
            et_al_subsequent_use_first: self.et_al_subsequent_use_first,
            et_al_use_last: self.et_al_use_last,
            name_form: self.name_form,
            initialize: self.initialize,
            initialize_with: self.initialize_with.clone(),
            name_as_sort_order: self.name_as_sort_order,
            sort_separator: self.sort_separator.clone(),
            name_delimiter: None,
            names_delimiter: self.delimiter.clone(),
        }
    }

    /// Convert a [`Names`] within a substitute to a name using the parent element.
    pub fn from_names_substitute(&self, child: &Self) -> Names {
        if child.name().is_some()
            || child.et_al().is_some()
            || child.substitute().is_some()
        {
            return child.clone();
        }

        let formatting = child.to_formatting().apply(self.to_formatting());
        let options = self.options().apply(&child.options());

        Names {
            variable: if child.variable.is_empty() {
                self.variable.clone()
            } else {
                child.variable.clone()
            },
            children: self
                .children
                .iter()
                .filter(|c| !matches!(c, NamesChild::Substitute(_)))
                .cloned()
                .collect(),
            delimiter: child.delimiter.clone().or_else(|| self.delimiter.clone()),

            and: options.and,
            delimiter_precedes_et_al: options.delimiter_precedes_et_al,
            delimiter_precedes_last: options.delimiter_precedes_last,
            et_al_min: options.et_al_min,
            et_al_use_first: options.et_al_use_first,
            et_al_subsequent_min: options.et_al_subsequent_min,
            et_al_subsequent_use_first: options.et_al_subsequent_use_first,
            et_al_use_last: options.et_al_use_last,
            name_form: options.name_form,
            initialize: options.initialize,
            initialize_with: options.initialize_with,
            name_as_sort_order: options.name_as_sort_order,
            sort_separator: options.sort_separator,

            font_style: formatting.font_style,
            font_variant: formatting.font_variant,
            font_weight: formatting.font_weight,
            text_decoration: formatting.text_decoration,
            vertical_align: formatting.vertical_align,

            prefix: child.prefix.clone().or_else(|| self.prefix.clone()),
            suffix: child.suffix.clone().or_else(|| self.suffix.clone()),
            display: child.display.or(self.display),
        }
    }
}

to_formatting!(Names, self);
to_affixes!(Names, self);

/// Where the `cs:label` element within a `cs:names` element appeared relative
/// to `cs:name`.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum NameLabelPosition {
    /// The label appeared after the name element.
    AfterName,
    /// The label appeared before the name element.
    BeforeName,
}

/// Possible children for a `cs:names` element.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum NamesChild {
    /// A `cs:name` element.
    Name(Name),
    /// A `cs:et-al` element.
    EtAl(EtAl),
    /// A `cs:label` element.
    Label(VariablelessLabel),
    /// A `cs:substitute` element.
    Substitute(Substitute),
}

/// Configuration of how to print names.
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", default)]
pub struct Name {
    /// Delimiter between names.
    #[serde(rename = "@delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    delimiter: Option<String>,
    /// Which name parts to display for personal names.
    #[serde(rename = "@form")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub form: Option<NameForm>,
    /// Name parts for formatting for the given and family name.
    #[serde(rename = "name-part")]
    parts: Vec<NamePart>,
    /// Options for this name.
    #[serde(flatten)]
    options: InheritableNameOptions,
    /// Override formatting style.
    #[serde(flatten)]
    pub formatting: Formatting,
    /// Add prefix and suffix.
    #[serde(flatten)]
    pub affixes: Affixes,
}

to_formatting!(Name);
to_affixes!(Name);

impl Name {
    /// Retrieve [`NamePart`] configuration for the given name.
    pub fn name_part_given(&self) -> Option<&NamePart> {
        self.parts.iter().find(|p| p.name == NamePartName::Given)
    }

    /// Retrieve [`NamePart`] configuration for the family name.
    pub fn name_part_family(&self) -> Option<&NamePart> {
        self.parts.iter().find(|p| p.name == NamePartName::Family)
    }

    /// Retrieve the [`NameOptions`] for this name.
    pub fn options<'s>(&'s self, inherited: &'s InheritableNameOptions) -> NameOptions {
        let applied = inherited.apply(&self.options);
        NameOptions {
            and: applied.and,
            delimiter: self
                .delimiter
                .as_deref()
                .or(inherited.name_delimiter.as_deref())
                .unwrap_or(", "),
            delimiter_precedes_et_al: applied
                .delimiter_precedes_et_al
                .unwrap_or_default(),
            delimiter_precedes_last: applied.delimiter_precedes_last.unwrap_or_default(),
            et_al_min: applied.et_al_min,
            et_al_use_first: applied.et_al_use_first,
            et_al_subsequent_min: applied.et_al_subsequent_min,
            et_al_subsequent_use_first: applied.et_al_subsequent_use_first,
            et_al_use_last: applied.et_al_use_last.unwrap_or_default(),
            form: self.form.or(inherited.name_form).unwrap_or_default(),
            initialize: applied.initialize.unwrap_or(true),
            initialize_with: self
                .options
                .initialize_with
                .as_deref()
                .or(inherited.initialize_with.as_deref()),
            name_as_sort_order: applied.name_as_sort_order,
            sort_separator: self
                .options
                .sort_separator
                .as_deref()
                .or(inherited.sort_separator.as_deref())
                .unwrap_or(", "),
        }
    }
}

/// Global configuration of how to print names.
#[derive(Debug, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(default)]
pub struct InheritableNameOptions {
    /// Delimiter between second-to-last and last name.
    #[serde(rename = "@and")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub and: Option<NameAnd>,
    /// Delimiter inherited to `cs:name` elements.
    #[serde(rename = "@name-delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_delimiter: Option<String>,
    /// Delimiter inherited to `cs:names` elements.
    #[serde(rename = "@names-delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub names_delimiter: Option<String>,
    /// Delimiter before et al.
    #[serde(rename = "@delimiter-precedes-et-al")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter_precedes_et_al: Option<DelimiterBehavior>,
    /// Whether to use the delimiter before the last name.
    #[serde(rename = "@delimiter-precedes-last")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter_precedes_last: Option<DelimiterBehavior>,
    /// Minimum number of names to use et al.
    #[serde(rename = "@et-al-min", deserialize_with = "deserialize_u32_option", default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_min: Option<u32>,
    /// Maximum number of names to use before et al.
    #[serde(
        rename = "@et-al-use-first",
        deserialize_with = "deserialize_u32_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_use_first: Option<u32>,
    /// Minimum number of names to use et al. for repeated citations.
    #[serde(
        rename = "@et-al-subsequent-min",
        deserialize_with = "deserialize_u32_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_subsequent_min: Option<u32>,
    /// Maximum number of names to use before et al. for repeated citations.
    #[serde(
        rename = "@et-al-subsequent-use-first",
        deserialize_with = "deserialize_u32_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_subsequent_use_first: Option<u32>,
    /// Whether to use the last name in the author list when there are at least
    /// `et_al_min` names.
    #[serde(
        rename = "@et-al-use-last",
        deserialize_with = "deserialize_bool_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub et_al_use_last: Option<bool>,
    /// Which name parts to display for personal names.
    #[serde(rename = "@name-form")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_form: Option<NameForm>,
    /// Whether to initialize the first name if `initialize-with` is Some.
    #[serde(
        rename = "@initialize",
        deserialize_with = "deserialize_bool_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initialize: Option<bool>,
    /// String to initialize the first name with.
    #[serde(rename = "@initialize-with")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initialize_with: Option<String>,
    /// Whether to turn the name around.
    #[serde(rename = "@name-as-sort-order")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_as_sort_order: Option<NameAsSortOrder>,
    /// Delimiter between given name and first name. Only used if
    /// `name-as-sort-order` is Some.
    #[serde(rename = "@sort-separator")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_separator: Option<String>,
}

/// Definite name options. Obtain from [`Name::options`] using
/// [`InheritableNameOptions`].
pub struct NameOptions<'s> {
    /// Delimiter between second-to-last and last name.
    pub and: Option<NameAnd>,
    /// Delimiter to separate names.
    pub delimiter: &'s str,
    /// Delimiter before et al.
    pub delimiter_precedes_et_al: DelimiterBehavior,
    /// Whether to use the delimiter before the last name.
    pub delimiter_precedes_last: DelimiterBehavior,
    /// Minimum number of names to use et al.
    pub et_al_min: Option<u32>,
    /// Maximum number of names to use before et al.
    pub et_al_use_first: Option<u32>,
    /// Minimum number of names to use et al. for repeated citations.
    pub et_al_subsequent_min: Option<u32>,
    /// Maximum number of names to use before et al. for repeated citations.
    pub et_al_subsequent_use_first: Option<u32>,
    /// Whether to use the last name in the author list when there are at least
    /// `et_al_min` names.
    pub et_al_use_last: bool,
    /// Which name parts to display for personal names.
    pub form: NameForm,
    /// Whether to initialize the first name if `initialize-with` is Some.
    pub initialize: bool,
    /// String to initialize the first name with.
    pub initialize_with: Option<&'s str>,
    /// Whether to turn the name around.
    pub name_as_sort_order: Option<NameAsSortOrder>,
    /// Delimiter between given name and first name. Only used if
    /// `name-as-sort-order` is Some.
    pub sort_separator: &'s str,
}

impl InheritableNameOptions {
    /// Apply the child options to the parent options.
    pub fn apply(&self, child: &Self) -> Self {
        Self {
            and: child.and.or(self.and),
            name_delimiter: child
                .name_delimiter
                .clone()
                .or_else(|| self.name_delimiter.clone()),
            names_delimiter: child
                .names_delimiter
                .clone()
                .or_else(|| self.names_delimiter.clone()),
            delimiter_precedes_et_al: child
                .delimiter_precedes_et_al
                .or(self.delimiter_precedes_et_al),
            delimiter_precedes_last: child
                .delimiter_precedes_last
                .or(self.delimiter_precedes_last),
            et_al_min: child.et_al_min.or(self.et_al_min),
            et_al_use_first: child.et_al_use_first.or(self.et_al_use_first),
            et_al_subsequent_min: child
                .et_al_subsequent_min
                .or(self.et_al_subsequent_min),
            et_al_subsequent_use_first: child
                .et_al_subsequent_use_first
                .or(self.et_al_subsequent_use_first),
            et_al_use_last: child.et_al_use_last.or(self.et_al_use_last),
            name_form: child.name_form.or(self.name_form),
            initialize: child.initialize.or(self.initialize),
            initialize_with: child
                .initialize_with
                .clone()
                .or_else(|| self.initialize_with.clone()),
            name_as_sort_order: child.name_as_sort_order.or(self.name_as_sort_order),
            sort_separator: child
                .sort_separator
                .clone()
                .or_else(|| self.sort_separator.clone()),
        }
    }
}

impl NameOptions<'_> {
    /// Whether the nth name is suppressed given the number of names and this
    /// configuration.
    pub fn is_suppressed(&self, idx: usize, length: usize, is_subsequent: bool) -> bool {
        // This is not suppressed if we print the last element and this is it.
        if self.et_al_use_last && idx + 1 >= length {
            return false;
        }

        // If this is a subsequent citation of the same item, use other CSL options, if they exist
        let (et_al_min, et_al_use_first) = if is_subsequent {
            (
                self.et_al_subsequent_min.or(self.et_al_min),
                self.et_al_subsequent_use_first.or(self.et_al_use_first),
            )
        } else {
            (self.et_al_min, self.et_al_use_first)
        };

        let et_al_min = et_al_min.map_or(usize::MAX, |u| u as usize);
        let et_al_use_first = et_al_use_first.map_or(usize::MAX, |u| u as usize);

        length >= et_al_min && idx + 1 > et_al_use_first
    }
}

/// How to render the delimiter before the last name.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum NameAnd {
    /// Use the string "and".
    Text,
    /// Use the ampersand character.
    Symbol,
}

/// When delimiters shall be inserted.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum DelimiterBehavior {
    /// Only used for lists with more than one (`-precedes-et-al`) or two
    /// (`-precedes-last`) names.
    #[default]
    Contextual,
    /// Only use if the preceding name is inverted (per `name-as-sort-order`).
    AfterInvertedName,
    /// Always use the delimiter for this condition.
    Always,
    /// Never use the delimiter for this condition.
    Never,
}

/// How many name parts to print.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum NameForm {
    /// Print all name parts
    #[default]
    Long,
    /// Print only the family name part and non-dropping-particle.
    Short,
    /// Count the total number of names.
    Count,
}

/// In which order to print the names.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum NameAsSortOrder {
    /// Only the first name is turned around.
    First,
    /// All names are turned around.
    All,
}

/// How to format a given name part.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct NamePart {
    /// Which name part this applies to.
    #[serde(rename = "@name")]
    pub name: NamePartName,
    /// Override formatting style.
    #[serde(flatten)]
    pub formatting: Formatting,
    /// Add prefix and suffix.
    #[serde(flatten)]
    pub affixes: Affixes,
    /// Transform the text case.
    #[serde(rename = "@text-case")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_case: Option<TextCase>,
}

to_formatting!(NamePart);
to_affixes!(NamePart);

/// Which part of the name a [`NamePart`] applies to.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum NamePartName {
    /// The given name.
    Given,
    /// The family name.
    Family,
}

/// Configure the et al. abbreviation.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct EtAl {
    /// Which term to use.
    #[serde(rename = "@term", default)]
    pub term: EtAlTerm,
    /// Override formatting style.
    #[serde(flatten)]
    pub formatting: Formatting,
}

to_formatting!(EtAl);

/// Which term to use for et al.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum EtAlTerm {
    /// ā€œet al.ā€
    #[default]
    #[serde(rename = "et al", alias = "et-al")]
    EtAl,
    /// ā€œand othersā€
    #[serde(rename = "and others", alias = "and-others")]
    AndOthers,
}

impl From<EtAlTerm> for Term {
    fn from(term: EtAlTerm) -> Self {
        match term {
            EtAlTerm::EtAl => Term::Other(OtherTerm::EtAl),
            EtAlTerm::AndOthers => Term::Other(OtherTerm::AndOthers),
        }
    }
}

/// What to do if the name variable is empty.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Substitute {
    /// The layout to use instead.
    #[serde(rename = "$value")]
    pub children: Vec<LayoutRenderingElement>,
}

/// Print a label for a number variable.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Label {
    /// The variable for which to print the label.
    #[serde(rename = "@variable")]
    pub variable: NumberOrPageVariable,
    /// The form of the label.
    #[serde(flatten)]
    pub label: VariablelessLabel,
}

/// A label without its variable.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct VariablelessLabel {
    /// What variant of label is chosen.
    #[serde(rename = "@form", default)]
    pub form: TermForm,
    /// How to pluiralize the label.
    #[serde(rename = "@plural", default)]
    pub plural: LabelPluralize,
    /// Override formatting style.
    #[serde(flatten)]
    pub formatting: Formatting,
    /// Add prefix and suffix.
    #[serde(flatten)]
    pub affixes: Affixes,
    /// Transform the text case.
    #[serde(rename = "@text-case")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_case: Option<TextCase>,
    /// Remove periods from the output.
    ///
    /// Default: `false`
    #[serde(rename = "@strip-periods", default, deserialize_with = "deserialize_bool")]
    pub strip_periods: bool,
}

to_formatting!(VariablelessLabel);
to_affixes!(VariablelessLabel);

/// How to pluralize a label.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum LabelPluralize {
    /// Match plurality of the variable.
    #[default]
    Contextual,
    /// Always use the plural form.
    Always,
    /// Always use the singular form.
    Never,
}

/// A group of formatting instructions that is only shown if no variable is
/// referenced or at least one referenced variable is populated.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Group {
    /// The formatting instructions.
    #[serde(rename = "$value")]
    pub children: Vec<LayoutRenderingElement>,
    // Formatting and affixes fields are rolled into this because
    // #[serde(flatten)] doesn't work with $value fields.
    /// Set the font style.
    #[serde(rename = "@font-style")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_style: Option<FontStyle>,
    /// Choose normal or small caps.
    #[serde(rename = "@font-variant")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_variant: Option<FontVariant>,
    /// Set the font weight.
    #[serde(rename = "@font-weight")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_weight: Option<FontWeight>,
    /// Choose underlining.
    #[serde(rename = "@text-decoration")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_decoration: Option<TextDecoration>,
    /// Choose vertical alignment.
    #[serde(rename = "@vertical-align")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vertical_align: Option<VerticalAlign>,
    /// The prefix.
    #[serde(rename = "@prefix")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    /// The suffix.
    #[serde(rename = "@suffix")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,
    /// Delimit pieces of the output.
    #[serde(rename = "@delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter: Option<String>,
    /// Set layout level.
    #[serde(rename = "@display")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display: Option<Display>,
}

to_formatting!(Group, self);
to_affixes!(Group, self);

/// A conditional group of formatting instructions.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Choose {
    /// If branch of the conditional group.
    #[serde(rename = "if")]
    pub if_: ChooseBranch,
    /// Other branches of the conditional group. The first matching branch is used.
    #[serde(rename = "else-if")]
    #[serde(default)]
    pub else_if: Vec<ChooseBranch>,
    /// The formatting instructions to use if no branch matches.
    #[serde(rename = "else")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub otherwise: Option<ElseBranch>,
    /// The delimiter between rendering elements in the chosen branch.
    #[serde(rename = "@delimiter")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delimiter: Option<String>,
}

impl Choose {
    /// Return an iterator over all branches with a condition.
    pub fn branches(&self) -> impl Iterator<Item = &ChooseBranch> {
        std::iter::once(&self.if_).chain(self.else_if.iter())
    }

    /// Find the child element that renders the given variable.
    pub fn find_variable_element(
        &self,
        variable: Variable,
        macros: &[CslMacro],
    ) -> Option<LayoutRenderingElement> {
        self.branches()
            .find_map(|b| {
                b.children
                    .iter()
                    .find_map(|c| c.find_variable_element(variable, macros))
            })
            .clone()
    }
}

/// A single branch of a conditional group.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct ChooseBranch {
    /// Other than this choose, two elements would result in the same
    /// rendering.
    #[serde(
        rename = "@disambiguate",
        deserialize_with = "deserialize_bool_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disambiguate: Option<bool>,
    /// The variable contains numeric data.
    #[serde(rename = "@is-numeric")]
    /// The variable contains an approximate date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_numeric: Option<Vec<Variable>>,
    /// The variable contains an approximate date.
    #[serde(rename = "@is-uncertain-date")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_uncertain_date: Option<Vec<DateVariable>>,
    /// The locator matches the given type.
    #[serde(rename = "@locator")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locator: Option<Vec<Locator>>,
    /// Tests the position of this citation in the citations to the same item.
    /// Only ever true for citations.
    #[serde(rename = "@position")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub position: Option<Vec<TestPosition>>,
    /// Tests whether the item is of a certain type.
    #[serde(rename = "@type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub type_: Option<Vec<Kind>>,
    /// Tests whether the default form of this variable is non-empty.
    #[serde(rename = "@variable")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variable: Option<Vec<Variable>>,
    /// How to handle the set of tests.
    #[serde(rename = "@match")]
    #[serde(default)]
    pub match_: ChooseMatch,
    #[serde(rename = "$value", default)]
    /// The formatting instructions to use if the condition matches.
    pub children: Vec<LayoutRenderingElement>,
}

impl ChooseBranch {
    /// Retrieve the test of this branch. Valid CSL files must return `Some`
    /// here.
    pub fn test(&self) -> Option<ChooseTest> {
        if let Some(disambiguate) = self.disambiguate {
            if !disambiguate {
                None
            } else {
                Some(ChooseTest::Disambiguate)
            }
        } else if let Some(is_numeric) = &self.is_numeric {
            Some(ChooseTest::IsNumeric(is_numeric))
        } else if let Some(is_uncertain_date) = &self.is_uncertain_date {
            Some(ChooseTest::IsUncertainDate(is_uncertain_date))
        } else if let Some(locator) = &self.locator {
            Some(ChooseTest::Locator(locator))
        } else if let Some(position) = &self.position {
            Some(ChooseTest::Position(position))
        } else if let Some(type_) = &self.type_ {
            Some(ChooseTest::Type(type_))
        } else {
            self.variable.as_ref().map(|variable| ChooseTest::Variable(variable))
        }
    }
}

/// The formatting instructions to use if no branch matches.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct ElseBranch {
    /// The formatting instructions.
    #[serde(rename = "$value")]
    pub children: Vec<LayoutRenderingElement>,
}

/// A single test in a conditional group.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum ChooseTest<'a> {
    /// Other than this choose, two elements would result in the same
    /// rendering.
    Disambiguate,
    /// The variable contains numeric data.
    IsNumeric(&'a [Variable]),
    /// The variable contains an approximate date.
    IsUncertainDate(&'a [DateVariable]),
    /// The locator matches the given type.
    Locator(&'a [Locator]),
    /// Tests the position of this citation in the citations to the same item.
    /// Only ever true for citations.
    Position(&'a [TestPosition]),
    /// Tests whether the item is of a certain type.
    Type(&'a [Kind]),
    /// Tests whether the default form of this variable is non-empty.
    Variable(&'a [Variable]),
}

/// Possible positions of a citation in the citations to the same item.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum TestPosition {
    /// The first citation to the item.
    First,
    /// Previously cited.
    Subsequent,
    /// Directly following a citation to the same item but the locators don't necessarily match.
    IbidWithLocator,
    /// Directly following a citation to the same item with the same locators.
    Ibid,
    /// Other citation within `near-note-distance` of the same item.
    NearNote,
}

/// How to handle the set of tests in a conditional group.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ChooseMatch {
    /// All tests must match.
    #[default]
    All,
    /// At least one test must match.
    Any,
    /// No test must match.
    None,
}

impl ChooseMatch {
    /// Check whether the iterator of tests is true for this match type.
    pub fn test(self, mut tests: impl Iterator<Item = bool>) -> bool {
        match self {
            Self::All => tests.all(|t| t),
            Self::Any => tests.any(|t| t),
            Self::None => tests.all(|t| !t),
        }
    }
}

/// A reusable set of formatting instructions.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct CslMacro {
    /// The name of the macro.
    #[serde(rename = "@name")]
    pub name: String,
    /// The formatting instructions.
    #[serde(rename = "$value")]
    #[serde(default)]
    pub children: Vec<LayoutRenderingElement>,
}

/// Root element of a locale file.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct LocaleFile {
    /// The version of the locale file.
    #[serde(rename = "@version")]
    pub version: String,
    /// Which languages or dialects this data applies to.
    #[serde(rename = "@lang")]
    pub lang: LocaleCode,
    /// Metadata of the locale.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<LocaleInfo>,
    /// The terms used in the locale.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub terms: Option<Terms>,
    /// How to format dates in the locale file.
    #[serde(default)]
    pub date: Vec<Date>,
    /// Style options for the locale.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style_options: Option<LocaleOptions>,
}

impl LocaleFile {
    /// Create a locale from an XML string.
    pub fn from_xml(xml: &str) -> XmlResult<Self> {
        let locale: Self = quick_xml::de::from_str(xml)?;
        Ok(locale)
    }

    /// Write the locale to an XML string.
    pub fn to_xml(&self) -> XmlResult<String> {
        let mut buf = String::new();
        let ser = quick_xml::se::Serializer::with_root(&mut buf, Some("style"))?;
        self.serialize(ser)?;
        Ok(buf)
    }
}

/// Supplemental localization data in a citation style.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Locale {
    /// Which languages or dialects this data applies to. Must be `Some` if this
    /// appears in a locale file.
    #[serde(rename = "@lang")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lang: Option<LocaleCode>,
    /// Metadata of the locale.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub info: Option<LocaleInfo>,
    /// The terms used in the locale.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub terms: Option<Terms>,
    /// How to format dates in the locale file.
    #[serde(default)]
    pub date: Vec<Date>,
    /// Style options for the locale.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style_options: Option<LocaleOptions>,
}

impl Locale {
    /// Get a term translation.
    pub fn term(&self, term: Term, form: TermForm) -> Option<&LocalizedTerm> {
        self.terms.as_ref().and_then(|terms| {
            terms
                .terms
                .iter()
                .find(|t| t.name.is_lexically_same(term) && t.form == form)
        })
    }

    /// Retrieve a struct for ordinal term lookups if this locale contains any
    /// ordinal terms.
    pub fn ordinals(&self) -> Option<OrdinalLookup<'_>> {
        self.terms.as_ref().and_then(|terms| {
            terms.terms.iter().any(|t| t.name.is_ordinal()).then(|| {
                OrdinalLookup::new(terms.terms.iter().filter(|t| t.name.is_ordinal()))
            })
        })
    }
}

/// Get the right forms of ordinal terms for numbers.
pub struct OrdinalLookup<'a> {
    terms: Vec<&'a LocalizedTerm>,
    legacy_behavior: bool,
}

impl<'a> OrdinalLookup<'a> {
    fn new(ordinal_terms: impl Iterator<Item = &'a LocalizedTerm>) -> Self {
        let terms = ordinal_terms.collect::<Vec<_>>();
        let mut legacy_behavior = false;
        // Must not define "OtherTerm::Ordinal"
        let defines_ordinal =
            terms.iter().any(|t| t.name == Term::Other(OtherTerm::Ordinal));

        if !defines_ordinal {
            // Contains OtherTerm::OrdinalN(1) - OtherTerm::OrdinalN(4)
            legacy_behavior = (1..=4).all(|n| {
                terms.iter().any(|t| t.name == Term::Other(OtherTerm::OrdinalN(n)))
            })
        }

        Self { terms, legacy_behavior }
    }

    /// Create an empty lookup that will never return matches.
    pub const fn empty() -> Self {
        Self { terms: Vec::new(), legacy_behavior: false }
    }

    /// Look up a short ordinal for a number.
    pub fn lookup(&self, n: i32, gender: Option<GrammarGender>) -> Option<&'a str> {
        let mut best_match: Option<&'a LocalizedTerm> = None;

        // Prefer match with o > 9 and the smallest difference to n
        let mut change_match = |other_match: &'a LocalizedTerm| {
            let Some(current) = best_match else {
                best_match = Some(other_match);
                return;
            };

            // Extract the number from the term name.
            let Term::Other(OtherTerm::OrdinalN(other_n)) = other_match.name else {
                return;
            };

            let Term::Other(OtherTerm::OrdinalN(curr_n)) = current.name else {
                best_match = Some(other_match);
                return;
            };

            best_match = Some(if other_n >= 10 && curr_n < 10 {
                other_match
            } else if other_n < 10 && curr_n >= 10 {
                current
            } else {
                // Both matches are either < 10 or >= 10.
                // Check the gender form.
                if gender == current.gender && gender != other_match.gender {
                    current
                } else if gender != current.gender && gender == other_match.gender {
                    other_match
                } else {
                    // Choose the smallest difference.
                    let diff_other = (n - other_n as i32).abs();
                    let diff_curr = (n - curr_n as i32).abs();

                    if diff_other <= diff_curr {
                        other_match
                    } else {
                        current
                    }
                }
            })
        };

        for term in self.terms.iter().copied() {
            let Term::Other(term_name) = term.name else { continue };

            let hit = match term_name {
                OtherTerm::Ordinal => true,
                OtherTerm::OrdinalN(o) if self.legacy_behavior => {
                    let class = match (n, n % 10) {
                        (11..=13, _) => 4,
                        (_, v @ 1..=3) => v as u8,
                        _ => 4,
                    };
                    o == class
                }
                OtherTerm::OrdinalN(o @ 0..=9) => match term.match_ {
                    Some(OrdinalMatch::LastDigit) | None => n % 10 == o as i32,
                    Some(OrdinalMatch::LastTwoDigits) => n % 100 == o as i32,
                    Some(OrdinalMatch::WholeNumber) => n == o as i32,
                },
                OtherTerm::OrdinalN(o @ 10..=99) => match term.match_ {
                    Some(OrdinalMatch::LastTwoDigits) | None => n % 100 == o as i32,
                    Some(OrdinalMatch::WholeNumber) => n == o as i32,
                    _ => false,
                },
                _ => false,
            };

            if hit {
                change_match(term);
            }
        }

        best_match.and_then(|t| t.single().or_else(|| t.multiple()))
    }

    /// Look up a long ordinal for a number. Does not include fallback to
    /// regular ordinals.
    pub fn lookup_long(&self, n: i32) -> Option<&'a str> {
        self.terms
            .iter()
            .find(|t| {
                let Term::Other(OtherTerm::LongOrdinal(o)) = t.name else { return false };
                if n > 0 && n <= 10 {
                    n == o as i32
                } else {
                    match t.match_ {
                        Some(OrdinalMatch::LastTwoDigits) | None => n % 100 == o as i32,
                        Some(OrdinalMatch::WholeNumber) => n == o as i32,
                        _ => false,
                    }
                }
            })
            .and_then(|t| t.single().or_else(|| t.multiple()))
    }
}

impl From<LocaleFile> for Locale {
    fn from(file: LocaleFile) -> Self {
        Self {
            lang: Some(file.lang),
            info: file.info,
            terms: file.terms,
            date: file.date,
            style_options: file.style_options,
        }
    }
}

impl TryFrom<Locale> for LocaleFile {
    type Error = ();

    fn try_from(value: Locale) -> Result<Self, Self::Error> {
        if value.lang.is_some() {
            Ok(Self {
                version: "1.0".to_string(),
                lang: value.lang.unwrap(),
                info: value.info,
                terms: value.terms,
                date: value.date,
                style_options: value.style_options,
            })
        } else {
            Err(())
        }
    }
}

/// Metadata of a locale.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct LocaleInfo {
    /// The translators of the locale.
    #[serde(rename = "translator")]
    #[serde(default)]
    pub translators: Vec<StyleAttribution>,
    /// The license under which the locale is published.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rights: Option<License>,
    /// When the locale was last updated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated: Option<Timestamp>,
}

/// Term localization container.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Terms {
    /// The terms.
    #[serde(rename = "term")]
    pub terms: Vec<LocalizedTerm>,
}

/// A localized term.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct LocalizedTerm {
    /// The term key.
    #[serde(rename = "@name")]
    pub name: Term,
    /// The localization.
    #[serde(rename = "$text")]
    #[serde(skip_serializing_if = "Option::is_none")]
    localization: Option<String>,
    /// The singular variant.
    #[serde(skip_serializing_if = "Option::is_none")]
    single: Option<String>,
    /// The plural variant.
    #[serde(skip_serializing_if = "Option::is_none")]
    multiple: Option<String>,
    /// The variant of this term translation.
    #[serde(rename = "@form", default)]
    pub form: TermForm,
    /// Specify the when this ordinal term is used.
    #[serde(rename = "@match")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_: Option<OrdinalMatch>,
    /// Specify for which grammatical gender this term has to get corresponding ordinals
    #[serde(rename = "@gender")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gender: Option<GrammarGender>,
    /// Specify which grammatical gender this ordinal term matches
    #[serde(rename = "@gender-form")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gender_form: Option<GrammarGender>,
}

impl LocalizedTerm {
    /// Get the singular variant of this term translation. Shall be defined for
    /// valid CSL files.
    pub fn single(&self) -> Option<&str> {
        self.single.as_deref().or(self.localization.as_deref())
    }

    /// Get the plural variant of this term translation. Shall be defined for
    /// valid CSL files.
    pub fn multiple(&self) -> Option<&str> {
        self.multiple.as_deref().or(self.localization.as_deref())
    }
}

/// The variant of a term translation.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum TermForm {
    /// The default variant.
    #[default]
    Long,
    /// The short noun variant.
    Short,
    /// The related verb.
    Verb,
    /// The related verb (short form).
    VerbShort,
    /// The symbol variant.
    Symbol,
}

impl TermForm {
    /// Which form is the next fallback if this form is not available.
    pub const fn fallback(self) -> Option<Self> {
        match self {
            Self::Long => None,
            Self::Short => Some(Self::Long),
            Self::Verb => Some(Self::Long),
            Self::VerbShort => Some(Self::Verb),
            Self::Symbol => Some(Self::Short),
        }
    }
}

/// Specify when which ordinal term is used.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum OrdinalMatch {
    /// Match the last digit for ordinal terms between zero and nine and the
    /// last two otherwise.
    #[default]
    LastDigit,
    /// Always match on the last two non-zero digits.
    LastTwoDigits,
    /// Match on the exact number.
    WholeNumber,
}

/// A grammatical gender. Use `None` for neutral.
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum GrammarGender {
    Feminine,
    Masculine,
}

/// Options for the locale.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct LocaleOptions {
    /// Only use ordinals for the first day in a month.
    ///
    /// Default: `false`
    #[serde(
        rename = "@limit-day-ordinals-to-day-1",
        deserialize_with = "deserialize_bool_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_day_ordinals_to_day_1: Option<bool>,
    /// Whether to place punctuation inside of quotation marks.
    ///
    /// Default: `false`
    #[serde(
        rename = "@punctuation-in-quote",
        deserialize_with = "deserialize_bool_option",
        default
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub punctuation_in_quote: Option<bool>,
}

/// Formatting properties.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Formatting {
    /// Set the font style.
    #[serde(rename = "@font-style")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_style: Option<FontStyle>,
    /// Choose normal or small caps.
    #[serde(rename = "@font-variant")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_variant: Option<FontVariant>,
    /// Set the font weight.
    #[serde(rename = "@font-weight")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub font_weight: Option<FontWeight>,
    /// Choose underlining.
    #[serde(rename = "@text-decoration")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_decoration: Option<TextDecoration>,
    /// Choose vertical alignment.
    #[serde(rename = "@vertical-align")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vertical_align: Option<VerticalAlign>,
}

impl Formatting {
    /// Check if this formatting is empty.
    pub fn is_empty(&self) -> bool {
        self.font_style.is_none()
            && self.font_variant.is_none()
            && self.font_weight.is_none()
            && self.text_decoration.is_none()
            && self.vertical_align.is_none()
    }

    /// Merge with a base formatting.
    pub fn apply(self, base: Self) -> Self {
        Self {
            font_style: self.font_style.or(base.font_style),
            font_variant: self.font_variant.or(base.font_variant),
            font_weight: self.font_weight.or(base.font_weight),
            text_decoration: self.text_decoration.or(base.text_decoration),
            vertical_align: self.vertical_align.or(base.vertical_align),
        }
    }
}

/// Font style.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FontStyle {
    /// Normal font style.
    #[default]
    Normal,
    /// Italic font style.
    Italic,
}

/// Font variant.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum FontVariant {
    /// Normal font variant.
    #[default]
    Normal,
    /// Small caps font variant.
    SmallCaps,
}

/// Font weight.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FontWeight {
    /// Normal font weight.
    #[default]
    Normal,
    /// Bold font weight.
    Bold,
    /// Light font weight.
    Light,
}

/// Text decoration.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TextDecoration {
    /// No text decoration.
    #[default]
    None,
    /// Underline text decoration.
    Underline,
}

/// Vertical alignment.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum VerticalAlign {
    /// No vertical alignment.
    #[default]
    #[serde(rename = "")]
    None,
    /// Align on the baseline.
    Baseline,
    /// Superscript vertical alignment.
    Sup,
    /// Subscript vertical alignment.
    Sub,
}

/// Prefixes and suffixes.
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Affixes {
    /// The prefix.
    #[serde(rename = "@prefix")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    /// The suffix.
    #[serde(rename = "@suffix")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,
}

/// On which layout level to display the citation.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Display {
    /// Block stretching from margin to margin.
    Block,
    /// Put in the left margin.
    LeftMargin,
    /// Align on page after `LeftMargin`.
    RightInline,
    /// `Block` and indented.
    Indent,
}

/// How to format text.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum TextCase {
    /// lowecase.
    Lowercase,
    /// UPPERCASE.
    Uppercase,
    /// Capitalize the first word.
    CapitalizeFirst,
    /// Capitalize All Words.
    CapitalizeAll,
    /// Sentence case. *Deprecated*.
    #[serde(rename = "sentence")]
    SentenceCase,
    /// Title case. Only applies to English.
    #[serde(rename = "title")]
    TitleCase,
}

impl TextCase {
    /// Check whether this case can be applied to languages other than English.
    pub fn is_language_independent(self) -> bool {
        match self {
            Self::Lowercase
            | Self::Uppercase
            | Self::CapitalizeFirst
            | Self::CapitalizeAll => true,
            Self::SentenceCase | Self::TitleCase => false,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use serde::de::DeserializeOwned;
    use std::{error::Error, fs};

    fn folder<F>(
        files: &'static str,
        extension: &'static str,
        kind: &'static str,
        mut check: F,
    ) where
        F: FnMut(&str) -> Option<Box<dyn Error>>,
    {
        let mut failures = 0;
        let mut tests = 0;

        // Read each `.csl` file in the `tests` directory.
        for entry in fs::read_dir(files).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();
            if path.extension().map(|os| os.to_str().unwrap()) != Some(extension)
                || !entry.file_type().unwrap().is_file()
            {
                continue;
            }

            tests += 1;

            let source = fs::read_to_string(&path).unwrap();
            let result = check(&source);
            if let Some(err) = result {
                failures += 1;
                println!("āŒ {:?} failed: \n\n{:#?}", &path, &err);
            }
        }

        if failures == 0 {
            print!("\nšŸŽ‰")
        } else {
            print!("\nšŸ˜¢")
        }

        println!(
            " {} out of {} {} files parsed successfully",
            tests - failures,
            tests,
            kind
        );

        if failures > 0 {
            panic!("{} tests failed", failures);
        }
    }

    fn check_style(csl_files: &'static str, kind: &'static str) {
        folder(csl_files, "csl", kind, |source| {
            let de = &mut deserializer(source);
            let result: Result<RawStyle, _> = serde_path_to_error::deserialize(de);
            match result {
                Ok(_) => None,
                Err(err) => Some(Box::new(err)),
            }
        })
    }

    fn check_locale(locale_files: &'static str) {
        folder(locale_files, "xml", "Locale", |source| {
            let de = &mut deserializer(source);
            let result: Result<LocaleFile, _> = serde_path_to_error::deserialize(de);
            match result {
                Ok(_) => None,
                Err(err) => Some(Box::new(err)),
            }
        })
    }

    #[track_caller]
    fn to_cbor<T: Serialize>(style: &T) -> Vec<u8> {
        let mut buf = Vec::new();
        ciborium::ser::into_writer(style, &mut buf).unwrap();
        buf
    }

    #[track_caller]
    fn from_cbor<T: DeserializeOwned>(reader: &[u8]) -> T {
        ciborium::de::from_reader(reader).unwrap()
    }

    #[test]
    fn test_independent() {
        check_style("tests/independent", "independent CSL style");
    }

    #[test]
    fn test_dependent() {
        check_style("tests/dependent", "dependent CSL style");
    }

    #[test]
    fn test_locale() {
        check_locale("tests/locales");
    }

    /// Be sure to check out the CSL
    /// [styles](https://github.com/citation-style-language/styles) repository
    /// into a sibling folder to run this test.
    #[test]
    fn roundtrip_cbor_all() {
        fs::create_dir_all("tests/artifacts/styles").unwrap();
        for style_thing in
            fs::read_dir("../styles/").expect("please check out the CSL styles repo")
        {
            let thing = style_thing.unwrap();
            if thing.file_type().unwrap().is_dir() {
                continue;
            }

            let path = thing.path();
            let extension = path.extension();
            if let Some(extension) = extension {
                if extension.to_str() != Some("csl") {
                    continue;
                }
            } else {
                continue;
            }

            eprintln!("Testing {}", path.display());
            let source = fs::read_to_string(&path).unwrap();
            let style = Style::from_xml(&source).unwrap();
            let cbor = to_cbor(&style);
            fs::write(
                format!(
                    "tests/artifacts/styles/{}.cbor",
                    path.file_stem().unwrap().to_str().unwrap()
                ),
                &cbor,
            )
            .unwrap();
            let style2 = from_cbor(&cbor);
            assert_eq!(style, style2);
        }
    }

    /// Be sure to check out the CSL
    /// [locales](https://github.com/citation-style-language/locales) repository
    /// into a sibling folder to run this test.
    #[test]
    fn roundtrip_cbor_all_locales() {
        fs::create_dir_all("tests/artifacts/locales").unwrap();
        for style_thing in
            fs::read_dir("../locales/").expect("please check out the CSL locales repo")
        {
            let thing = style_thing.unwrap();
            if thing.file_type().unwrap().is_dir() {
                continue;
            }

            let path = thing.path();
            let extension = path.extension();
            if let Some(extension) = extension {
                if extension.to_str() != Some("xml")
                    || !path
                        .file_stem()
                        .unwrap()
                        .to_str()
                        .unwrap()
                        .starts_with("locales-")
                {
                    continue;
                }
            } else {
                continue;
            }

            eprintln!("Testing {}", path.display());
            let source = fs::read_to_string(&path).unwrap();
            let locale = LocaleFile::from_xml(&source).unwrap();
            let cbor = to_cbor(&locale);
            fs::write(
                format!(
                    "tests/artifacts/locales/{}.cbor",
                    path.file_stem().unwrap().to_str().unwrap()
                ),
                &cbor,
            )
            .unwrap();
            let locale2 = from_cbor(&cbor);
            assert_eq!(locale, locale2);
        }
    }

    #[test]
    fn page_range() {
        fn run(format: PageRangeFormat, start: &str, end: &str) -> String {
            let mut buf = String::new();
            format.format(&mut buf, start, end, None).unwrap();
            buf
        }

        let c15 = PageRangeFormat::Chicago15;
        let c16 = PageRangeFormat::Chicago16;
        let exp = PageRangeFormat::Expanded;
        let min = PageRangeFormat::Minimal;
        let mi2 = PageRangeFormat::MinimalTwo;

        // https://docs.citationstyles.org/en/stable/specification.html#appendix-v-page-range-formats

        assert_eq!("3ā€“10", run(c15, "3", "10"));
        assert_eq!("71ā€“72", run(c15, "71", "72"));
        assert_eq!("100ā€“104", run(c15, "100", "4"));
        assert_eq!("600ā€“613", run(c15, "600", "613"));
        assert_eq!("1100ā€“1123", run(c15, "1100", "1123"));
        assert_eq!("107ā€“8", run(c15, "107", "108"));
        assert_eq!("505ā€“17", run(c15, "505", "517"));
        assert_eq!("1002ā€“6", run(c15, "1002", "1006"));
        assert_eq!("321ā€“25", run(c15, "321", "325"));
        assert_eq!("415ā€“532", run(c15, "415", "532"));
        assert_eq!("11564ā€“68", run(c15, "11564", "11568"));
        assert_eq!("13792ā€“803", run(c15, "13792", "13803"));
        assert_eq!("1496ā€“1504", run(c15, "1496", "1504"));
        assert_eq!("2787ā€“2816", run(c15, "2787", "2816"));
        assert_eq!("101ā€“8", run(c15, "101", "108"));

        assert_eq!("3ā€“10", run(c16, "3", "10"));
        assert_eq!("71ā€“72", run(c16, "71", "72"));
        assert_eq!("92ā€“113", run(c16, "92", "113"));
        assert_eq!("100ā€“104", run(c16, "100", "4"));
        assert_eq!("600ā€“613", run(c16, "600", "613"));
        assert_eq!("1100ā€“1123", run(c16, "1100", "1123"));
        assert_eq!("107ā€“8", run(c16, "107", "108"));
        assert_eq!("505ā€“17", run(c16, "505", "517"));
        assert_eq!("1002ā€“6", run(c16, "1002", "1006"));
        assert_eq!("321ā€“25", run(c16, "321", "325"));
        assert_eq!("415ā€“532", run(c16, "415", "532"));
        assert_eq!("1087ā€“89", run(c16, "1087", "1089"));
        assert_eq!("1496ā€“500", run(c16, "1496", "1500"));
        assert_eq!("11564ā€“68", run(c16, "11564", "11568"));
        assert_eq!("13792ā€“803", run(c16, "13792", "13803"));
        assert_eq!("12991ā€“3001", run(c16, "12991", "13001"));
        assert_eq!("12991ā€“123001", run(c16, "12991", "123001"));

        assert_eq!("42ā€“45", run(exp, "42", "45"));
        assert_eq!("321ā€“328", run(exp, "321", "328"));
        assert_eq!("2787ā€“2816", run(exp, "2787", "2816"));

        assert_eq!("42ā€“5", run(min, "42", "45"));
        assert_eq!("321ā€“8", run(min, "321", "328"));
        assert_eq!("2787ā€“816", run(min, "2787", "2816"));

        assert_eq!("7ā€“8", run(mi2, "7", "8"));
        assert_eq!("42ā€“45", run(mi2, "42", "45"));
        assert_eq!("321ā€“28", run(mi2, "321", "328"));
        assert_eq!("2787ā€“816", run(mi2, "2787", "2816"));
    }

    /// Tests the bug from PR typst/hayagriva#155
    #[test]
    fn test_bug_hayagriva_115() {
        fn run(format: PageRangeFormat, start: &str, end: &str) -> String {
            let mut buf = String::new();
            format.format(&mut buf, start, end, None).unwrap();
            buf
        }
        let c16 = PageRangeFormat::Chicago16;

        assert_eq!("12991ā€“123001", run(c16, "12991", "123001"));
    }

    #[test]
    fn page_range_prefix() {
        fn run(format: PageRangeFormat, start: &str, end: &str) -> String {
            let mut buf = String::new();
            format.format(&mut buf, start, end, None).unwrap();
            buf
        }

        let c15 = PageRangeFormat::Chicago15;
        let exp = PageRangeFormat::Expanded;
        let min = PageRangeFormat::Minimal;

        assert_eq!("8n11564ā€“68", run(c15, "8n11564", "8n1568"));
        assert_eq!("n11564ā€“68", run(c15, "n11564", "n1568"));
        assert_eq!("n11564ā€“1568", run(c15, "n11564", "1568"));

        assert_eq!("N110ā€“5", run(exp, "N110 ", " 5"));
        assert_eq!("N110ā€“N115", run(exp, "N110 ", " N5"));
        assert_eq!("110ā€“N6", run(exp, "110 ", " N6"));
        assert_eq!("N110ā€“P5", run(exp, "N110 ", " P5"));
        assert_eq!("123N110ā€“N5", run(exp, "123N110 ", " N5"));
        assert_eq!("456K200ā€“99", run(exp, "456K200 ", " 99"));
        assert_eq!("000c23ā€“22", run(exp, "000c23 ", " 22"));

        assert_eq!("n11564ā€“8", run(min, "n11564 ", " n1568"));
        assert_eq!("n11564ā€“1568", run(min, "n11564 ", " 1568"));
    }
}