asciidoc-parser 0.19.0

Parser for AsciiDoc format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
use std::{borrow::Cow, path::Path, sync::LazyLock};

use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
use regex::{Captures, Regex, Replacer};

use crate::{
    Parser, Span,
    attributes::{Attrlist, AttrlistContext},
    content::{Content, content::XrefSegment},
    internal::{LookaheadReplacer, LookaheadResult, replace_with_lookahead},
    parser::{
        FootnoteRenderParams, IconRenderParams, ImageRenderParams, IndexTermRenderParams,
        LinkRenderParams, LinkRenderType, MenuRenderParams,
    },
    warnings::WarningType,
};

pub(super) fn apply_macros(content: &mut Content<'_>, parser: &Parser) {
    let /* mut */ text = content.rendered().to_string();
    let found_square_bracket = text.contains('[');
    let found_colon = text.contains(':');
    let found_macroish = found_square_bracket && found_colon;
    let found_macroish_short = found_macroish && text.contains(":[");

    // A bibliography anchor (`[[[id]]]` / `[[[id,xreftext]]]`) is recognized only
    // when it prefixes the principal text of a bibliography list item; the parser
    // sets a flag while substituting that text. This runs before the inline-anchor
    // pass below so the prefix anchor is consumed as a whole rather than being
    // mistaken for a regular inline anchor (`[[id]]`) wrapped in square brackets.
    // The regex is `^`-anchored, so a `[[[…]]]` appearing later in the entry falls
    // through to the inline-anchor pass (matching Asciidoctor).
    if found_square_bracket && text.contains("[[[") && parser.in_bibliography_list_item.get() {
        let replacer = InlineBiblioAnchorReplacer {
            parser,
            source: content.original(),
        };

        if let Cow::Owned(new_result) =
            INLINE_BIBLIO_ANCHOR.replace_all(content.rendered(), replacer)
        {
            content.rendered = new_result.into();
        }
    }

    // TO DO (#262): Implement extensions that can define macros.
    // Port Ruby Asciidoctor's implementation from
    // https://github.com/asciidoctor/asciidoctor/blob/main/lib/asciidoctor/substitutors.rb#L306-L347.

    // The UI macros (`kbd:`, `btn:`, and `menu:`) are recognized only when the
    // `experimental` document attribute is set. Although the UI macros are a
    // stable part of the AsciiDoc language, requiring the attribute is an
    // optimization that lets the processor skip this work in the common case.
    //
    // Adapted from Asciidoctor's #sub_macros, found in
    // https://github.com/asciidoctor/asciidoctor/blob/main/lib/asciidoctor/substitutors.rb#L349-L411.
    //
    // NOTE: The shorthand menu syntax (`"File > Save"`, handled by Asciidoctor's
    // `InlineMenuRx`) is intentionally not implemented; per the spec it is not
    // on a standards track.
    if parser.is_attribute_set("experimental") {
        if found_macroish_short && (text.contains("kbd:") || text.contains("btn:")) {
            let replacer = InlineKbdBtnMacroReplacer(parser);

            if let Cow::Owned(new_result) =
                INLINE_KBD_BTN_MACRO.replace_all(content.rendered(), replacer)
            {
                content.rendered = new_result.into();
            }
        }

        if found_macroish && text.contains("menu:") {
            let replacer = InlineMenuMacroReplacer(parser);

            if let Cow::Owned(new_result) =
                INLINE_MENU_MACRO.replace_all(content.rendered(), replacer)
            {
                content.rendered = new_result.into();
            }
        }
    }

    if found_macroish && (text.contains("image:") || text.contains("icon:")) {
        let replacer = InlineImageMacroReplacer(parser);

        if let Cow::Owned(new_result) = INLINE_IMAGE_MACRO.replace_all(content.rendered(), replacer)
        {
            content.rendered = new_result.into();
        }
    }

    if (text.contains("((") && text.contains("))"))
        || (found_macroish_short && text.contains("dexterm"))
    {
        let replacer = InlineIndextermReplacer(parser);

        if let Cow::Owned(new_result) =
            replace_with_lookahead(&INLINE_INDEXTERM, content.rendered(), replacer)
        {
            content.rendered = new_result.into();
        }
    }

    if found_colon && text.contains("://") {
        let replacer = InlineLinkReplacer(parser);

        if let Cow::Owned(new_result) = INLINE_LINK.replace_all(content.rendered(), replacer) {
            content.rendered = new_result.into();
        }
    }

    if found_macroish && (text.contains("link:") || text.contains("ilto:")) {
        let replacer = InlineLinkMacroReplacer(parser);

        if let Cow::Owned(new_result) = INLINE_LINK_MACRO.replace_all(content.rendered(), replacer)
        {
            content.rendered = new_result.into();
        }
    }

    if text.contains('@') {
        let replacer = InlineEmailReplacer(parser);

        if let Cow::Owned(new_result) = INLINE_EMAIL.replace_all(content.rendered(), replacer) {
            content.rendered = new_result.into();
        }
    }

    if (found_square_bracket && text.contains("[[")) || (found_macroish && text.contains("or:")) {
        let replacer = InlineAnchorReplacer(parser);

        if let Cow::Owned(new_result) = INLINE_ANCHOR.replace_all(content.rendered(), replacer) {
            content.rendered = new_result.into();
        }
    }

    // Cross-references (`<<id>>`, `<<id,text>>`, `xref:id[]`, `xref:id[text]`).
    //
    // By the time the macros step runs, the special-characters step has already
    // turned `<<` / `>>` into `&lt;&lt;` / `&gt;&gt;`. We do NOT resolve the
    // reference here, because its target may be defined later in the document
    // (or, for multi-document workflows, in another document). Instead each
    // cross-reference is recorded as a deferred `XrefSegment` and a placeholder
    // is left in the rendered text; resolution happens later via
    // `Document::resolve_references`.
    //
    // This runs *before* footnotes so that a cross-reference inside a footnote
    // becomes a (bracket-free) placeholder before the footnote text is
    // extracted. That lets the footnote text — including the `xref:id[…]` macro
    // form, whose literal `]` would otherwise truncate the footnote — be
    // captured intact, and lets the footnote re-home the placeholder so it is
    // resolved in the document-level pass too.
    let mut xrefs: Vec<XrefSegment> = vec![];

    if (text.contains("&lt;&lt;") || (found_macroish && text.contains("xref:")))
        && let Cow::Owned(new_result) = INLINE_XREF.replace_all(
            content.rendered(),
            InlineXrefReplacer {
                parser,
                xrefs: &mut xrefs,
            },
        )
    {
        content.rendered = new_result.into();
    }

    // Footnotes (`footnote:[text]`, `footnote:id[text]`, `footnote:id[]`, and
    // the deprecated `footnoteref:[id,text]` / `footnoteref:[id]`).
    //
    // The footnote *text* is extracted out of the flow of text (only a
    // superscript marker is left behind), so any macro inside the footnote that
    // has already been substituted at this point (images, links, anchors, index
    // terms, and now cross-references) is captured as part of the footnote text.
    // Any cross-reference placeholders captured this way are re-homed onto the
    // footnote so they resolve in the document-level pass.
    if found_macroish && text.contains("tnote") {
        let replacer = InlineFootnoteMacroReplacer {
            parser,
            source: content.original(),
            all_xrefs: &xrefs,
        };

        if let Cow::Owned(new_result) =
            replace_with_lookahead(&INLINE_FOOTNOTE_MACRO, content.rendered(), replacer)
        {
            content.rendered = new_result.into();
        }
    }

    content.set_deferred_xrefs(xrefs);
}

static INLINE_IMAGE_MACRO: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)                    
            \\?                         # Optional escape: literal backslash
            i(?:mage|con):              # 'image:' or 'icon:' prefix

            (                           # Group 1: the target
                [^:\s\[\n]                  # First char: not colon, whitespace, [, or newline
                [^\[\n]*?                   # Middle chars: any except [ or newline, lazily
                [^\s\[\n]                   # Last char: not whitespace, [, or newline
            )?                          # Entire target group is optional

            \[                          # Opening square bracket

            (                           # Group 2: bracketed text
                |                       #   EITHER: empty alt text
                .*?[^\\]                #   OR: content ending in a non-backslash
            )

            \]                          # Closing square bracket
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineImageMacroReplacer<'p>(&'p Parser);

impl Replacer for InlineImageMacroReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        if caps[0].starts_with('\\') {
            // Honor the escape.
            dest.push_str(&caps[0][1..]);
            return;
        }

        let target = &caps[1];
        let span = Span::new(&caps[2]);
        let attrlist = Attrlist::parse(span, self.0, AttrlistContext::Inline)
            .item
            .item;

        let default_alt = basename(&target.replace(['_', '-'], " "));
        // IMPORTANT: Implementations of `render_icon` and `render_image` need to
        // remember to use `default_alt` when attrlist doesn't contain a value for
        // `alt`.

        if caps[0].starts_with("image:") {
            // TO DO: Register image with parser?
            // IMPORTANT: May require interior mutability on Parser because it looks like we
            // can't pass mutable references to Parser in a recursive Regex replacement.

            // TO DO (https://github.com/asciidoc-rs/asciidoc-parser/issues/335):
            // todo!("Port this: {}", "doc.register :images, target");

            let params = ImageRenderParams {
                target,
                alt: attrlist
                    .named_or_positional_attribute("alt", 1)
                    .map_or(default_alt, |a| {
                        normalize_text_lf_escaped_bracket(a.value())
                    }),
                width: attrlist
                    .named_or_positional_attribute("width", 2)
                    .map(|a| a.value()),
                height: attrlist
                    .named_or_positional_attribute("height", 3)
                    .map(|a| a.value()),
                attrlist: &attrlist,
                parser: self.0,
            };

            self.0.renderer.render_image(&params, dest);
        } else {
            let params = IconRenderParams {
                target,
                alt: attrlist.named_attribute("alt").map_or(default_alt, |a| {
                    normalize_text_lf_escaped_bracket(a.value())
                }),
                size: attrlist
                    .named_or_positional_attribute("size", 1)
                    .map(|a| a.value()),
                attrlist: &attrlist,
                parser: self.0,
            };

            self.0.renderer.render_icon(&params, dest);
        }
    }
}

fn basename(path: &str) -> String {
    Path::new(path)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or_default()
        .to_string()
}

/// Matches a keyboard (`kbd:[…]`) or button (`btn:[…]`) UI macro.
///
/// ## Examples
///
/// * `kbd:[F3]`
/// * `kbd:[Ctrl+Shift+T]`
/// * `kbd:[Ctrl+\]]`
/// * `btn:[Save]`
static INLINE_KBD_BTN_MACRO: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)                    # extended mode; dot matches newline
        (\\)?                       # (1) optional escape backslash
        (kbd|btn):                  # (2) macro name
        \[
            ( .*?[^\\] )            # (3) bracketed content, ending in a non-backslash
        \]
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineKbdBtnMacroReplacer<'p>(&'p Parser);

impl Replacer for InlineKbdBtnMacroReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        // Honor the escape: emit the macro text without the leading backslash.
        if caps.get(1).is_some() {
            dest.push_str(&caps[0][1..]);
            return;
        }

        if &caps[2] == "kbd" {
            let keys = split_kbd_keys(&caps[3]);
            self.0.renderer.render_keyboard(&keys, dest);
        } else {
            // A button label is normalized like other bracketed macro text:
            // surrounding whitespace and newlines are folded, and any escaped
            // closing bracket is unescaped.
            let text = normalize_index_text(&caps[3], true);
            self.0.renderer.render_button(&text, dest);
        }
    }
}

/// Splits the raw argument of a `kbd:[…]` macro into individual keys, mirroring
/// Asciidoctor's delimiter handling.
///
/// A single key produces a one-element vector; a key sequence is split on the
/// first delimiter found — a comma (`,`) or a plus (`+`) — searching from the
/// *second* character so that a leading delimiter is treated as a literal key
/// (e.g. `kbd:[,te]` is the single key `,te`). If the argument ends with the
/// delimiter, that trailing delimiter is preserved as the value of the final
/// key (e.g. `kbd:[Ctrl + +]` yields `Ctrl` and `+`).
fn split_kbd_keys(raw: &str) -> Vec<String> {
    let mut keys = raw.trim().to_string();
    if keys.contains(']') {
        keys = keys.replace("\\]", "]");
    }

    // The delimiter is the earliest comma or plus that is not the first
    // character. Scanning from the second character and taking the first match
    // yields the same choice as Asciidoctor's `min` of the two candidate
    // indexes. Because the scan starts at the second character, a single-key
    // argument (or one whose only delimiter is a leading literal) yields `None`
    // here, so no separate length check is needed.
    let delim = keys.chars().skip(1).find(|c| *c == ',' || *c == '+');

    if let Some(delim) = delim {
        let ends_with_delim = keys.ends_with(delim);

        // Drop the trailing delimiter before splitting; it is restored on the
        // last key below. (Rust's `split` keeps trailing empty segments, which
        // matches Asciidoctor's `split delim, -1`.)
        let split_source = if ends_with_delim {
            &keys[..keys.len() - delim.len_utf8()]
        } else {
            keys.as_str()
        };

        let mut parts: Vec<String> = split_source
            .split(delim)
            .map(|k| k.trim().to_string())
            .collect();

        if ends_with_delim && let Some(last) = parts.last_mut() {
            last.push(delim);
        }

        parts
    } else {
        vec![keys]
    }
}

/// Matches a menu (`menu:…[…]`) UI macro.
///
/// The shorthand form (`"File > Save"`) is intentionally not matched here; per
/// the spec it is not on a standards track.
///
/// ## Examples
///
/// * `menu:File[]`
/// * `menu:File[Save]`
/// * `menu:View[Zoom > Reset]`
/// * `menu:Tools[Project, Build]`
static INLINE_MENU_MACRO: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)                        # extended mode; dot matches newline
        \\?                             # optional escape backslash (not captured)
        menu:
        (                               # (1) menu name
            \w                              # a single word character
          |                                 # or
            [\w&] [^\n\[]* [^\s\[]           # first word/ampersand char, then any run
                                            # not containing a newline or '[', ending
                                            # in a non-space, non-'[' character
        )
        \[ \x20*                        # opening '[' then optional spaces
        (?:                             # menu items (optional)
            |                               # empty
            ( .*?[^\\] )                    # (2) items, ending in a non-backslash
        )
        \]
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineMenuMacroReplacer<'p>(&'p Parser);

impl Replacer for InlineMenuMacroReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        // Honor the escape: emit the macro text without the leading backslash.
        if caps[0].starts_with('\\') {
            dest.push_str(&caps[0][1..]);
            return;
        }

        let menu = &caps[1];

        // The items list, if present, is split into zero or more submenus and a
        // trailing menu item. The `&gt;` delimiter (already substituted from
        // `>`) takes precedence over a comma; without either, the whole list is
        // a single menu item.
        let (submenus, menuitem): (Vec<String>, Option<String>) = if let Some(items) = caps.get(2) {
            let mut items = items.as_str().to_string();
            if items.contains(']') {
                items = items.replace("\\]", "]");
            }

            let delim = if items.contains("&gt;") {
                Some("&gt;")
            } else if items.contains(',') {
                Some(",")
            } else {
                None
            };

            if let Some(delim) = delim {
                let mut parts: Vec<String> =
                    items.split(delim).map(|i| i.trim().to_string()).collect();
                let menuitem = parts.pop();
                (parts, menuitem)
            } else {
                (vec![], Some(items.trim_end().to_string()))
            }
        } else {
            (vec![], None)
        };

        let params = MenuRenderParams {
            menu,
            submenus: &submenus,
            menuitem: menuitem.as_deref(),
            parser: self.0,
        };

        self.0.renderer.render_menu(&params, dest);
    }
}

fn normalize_text_lf_escaped_bracket(text: &str) -> String {
    text.replace("\n", " ").replace("\\]", "]")
}

/// Matches an [index term] inline macro, in either the macro form
/// (`indexterm:[…]` / `indexterm2:[…]`) or the shorthand form
/// (`(((primary, secondary, tertiary)))` / `((primary))`).
///
/// The shorthand alternative captures the text between the outermost `((` and
/// `))`. Asciidoctor anchors the closing `))` with a `(?!\))` look-ahead so
/// that the *last* pair in a run of parentheses closes the term; Rust's regex
/// engine has no look-ahead, so [`InlineIndextermReplacer`] re-creates that
/// behavior by absorbing any trailing `)` that follow the matched `))`.
///
/// [index term]: https://docs.asciidoctor.org/asciidoc/latest/sections/user-index/
static INLINE_INDEXTERM: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)                         # extended mode; dot matches newline
        \\?                              # optional escaping backslash
        (?:
            (indexterm2?):\[ (.*?[^\\]) \]   # (1) macro name, (2) macro argument
          |
            \(\( (.+?) \)\)                  # (3) shorthand enclosed text
        )
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineIndextermReplacer<'p>(&'p Parser);

impl LookaheadReplacer for InlineIndextermReplacer<'_> {
    fn replace_append(
        &mut self,
        caps: &Captures<'_>,
        dest: &mut String,
        after: &str,
    ) -> LookaheadResult {
        // Adapted from Asciidoctor#sub_macros (the `InlineIndextermMacroRx`
        // branch), found in
        // https://github.com/asciidoctor/asciidoctor/blob/main/lib/asciidoctor/substitutors.rb.

        let parser = self.0;

        // Macro form: `indexterm:[…]` (concealed) or `indexterm2:[…]` (flow).
        if let Some(name) = caps.get(1) {
            // Honor the escape: emit the macro text without the backslash.
            if caps[0].starts_with('\\') {
                dest.push_str(&caps[0][1..]);
                return LookaheadResult::Continue;
            }

            if name.as_str() == "indexterm2" {
                // A flow index term renders its primary term inline. When the
                // argument carries an attribute list (it contains `=`), the
                // first positional attribute is the primary term.
                let arg = normalize_index_text(&caps[2], true);
                let term = if arg.contains('=') {
                    Attrlist::parse(Span::new(&arg), parser, AttrlistContext::Inline)
                        .item
                        .item
                        .nth_attribute(1)
                        .map(|a| a.value().to_string())
                        .unwrap_or(arg)
                } else {
                    arg
                };

                parser.renderer.render_index_term(
                    &IndexTermRenderParams {
                        visible_term: Some(&term),
                    },
                    dest,
                );
            } else {
                // A concealed index term produces no inline output.
                parser
                    .renderer
                    .render_index_term(&IndexTermRenderParams { visible_term: None }, dest);
            }

            return LookaheadResult::Continue;
        }

        // Shorthand form: `((…))` / `(((…)))`.
        //
        // Absorb any `)` that immediately follow the matched `))` so that the
        // closing pair is the last in the run, mirroring Asciidoctor's
        // `(?!\))` look-ahead. Those extra characters are part of this logical
        // match, so they are skipped (rather than re-scanned) once consumed.
        let extra = after.bytes().take_while(|b| *b == b')').count();
        let advance = if extra > 0 {
            LookaheadResult::SkipAheadAndRetry(caps[0].len() + extra)
        } else {
            LookaheadResult::Continue
        };

        let mut encl_text = String::with_capacity(caps[3].len() + extra);
        encl_text.push_str(&caps[3]);
        for _ in 0..extra {
            encl_text.push(')');
        }

        let escaped = caps[0].starts_with('\\');

        // Strip the enclosing parentheses (if any) to decide whether the term
        // is concealed or visible, and which literal parentheses to preserve in
        // the flow of text. `before`/`trailing` carry literal parentheses that
        // are adjacent to (but not part of) the index term.
        let (inner, visible, before, trailing): (&str, bool, &str, &str) = if escaped {
            if encl_text.starts_with('(') && encl_text.ends_with(')') {
                // An escaped concealed term still processes a nested flow term.
                (&encl_text[1..encl_text.len() - 1], true, "(", ")")
            } else {
                // Honor the escape: emit the enclosed text verbatim (the full
                // match, including any absorbed parens, minus the backslash).
                dest.push_str(&caps[0][1..]);
                for _ in 0..extra {
                    dest.push(')');
                }
                return advance;
            }
        } else if let Some(without_open) = encl_text.strip_prefix('(') {
            if let Some(inner) = without_open.strip_suffix(')') {
                // `(((concealed)))`
                (inner, false, "", "")
            } else {
                (without_open, true, "(", "")
            }
        } else if let Some(inner) = encl_text.strip_suffix(')') {
            (inner, true, "", ")")
        } else {
            // `((visible))`
            (&encl_text[..], true, "", "")
        };

        dest.push_str(before);

        if visible {
            let term = strip_see_and_seealso(&normalize_index_text(inner, false));
            parser.renderer.render_index_term(
                &IndexTermRenderParams {
                    visible_term: Some(&term),
                },
                dest,
            );
        } else {
            parser
                .renderer
                .render_index_term(&IndexTermRenderParams { visible_term: None }, dest);
        }

        dest.push_str(trailing);

        advance
    }
}

/// Normalizes the text of an index term: trims surrounding whitespace and
/// collapses embedded newlines to spaces (Asciidoctor compacts a multi-line
/// term onto a single line). When `unescape_brackets` is set (the macro forms),
/// an escaped closing square bracket (`\]`) is also unescaped.
fn normalize_index_text(text: &str, unescape_brackets: bool) -> String {
    let normalized = text.trim().replace('\n', " ");
    if unescape_brackets {
        normalized.replace("\\]", "]")
    } else {
        normalized
    }
}

/// Strips a trailing `see` (` >> …`) or `see-also` (` &> …`) clause from a
/// visible index term, leaving only the primary term to display in the flow of
/// text. By the time macros are processed, the special-characters substitution
/// has already turned `>` into `&gt;` and `&` into `&amp;`, so the separators
/// appear here as ` &gt;&gt; ` and ` &amp;&gt; `.
fn strip_see_and_seealso(term: &str) -> String {
    // Cheap guard mirroring Asciidoctor's `term.include? ';&'`.
    if term.contains(";&") {
        if let Some((primary, _see)) = term.split_once(" &gt;&gt; ") {
            return primary.to_string();
        }
        if let Some((primary, _see_also)) = term.split_once(" &amp;&gt; ") {
            return primary.to_string();
        }
    }
    term.to_string()
}

static INLINE_LINK: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?msx)
        ( ^ | link: | [\ \t] | \\?&lt;() | [>\(\)\[\];"'] )   # capture group 1: prefix
                                                              # capture group 2: flag for prefix == "&lt;"
        ( \\? (?: https? | file | ftp | irc ):// )            # capture group 3: scheme
        (?:
            ( [^\s\[\]]+ )                                    # capture group 4: target
            \[ ( | .*?[^\\] ) \]                              # capture group 5: attrlist
          | ( [^\s]+? ) &gt;                                  # capture group 6: URL inside <>
                                                              # (Ruby gates this with a `\2` back-ref to
                                                              # group 2; unsupported here - see issue #503)
          | ( [^\s\[\]<]* ( [^\s,.?!\[\]<\)] ) )              # capture group 7: bare link,
                                                              # capture group 8: trailing char
        )
    "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineLinkReplacer<'p>(&'p Parser);

impl Replacer for InlineLinkReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        let mut attrlist = Attrlist::parse(Span::default(), self.0, AttrlistContext::Inline)
            .item
            .item;

        if caps.get(2).is_some() && caps.get(5).is_none() {
            // Honor the escapes.
            if caps[1].starts_with('\\') {
                dest.push_str(&caps[0][1..]);
                return;
            }

            if caps[3].starts_with('\\') {
                dest.push_str(&caps[1]);
                dest.push_str(&caps[0][caps[1].len() + 1..]);
                return;
            }

            let Some(link_suffix) = caps.get(6) else {
                dest.push_str(&caps[0]);
                return;
            };

            let target = format!(
                "{scheme}{link_suffix}",
                scheme = &caps[3],
                link_suffix = link_suffix.as_str()
            );

            // TO DO (https://github.com/asciidoc-rs/asciidoc-parser/issues/335):
            // doc.register :links, target

            let link_text = if self.0.is_attribute_set("hide-uri-scheme") {
                URI_SNIFF.replace_all(&target, "").into_owned()
            } else {
                target.clone()
            };

            let params = LinkRenderParams {
                target,
                link_text,
                extra_roles: vec!["bare"],
                window: None,
                type_: LinkRenderType::Link,
                attrlist: &attrlist,
                parser: self.0,
            };

            self.0.renderer.render_link(&params, dest);

            return;
        }

        let mut prefix = caps[1].to_string();
        let scheme = &caps[3];

        // Honor the escape.
        if scheme.starts_with('\\') {
            dest.push_str(&prefix);
            dest.push_str(&caps[0][prefix.len() + 1..]);
            return;
        }

        // Groups 4, 6, and 7 are mutually exclusive regex alternatives;
        // exactly one will be Some(_) when we reach this point.
        // Group 4 = formal macro target (URL before '['), group 7 = bare link.
        //
        // Group 6 is the URL captured before a `&gt;`. When the `&lt;` prefix is
        // also present (group 2), the angle-bracketed-URL case is handled earlier
        // and returns. Reaching here with group 6 means a stray `&gt;` with no
        // matching `&lt;`; Asciidoctor treats that as a bare link that keeps the
        // literal `&gt;`, then strips trailing punctuation via the rule below
        // (e.g. `https://example.org>` renders with href `https://example.org&gt`
        // and the `;` left outside the link).
        //
        // TO DO (https://github.com/asciidoc-rs/asciidoc-parser/issues/503):
        // Group 6 should never participate without group 2. Ruby gates it with a
        // `\2` back-reference, which the `regex` crate can't express, so it can
        // fire spuriously here and a stray `&gt;` followed by more punctuation
        // (e.g. `>;`) still diverges from Asciidoctor.
        let url_part = caps
            .get(4)
            .map(|m| m.as_str().to_owned())
            .or_else(|| caps.get(7).map(|m| m.as_str().to_owned()))
            .or_else(|| caps.get(6).map(|m| format!("{}&gt;", m.as_str())))
            .unwrap_or_default();
        let mut target = format!("{scheme}{url_part}");

        let mut suffix = "".to_owned();
        let mut link_text: Option<String> = None;

        // NOTE: If capture group 5 exists (the attrlist), we're looking at a formal macro (e.g., https://example.org[]).
        if let Some(attrlist) = caps.get(5) {
            if prefix == "link:" {
                prefix = "".to_owned();
            }

            if !attrlist.is_empty() {
                link_text = Some(attrlist.as_str().to_owned());
            }
        } else {
            if prefix == "link" || prefix == "\"" || prefix == "'" {
                // Note from the Ruby implementation which also applies to this if clause:

                // Invalid macro syntax (link: prefix w/o trailing square brackets or URL
                // enclosed in quotes).

                // FIXME: We probably shouldn't even get here when the link: prefix is present.
                // The regex is doing too much.
                dest.push_str(&caps[0]);
                return;
            }

            // Strip a trailing ';' or ':' (and an adjacent ')') out of a bare
            // URL. Keying off the target's final character rather than capture
            // group 8 covers both the bare-link case (group 7) and the stray
            // `&gt;` case (group 6, whose reconstructed URL ends in ';').
            if let Some(tail) = target.chars().last().filter(|c| *c == ';' || *c == ':') {
                target.truncate(target.len() - 1);
                suffix = tail.to_string();

                if target.ends_with(')') {
                    target.truncate(target.len() - 1);
                    suffix = format!("){suffix}");
                }
            }
        }

        let mut bare = false;

        let link_text_for_attrlist = link_text.clone().unwrap_or_default();
        let span_for_attrlist = Span::new(&link_text_for_attrlist);
        let mut window: Option<&'static str> = None;

        let link_text = if let Some(mut link_text) = link_text {
            link_text = link_text.replace("\\]", "]");

            if link_text.contains('=') {
                let (lt, attrs) = extract_attributes_from_text(&span_for_attrlist, self.0, None);

                link_text = lt.replace("\\\"", "\"");
                attrlist = attrs; // ???
            }

            if link_text.ends_with('^') {
                link_text.truncate(link_text.len() - 1);
                window = Some("_blank");
            }

            if link_text.is_empty() {
                bare = true;

                if self.0.is_attribute_set("hide-uri-scheme") {
                    // NOTE: The modified target will not be a bare URI scheme (e.g., http://) in this case.
                    URI_SNIFF.replace_all(&target, "").into_owned()
                } else {
                    target.clone()
                }
            } else {
                link_text
            }
        } else {
            // NOTE: The modified target will not be a bare URI scheme (e.g., http://) in this case.
            bare = true;

            if self.0.is_attribute_set("hide-uri-scheme") {
                URI_SNIFF.replace_all(&target, "").into_owned()
            } else {
                target.clone()
            }
        };

        let extra_roles = if bare { vec!["bare"] } else { vec![] };

        // TO DO (https://github.com/asciidoc-rs/asciidoc-parser/issues/335):
        // doc.register :links, (link_opts[:target] = target)

        dest.push_str(&prefix);

        let params = LinkRenderParams {
            target,
            link_text,
            extra_roles,
            window,
            type_: LinkRenderType::Link,
            attrlist: &attrlist,
            parser: self.0,
        };

        self.0.renderer.render_link(&params, dest);

        dest.push_str(&suffix);
    }
}

static INLINE_LINK_MACRO: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)                # (?x) extended mode, (?s) dot matches newline

        \\?                     # Optional backslash escape before macro

        (?:                     # Non-capturing group for macro name
            link                #   'link'
          | (mailto)            #   capture group 1: 'mailto'
        )

        :                       # Colon after macro name

        (?:                     # Non-capturing outer group
            ().                 #   capture group 2: empty target
          | ([^:\s\[] [^\s\[]*) #   capture group 3: valid target (no colon/space/'[')
        )

        \[                      # Opening square bracket

        (?:                     # Non-capturing outer group
            ()                  #   capture group 4: empty label
          | (.*?[^\\])          #   capture group 5: minimally match anything, not ending in '\'
        )

        \]                      # Closing square bracket
    "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineLinkMacroReplacer<'p>(&'p Parser);

impl Replacer for InlineLinkMacroReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        if caps[0].starts_with('\\') {
            // Honor the escape.
            dest.push_str(&caps[0][1..]);
            return;
        }

        let (mailto, mailto_text, mut target) = if caps.get(1).is_some() {
            let mailto_text = &caps[3];
            (
                caps.get(1).map(|c| c.as_str()),
                Some(mailto_text),
                format!("mailto:{mailto_text}"),
            )
        } else {
            (None, None, caps[3].to_string())
        };

        let mut attrlist: Option<Attrlist<'_>> = None;
        let link_type = LinkRenderType::Link;

        let mut link_text = caps
            .get(5)
            .map(|c| c.as_str().to_string())
            .unwrap_or_default();

        let link_text_for_attrlist = link_text.replace("\n", " ");
        let span_for_attrlist = Span::new(&link_text_for_attrlist);
        let mut window: Option<&'static str> = None;

        if !link_text.is_empty() {
            link_text = link_text.replace("\\]", "]");

            if let Some(_mailto) = mailto {
                if link_text.contains(',') {
                    let (lt, attrs) =
                        extract_attributes_from_text(&span_for_attrlist, self.0, None);

                    link_text = lt;

                    if let Some(target_attr) = attrs.nth_attribute(2) {
                        target = format!(
                            "{target}?subject={subject}",
                            subject = encode_uri_component(target_attr.value())
                        );

                        if let Some(body) = attrs.nth_attribute(3) {
                            target = format!(
                                "{target}&amp;body={body}",
                                body = encode_uri_component(body.value())
                            );
                        }
                    }

                    attrlist = Some(attrs);
                }
            } else if link_text.contains('=') {
                let (lt, attrs) = extract_attributes_from_text(&span_for_attrlist, self.0, None);
                link_text = lt;

                attrlist = Some(attrs);
            }

            if link_text.ends_with('^') {
                link_text.truncate(link_text.len() - 1);
                window = Some("_blank");
            }
        }

        let attrlist = if let Some(attrlist) = attrlist {
            attrlist
        } else {
            Attrlist::parse(Span::default(), self.0, AttrlistContext::Inline)
                .item
                .item
        };

        let mut extra_roles: Vec<&str> = vec![];

        if link_text.is_empty() {
            // mailto is a special case; already processed.
            if let Some(_mailto) = mailto {
                link_text = mailto_text.map(|s| s.to_owned()).unwrap_or_default();
            } else {
                link_text = if self.0.is_attribute_set("hide-uri-scheme") {
                    let lt = URI_SNIFF.replace_all(&target, "").into_owned();
                    if lt.is_empty() { target.clone() } else { lt }
                } else {
                    target.clone()
                };

                extra_roles.push("bare");
            }
        }

        // TO DO (https://github.com/asciidoc-rs/asciidoc-parser/issues/335):
        // doc.register :links, (link_opts[:target] = target)

        let params = LinkRenderParams {
            target,
            link_text: link_text.clone(),
            extra_roles,
            window,
            type_: link_type,
            attrlist: &attrlist,
            parser: self.0,
        };

        self.0.renderer.render_link(&params, dest);
    }
}

/// This function is used in cases when the attrlist can be mixed with the text
/// of a macro. If no attributes are detected aside from the first positional
/// attribute, and the first positional attribute matches the attrlist, then the
/// original text is returned.
///
/// Precondition: Any new-line characters (`\n`) must be replaced with spaces
/// prior to calling this function.
fn extract_attributes_from_text<'src>(
    text: &'src Span<'src>,
    parser: &Parser,
    default_text: Option<&str>,
) -> (String, Attrlist<'src>) {
    let attrlist_maw = Attrlist::parse(*text, parser, AttrlistContext::Inline);
    let attrs = attrlist_maw.item.item;

    if let Some(resolved_text) = attrs.nth_attribute(1) {
        // NOTE: If resolved text remains unchanged, return an empty attribute list and
        // return unparsed text. Commented out because I haven't seen an example of this
        // happening in practice. Each of the call sites for this function introduces a
        // constraint that should make this impossible.

        /* if resolved_text.value() == text.data() {
            let empty_attrs = Attrlist::parse(Span::default(), parser, AttrlistContext::Inline).item.item;
            (text.data().to_owned(), empty_attrs)
        } else { */
        (resolved_text.value().to_owned(), attrs)
        /* } */
    } else {
        let default_text = default_text.map(|s| s.to_string());
        (default_text.unwrap_or_default(), attrs)
    }
}

// Ruby CGI.escape allows A-Z a-z 0-9 *_.-
// It encodes space as '+'. (We'll fix afterward.)
// Start with the standard URL encoding set.
const CGI_ESCAPE_SET: &AsciiSet = &CONTROLS
    .add(b' ') // space
    .add(b'!')
    .add(b'"')
    .add(b'#')
    .add(b'$')
    .add(b'%')
    .add(b'&')
    .add(b'\'')
    .add(b'(')
    .add(b')')
    .add(b'+') // plus must be escaped
    .add(b',')
    .add(b'/')
    .add(b':')
    .add(b';')
    .add(b'<')
    .add(b'=')
    .add(b'>')
    .add(b'?')
    .add(b'@')
    .add(b'[')
    .add(b'\\')
    .add(b']')
    .add(b'^')
    .add(b'`')
    .add(b'{')
    .add(b'|')
    .add(b'}');

fn encode_uri_component(s: &str) -> String {
    // First escape with percent-encoding.
    let encoded = utf8_percent_encode(s, CGI_ESCAPE_SET).to_string();

    // Then apply the Ruby `.gsub('+', '%20')` logic.
    // But note: percent-encoding gives us "%20" for space already,
    // so we need to manually *introduce* '+' for space first,
    // then swap them out.
    let with_plus = encoded.replace("%20", "+");
    with_plus.replace('+', "%20")
}

/// Matches an inline e-mail address.
///
/// # Example
/// `doc.writer@example.com`
static INLINE_EMAIL: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?x)                         # verbose mode (ignore whitespace & comments)

        ([\\>:/]?)                      # capture group 1: prefix that causes mismatch: \, >, :, or /

        (                               # capture group 2: actual e-mail address
            [\w_]                           # leading word character
            (?: &amp; | [\w\-.%+] )*        # subsequent word chars or symbols (&amp;, ., -, %, +)
            @                               # at sign
            [\p{L}\p{Nd}]                   # leading letter or digit in domain
            [\p{L}\p{Nd}_\-.]*              # rest of domain
            \.[a-zA-Z]{2,5}                 # dot + TLD (2–5 ASCII letters)
        )

        \b                              # word boundary
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineEmailReplacer<'p>(&'p Parser);

impl Replacer for InlineEmailReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        if let Some(escape) = &caps.get(1)
            && !escape.is_empty()
        {
            if escape.as_str() == "\\" {
                dest.push_str(&caps[0][1..]);
            } else {
                dest.push_str(&caps[0]);
            }
            return;
        }

        let target = format!("mailto:{mailto}", mailto = &caps[2]);

        let attrlist = Attrlist::parse(Span::default(), self.0, AttrlistContext::Inline)
            .item
            .item;

        let params = LinkRenderParams {
            target: target.clone(),
            link_text: caps[2].to_owned(),
            extra_roles: vec![],
            window: None,
            type_: LinkRenderType::Link,
            attrlist: &attrlist,
            parser: self.0,
        };

        self.0.renderer.render_link(&params, dest);
    }
}

/// Matches a bibliography anchor that prefixes a bibliography list item.
///
/// The anchor is matched only at the very start of the entry (`^`), mirroring
/// Asciidoctor: a `[[[…]]]` appearing later in the text is left to the regular
/// inline-anchor pass. The label must be _non-numeric_ (it may contain digits,
/// but must not begin with one), so an entry that opens with something like
/// `[[[1984]]]` is left untouched. An optional xreftext follows a comma.
///
/// A leading backslash is deliberately *not* accepted as an escape: `\[[[id]]]`
/// does not begin with `[[[`, so it simply isn't a bibliography anchor (the
/// backslash and inner `[[id]]` are handled by the inline-anchor pass, matching
/// Asciidoctor). The documented escape `[\[[id]]]` likewise does not start with
/// `[[[` and is handled there.
///
/// ## Examples
///
/// * `[[[label]]]`
/// * `[[[label,xreftext]]]`
static INLINE_BIBLIO_ANCHOR: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?x)
        ^                               # the anchor must prefix the entry
        \[\[\[                          # opening triple bracket
          (                             # (1) bibliography label
            [\p{Alphabetic}_:]              # first char: letter, '_' or ':' (never a digit)
            [\p{Alphabetic}\p{Nd}_\-:.]*    # rest: letters/digits/_/-/:/.
          )
          (?: , \s* (.+?) )?            # (2) optional xreftext after a comma
        \]\]\]                          # closing triple bracket
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineBiblioAnchorReplacer<'p, 's> {
    parser: &'p Parser,

    /// The original (pre-substitution) span of the content being rendered, used
    /// to locate a duplicate-id warning.
    source: Span<'s>,
}

impl Replacer for InlineBiblioAnchorReplacer<'_, '_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        let id = &caps[1];

        // The displayed reference text is the xreftext if supplied, otherwise the
        // label itself, always enclosed in square brackets (e.g. `[gof]`). This
        // same bracketed text is registered as the entry's reftext so a
        // cross-reference to the entry renders identically.
        let label = caps.get(2).map(|m| m.as_str()).unwrap_or(id);
        let reftext = format!("[{label}]");

        if self
            .parser
            .register_ref(id, Some(&reftext), crate::document::RefType::Bibliography)
            .is_err()
        {
            self.parser.record_substitution_warning(
                self.source,
                crate::warnings::WarningType::DuplicateId(id.to_string()),
            );
        }

        self.parser.renderer.render_anchor(id, None, dest);
        dest.push_str(&reftext);
    }
}

/// Matches an anchor (i.e., id + optional reference text) in the flow of text.
///
/// ##Examples
///
/// * `[[idname]]`
/// * `[[idname,Reference Text]]`
/// * `anchor:idname[]`
/// * `anchor:idname[Reference Text]`
static INLINE_ANCHOR: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?x)
    (\\)?                           # (1) optional escape backslash before the anchor

    (?:                             # either [[id[, reftext]]] OR anchor:id[reftext]
      \[\[                          # [[
        (                           # (2) anchor id for [[...]]
          [\p{Alphabetic}_:]        #     first char: letter, '_' or ':'
          [\p{Alphabetic}\p{Nd}_\-:.]*  # rest: letters/digits/_ or '-', ':', '.'
        )
        (?: , \s* (.+?) )?          # (3) optional reftext after comma (lazy)
        \]\]                        # ]]
      |
        anchor:                     # 'anchor:' prefix
        (                           # (4) anchor id for anchor:...[]
          [\p{Alphabetic}_:]        #     first char: letter, '_' or ':'
          [\p{Alphabetic}\p{Nd}_\-:.]*  # rest: letters/digits/_ or '-', ':', '.'
        )                           # end (4)
        \[                          # opening '[' for reftext
          (?:                       # either empty [] or a non-empty reftext
            \]                      #   empty -> immediate ']'
          |                         #   OR
            (.*?[^\\])              # (5) non-empty reftext (ends with a non-escaped char)
            \]                      #   closing ']'
          )
    )                               # end alternation
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineAnchorReplacer<'p>(&'p Parser);

impl Replacer for InlineAnchorReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        if caps.get(1).is_some() {
            dest.push_str(&caps[0][1..]);
            return;
        }

        // NOTE: reftext is only relevant for DocBook output;
        // in that case it is used as value of xreflabel attribute.

        let (id, reftext) = if let Some(id) = caps.get(2) {
            (id.as_str(), caps.get(3).map(|m| m.as_str().to_string()))
        } else {
            (
                &caps[4],
                caps.get(5)
                    .map(|m| m.as_str().to_string().replace("\\]", "]")),
            )
        };

        // Register the inline anchor so that later cross-references can resolve
        // against it. A duplicate ID here is non-fatal (first registration
        // wins); block- and section-level registration paths surface duplicate
        // warnings, so we don't double-report them for inline anchors.
        let _ = self
            .0
            .register_ref(id, reftext.as_deref(), crate::document::RefType::Anchor);

        self.0.renderer.render_anchor(id, reftext, dest);
    }
}

/// Matches a cross-reference, in either the double-angle-bracket shorthand or
/// the `xref:` macro form.
///
/// Note that the special-characters substitution runs before macros, so by this
/// point `<<` and `>>` have already become `&lt;&lt;` and `&gt;&gt;`.
///
/// ## Examples
///
/// * `<<idname>>` (seen here as `&lt;&lt;idname&gt;&gt;`)
/// * `<<idname,Reference Text>>`
/// * `xref:idname[]`
/// * `xref:idname[Reference Text]`
static INLINE_XREF: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)
        (\\)?                           # (1) optional escape backslash
        (?:
            &lt;&lt;                     #   shorthand: << (post special-chars)
              ( .*? )                    # (2) refid plus optional ", reftext"
            &gt;&gt;                     #   >>
          |
            xref:                        #   'xref:' macro form
              ( [^:\s\[] [^\s\[]* )      # (3) target
            \[                           #   opening '['
              ( | .*?[^\\] )             # (4) reftext: empty or ends non-escaped
            \]                           #   closing ']'
        )
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineXrefReplacer<'p, 'x> {
    parser: &'p Parser,

    /// Accumulates the cross-references discovered during replacement, in the
    /// same order as the placeholders emitted into the output.
    xrefs: &'x mut Vec<XrefSegment>,
}

impl Replacer for InlineXrefReplacer<'_, '_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        if caps.get(1).is_some() {
            // Honor the escape: emit the reference literally (sans backslash).
            dest.push_str(&caps[0][1..]);
            return;
        }

        let mut window: Option<String> = None;
        let mut roles: Vec<String> = vec![];

        let (target, provided_text) = if let Some(inner) = caps.get(2) {
            // Shorthand form: split an optional ", reftext" off the id. The id
            // is always treated as a same-document reference, even when it
            // contains a dot.
            match inner.as_str().split_once(',') {
                Some((id, text)) => (id.trim().to_string(), Some(text.trim().to_string())),
                None => (inner.as_str().trim().to_string(), None),
            }
        } else {
            // `xref:` macro form. A target that begins with `#` is an explicit
            // same-document reference (the hash is dropped); any other target
            // that contains a dot is treated as an inter-document reference and
            // left for a host-supplied resolver to interpret.
            let raw_target = &caps[3];
            let target = raw_target
                .strip_prefix('#')
                .unwrap_or(raw_target)
                .to_string();

            // The bracketed text is parsed as an attribute list when it contains
            // an `=` (mirroring the link macro): the first positional attribute
            // is the link text, and named attributes such as `window` and `role`
            // are honored. Otherwise the whole text is the link text.
            let raw_text = caps.get(4).map(|m| m.as_str()).unwrap_or_default();

            let provided_text = if raw_text.is_empty() {
                None
            } else if raw_text.contains('=') {
                let normalized = raw_text.replace('\n', " ");
                let attrlist =
                    Attrlist::parse(Span::new(&normalized), self.parser, AttrlistContext::Inline)
                        .item
                        .item;

                window = attrlist
                    .named_attribute("window")
                    .map(|a| a.value().to_string());
                roles = attrlist.roles().iter().map(|r| r.to_string()).collect();

                attrlist
                    .nth_attribute(1)
                    .map(|a| a.value().to_string())
                    .filter(|s| !s.is_empty())
            } else {
                Some(raw_text.replace("\\]", "]"))
            };

            (target, provided_text)
        };

        let index = self.xrefs.len();
        self.xrefs.push(XrefSegment {
            target,
            provided_text,
            window,
            roles,
            resolved: None,
        });

        dest.push_str(&Content::xref_placeholder(index));
    }
}

/// Matches a [footnote] inline macro, in either the `footnote:` form or the
/// deprecated `footnoteref:` form.
///
/// ## Examples
///
/// * `footnote:[text]` — an anonymous footnote
/// * `footnote:id[text]` — a footnote with an ID, so it can be referenced again
/// * `footnote:id[]` — a reference to a previously-defined footnote
/// * `footnoteref:[id,text]` / `footnoteref:[id]` — the deprecated equivalents
///
/// Asciidoctor anchors the match with a `(?!</a>)` look-ahead after the closing
/// bracket so a `footnote:[…]` that forms the text of an already-rendered link
/// is not matched again; the `regex` crate has no look-ahead, so
/// [`InlineFootnoteMacroReplacer`] re-creates that guard by inspecting the text
/// that follows the match.
///
/// [footnote]: https://docs.asciidoctor.org/asciidoc/latest/macros/footnote/
static INLINE_FOOTNOTE_MACRO: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)                     # extended mode; dot matches newline
        \\?                          # optional escaping backslash
        footnote
        (?:
            (ref):                   # (1) the deprecated 'footnoteref:' form
          |
            : ([\w-]+)?              # (2) optional id for the 'footnote:id' form
        )
        \[
            (?: | (.*?[^\\]) )       # (3) text: empty, or ends in a non-backslash
        \]
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineFootnoteMacroReplacer<'p, 's, 'x> {
    parser: &'p Parser,

    /// The original (pre-substitution) span of the content being rendered, used
    /// to locate any warning recorded while resolving a footnote.
    source: Span<'s>,

    /// The enclosing block's cross-references, produced by the (earlier)
    /// cross-reference pass. A footnote whose text contains a cross-reference
    /// placeholder re-homes the referenced segments out of this list onto
    /// itself.
    all_xrefs: &'x [XrefSegment],
}

impl LookaheadReplacer for InlineFootnoteMacroReplacer<'_, '_, '_> {
    fn replace_append(
        &mut self,
        caps: &Captures<'_>,
        dest: &mut String,
        after: &str,
    ) -> LookaheadResult {
        // Adapted from Asciidoctor#sub_macros (the `InlineFootnoteMacroRx`
        // branch), found in
        // https://github.com/asciidoctor/asciidoctor/blob/main/lib/asciidoctor/substitutors.rb.

        // Honor the escape: emit the macro text without the leading backslash.
        if caps[0].starts_with('\\') {
            dest.push_str(&caps[0][1..]);
            return LookaheadResult::Continue;
        }

        // Re-create Asciidoctor's `(?!</a>)` look-ahead: a closing bracket
        // immediately followed by `</a>` is not a footnote (it closes an
        // already-rendered link), so the macro is left untouched.
        if after.starts_with("</a>") {
            dest.push_str(&caps[0]);
            return LookaheadResult::Continue;
        }

        let parser = self.parser;

        // Resolve the macro into an (id, text) pair. The deprecated
        // `footnoteref:` form packs both into the bracketed text (`id,text`),
        // whereas the `footnote:` form takes the id from the macro target.
        let (id, content): (Option<String>, Option<String>) = if caps.get(1).is_some() {
            // `footnoteref:` form. With no bracketed text at all it is left
            // untouched (matching Asciidoctor's `next $&`).
            let Some(raw) = caps.get(3).map(|m| m.as_str()) else {
                dest.push_str(&caps[0]);
                return LookaheadResult::Continue;
            };

            // The `footnoteref:` macro is deprecated outside compatibility mode.
            if !parser.is_attribute_set("compat-mode") {
                parser.record_substitution_warning(
                    self.source,
                    WarningType::DeprecatedFootnorefMacro(caps[0].to_string()),
                );
            }

            match raw.split_once(',') {
                Some((id, content)) => (Some(id.to_string()), Some(content.to_string())),
                None => (Some(raw.to_string()), None),
            }
        } else {
            // `footnote:` form.
            (
                caps.get(2).map(|m| m.as_str().to_string()),
                caps.get(3).map(|m| m.as_str().to_string()),
            )
        };

        // `id` and `content` own their data, so each branch renders its marker
        // before they are dropped (the params borrow them).
        if let Some(id) = id {
            if let Some(index) = parser.footnote_index_for_id(&id) {
                // A reference to an already-defined footnote: reuse its number.
                parser.renderer.render_footnote(
                    &FootnoteRenderParams {
                        index: Some(index.as_str()),
                        id: None,
                        is_reference: true,
                        text: "",
                    },
                    dest,
                );
            } else if let Some(content) = content {
                // A defining occurrence that also carries an ID.
                let (template, xrefs) = crate::content::rehome_xref_placeholders(
                    &normalize_footnote_text(&content),
                    self.all_xrefs,
                );
                let index = parser.define_footnote(Some(&id), template, xrefs);
                parser.renderer.render_footnote(
                    &FootnoteRenderParams {
                        index: Some(index.as_str()),
                        id: Some(&id),
                        is_reference: false,
                        text: "",
                    },
                    dest,
                );
            } else {
                // A reference to an ID that was never defined.
                parser.record_substitution_warning(
                    self.source,
                    WarningType::InvalidFootnoteReference(id.clone()),
                );
                parser.renderer.render_footnote(
                    &FootnoteRenderParams {
                        index: None,
                        id: None,
                        is_reference: true,
                        text: &id,
                    },
                    dest,
                );
            }
        } else if let Some(content) = content {
            // An anonymous defining occurrence.
            let (template, xrefs) = crate::content::rehome_xref_placeholders(
                &normalize_footnote_text(&content),
                self.all_xrefs,
            );
            let index = parser.define_footnote(None, template, xrefs);
            parser.renderer.render_footnote(
                &FootnoteRenderParams {
                    index: Some(index.as_str()),
                    id: None,
                    is_reference: false,
                    text: "",
                },
                dest,
            );
        } else {
            // `footnote:[]` with neither an ID nor text is not a footnote.
            dest.push_str(&caps[0]);
        }

        LookaheadResult::Continue
    }
}

/// Normalizes the text of a footnote: trims surrounding whitespace, collapses
/// each embedded newline to a space (Asciidoctor compacts a multi-line footnote
/// onto a single line), and unescapes an escaped closing square bracket
/// (`\]` -> `]`). Mirrors Asciidoctor's `normalize_text text, true, true`.
fn normalize_footnote_text(content: &str) -> String {
    content.trim().replace('\n', " ").replace("\\]", "]")
}

static URI_SNIFF: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(r#"^\p{alpha}[\p{alpha}\p{digit}.+-]+:/{0,2}"#).unwrap()
});

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    //! This test suite fills in a few coverage gaps after doing spec-driven
    //! development (SDD) for macro parsing.

    mod inline_link {
        use crate::tests::prelude::*;

        #[test]
        fn escape_angle_bracket_autolink_before_lt() {
            let doc = Parser::default()
                .parse("You'll often see \\<https://example.org> used in examples.");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "You'll often see \\<https://example.org> used in examples.",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "You&#8217;ll often see &lt;https://example.org&gt; used in examples.",
                        },
                        source: Span {
                            data: "You'll often see \\<https://example.org> used in examples.",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "You'll often see \\<https://example.org> used in examples.",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn escape_angle_bracket_autolink_before_scheme() {
            let doc = Parser::default()
                .parse("You'll often see <\\https://example.org> used in examples.");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "You'll often see <\\https://example.org> used in examples.",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "You&#8217;ll often see &lt;https://example.org&gt; used in examples.",
                        },
                        source: Span {
                            data: "You'll often see <\\https://example.org> used in examples.",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "You'll often see <\\https://example.org> used in examples.",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn empty_inside_angle_brackets() {
            let doc = Parser::default().parse("There's no actual link <https://> in here.");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "There's no actual link <https://> in here.",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "There&#8217;s no actual link &lt;https://&gt; in here.",
                        },
                        source: Span {
                            data: "There's no actual link <https://> in here.",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "There's no actual link <https://> in here.",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn hide_uri_scheme() {
            let doc = Parser::default().parse("= Test Page\n:hide-uri-scheme:\n\nWe don't want you to know that this is HTTP: <https://example.com> just now.");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: Some(Span {
                            data: "Test Page",
                            line: 1,
                            col: 3,
                            offset: 2,
                        },),
                        title: Some("Test Page",),
                        attributes: &[Attribute {
                            name: Span {
                                data: "hide-uri-scheme",
                                line: 2,
                                col: 2,
                                offset: 13,
                            },
                            value_source: None,
                            value: InterpretedValue::Set,
                            source: Span {
                                data: ":hide-uri-scheme:",
                                line: 2,
                                col: 1,
                                offset: 12,
                            },
                        },],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "= Test Page\n:hide-uri-scheme:",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "We don't want you to know that this is HTTP: <https://example.com> just now.",
                                line: 4,
                                col: 1,
                                offset: 31,
                            },
                            rendered: "We don&#8217;t want you to know that this is HTTP: <a href=\"https://example.com\" class=\"bare\">example.com</a> just now.",
                        },
                        source: Span {
                            data: "We don't want you to know that this is HTTP: <https://example.com> just now.",
                            line: 4,
                            col: 1,
                            offset: 31,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "= Test Page\n:hide-uri-scheme:\n\nWe don't want you to know that this is HTTP: <https://example.com> just now.",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn link_with_semicolon_suffix() {
            let doc = Parser::default().parse(
                "You shouldn't visit https://example.com; it's just there to illustrate examples.",
            );

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "You shouldn't visit https://example.com; it's just there to illustrate examples.",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "You shouldn&#8217;t visit <a href=\"https://example.com\" class=\"bare\">https://example.com</a>; it&#8217;s just there to illustrate examples.",
                        },
                        source: Span {
                            data: "You shouldn't visit https://example.com; it's just there to illustrate examples.",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "You shouldn't visit https://example.com; it's just there to illustrate examples.",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn link_with_paren_and_colon_suffix() {
            let doc = Parser::default().parse(
            "You shouldn't visit that site (https://example.com): it's just there to illustrate examples.",
        );

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "You shouldn't visit that site (https://example.com): it's just there to illustrate examples.",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "You shouldn&#8217;t visit that site (<a href=\"https://example.com\" class=\"bare\">https://example.com</a>): it&#8217;s just there to illustrate examples.",
                        },
                        source: Span {
                            data: "You shouldn't visit that site (https://example.com): it's just there to illustrate examples.",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "You shouldn't visit that site (https://example.com): it's just there to illustrate examples.",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn named_attributes_without_link_text_and_hide_uri_scheme() {
            let doc = Parser::default()
            .parse("= Test\n:hide-uri-scheme:\n\nhttps://chat.asciidoc.org[role=button,window=_blank,opts=nofollow]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: Some(Span {
                            data: "Test",
                            line: 1,
                            col: 3,
                            offset: 2,
                        },),
                        title: Some("Test",),
                        attributes: &[Attribute {
                            name: Span {
                                data: "hide-uri-scheme",
                                line: 2,
                                col: 2,
                                offset: 8,
                            },
                            value_source: None,
                            value: InterpretedValue::Set,
                            source: Span {
                                data: ":hide-uri-scheme:",
                                line: 2,
                                col: 1,
                                offset: 7,
                            },
                        },],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "= Test\n:hide-uri-scheme:",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "https://chat.asciidoc.org[role=button,window=_blank,opts=nofollow]",
                                line: 4,
                                col: 1,
                                offset: 26,
                            },
                            rendered: "<a href=\"https://chat.asciidoc.org\" class=\"bare button\" target=\"_blank\" rel=\"nofollow\" noopener>chat.asciidoc.org</a>",
                        },
                        source: Span {
                            data: "https://chat.asciidoc.org[role=button,window=_blank,opts=nofollow]",
                            line: 4,
                            col: 1,
                            offset: 26,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "= Test\n:hide-uri-scheme:\n\nhttps://chat.asciidoc.org[role=button,window=_blank,opts=nofollow]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }
    }

    mod link_macro {
        use crate::tests::prelude::*;

        #[test]
        fn escape_link_macro() {
            let doc =
                Parser::default().parse("A link macro looks like this: \\link:target[link text].");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "A link macro looks like this: \\link:target[link text].",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "A link macro looks like this: link:target[link text].",
                        },
                        source: Span {
                            data: "A link macro looks like this: \\link:target[link text].",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "A link macro looks like this: \\link:target[link text].",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn empty_mailto_link() {
            let doc = Parser::default().parse("mailto:[,Subscribe me]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "mailto:[,Subscribe me]",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "mailto:[,Subscribe me]",
                        },
                        source: Span {
                            data: "mailto:[,Subscribe me]",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "mailto:[,Subscribe me]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn empty_link_text_with_hide_uri_scheme() {
            let doc = Parser::default()
                .parse("= Test Document\n:hide-uri-scheme:\n\nlink:https://example.com[]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: Some(Span {
                            data: "Test Document",
                            line: 1,
                            col: 3,
                            offset: 2,
                        },),
                        title: Some("Test Document",),
                        attributes: &[Attribute {
                            name: Span {
                                data: "hide-uri-scheme",
                                line: 2,
                                col: 2,
                                offset: 17,
                            },
                            value_source: None,
                            value: InterpretedValue::Set,
                            source: Span {
                                data: ":hide-uri-scheme:",
                                line: 2,
                                col: 1,
                                offset: 16,
                            },
                        },],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "= Test Document\n:hide-uri-scheme:",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "link:https://example.com[]",
                                line: 4,
                                col: 1,
                                offset: 35,
                            },
                            rendered: "<a href=\"https://example.com\" class=\"bare\">example.com</a>",
                        },
                        source: Span {
                            data: "link:https://example.com[]",
                            line: 4,
                            col: 1,
                            offset: 35,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "= Test Document\n:hide-uri-scheme:\n\nlink:https://example.com[]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn empty_mailto_link_text_with_hide_uri_scheme() {
            let doc = Parser::default()
                .parse("= Test Document\n:hide-uri-scheme:\n\nlink:mailto:fred@example.com[]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: Some(Span {
                            data: "Test Document",
                            line: 1,
                            col: 3,
                            offset: 2,
                        },),
                        title: Some("Test Document",),
                        attributes: &[Attribute {
                            name: Span {
                                data: "hide-uri-scheme",
                                line: 2,
                                col: 2,
                                offset: 17,
                            },
                            value_source: None,
                            value: InterpretedValue::Set,
                            source: Span {
                                data: ":hide-uri-scheme:",
                                line: 2,
                                col: 1,
                                offset: 16,
                            },
                        },],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "= Test Document\n:hide-uri-scheme:",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "link:mailto:fred@example.com[]",
                                line: 4,
                                col: 1,
                                offset: 35,
                            },
                            rendered: "<a href=\"mailto:fred@example.com\" class=\"bare\">fred@example.com</a>",
                        },
                        source: Span {
                            data: "link:mailto:fred@example.com[]",
                            line: 4,
                            col: 1,
                            offset: 35,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "= Test Document\n:hide-uri-scheme:\n\nlink:mailto:fred@example.com[]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }
    }

    mod inline_anchor {
        use crate::tests::prelude::*;

        #[test]
        fn inline_ref_double_brackets() {
            let doc = Parser::default().parse("Here you can read about tigers.[[tigers]]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "Here you can read about tigers.[[tigers]]",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "Here you can read about tigers.<a id=\"tigers\"></a>",
                        },
                        source: Span {
                            data: "Here you can read about tigers.[[tigers]]",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "Here you can read about tigers.[[tigers]]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog {
                        refs: HashMap::from([(
                            "tigers",
                            RefEntry {
                                id: "tigers",
                                reftext: None,
                                ref_type: crate::document::RefType::Anchor,
                            },
                        )]),
                        reftext_to_id: HashMap::new(),
                    },
                }
            );
        }

        #[test]
        fn inline_ref_macro() {
            let doc = Parser::default().parse("Here you can read about tigers.anchor:tigers[]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "Here you can read about tigers.anchor:tigers[]",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "Here you can read about tigers.<a id=\"tigers\"></a>",
                        },
                        source: Span {
                            data: "Here you can read about tigers.anchor:tigers[]",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "Here you can read about tigers.anchor:tigers[]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog {
                        refs: HashMap::from([(
                            "tigers",
                            RefEntry {
                                id: "tigers",
                                reftext: None,
                                ref_type: crate::document::RefType::Anchor,
                            },
                        )]),
                        reftext_to_id: HashMap::new(),
                    },
                }
            );
        }

        #[test]
        fn inline_ref_with_reftext_double_brackets() {
            let doc = Parser::default().parse("Here you can read about tigers.[[tigers,Tigers]]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "Here you can read about tigers.[[tigers,Tigers]]",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "Here you can read about tigers.<a id=\"tigers\"></a>",
                        },
                        source: Span {
                            data: "Here you can read about tigers.[[tigers,Tigers]]",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "Here you can read about tigers.[[tigers,Tigers]]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog {
                        refs: HashMap::from([(
                            "tigers",
                            RefEntry {
                                id: "tigers",
                                reftext: Some("Tigers"),
                                ref_type: crate::document::RefType::Anchor,
                            },
                        )]),
                        reftext_to_id: HashMap::from([("Tigers", "tigers")]),
                    },
                }
            );
        }

        #[test]
        fn inline_ref_with_reftext_macro() {
            let doc =
                Parser::default().parse("Here you can read about tigers.anchor:tigers[Tigers]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "Here you can read about tigers.anchor:tigers[Tigers]",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "Here you can read about tigers.<a id=\"tigers\"></a>",
                        },
                        source: Span {
                            data: "Here you can read about tigers.anchor:tigers[Tigers]",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "Here you can read about tigers.anchor:tigers[Tigers]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog {
                        refs: HashMap::from([(
                            "tigers",
                            RefEntry {
                                id: "tigers",
                                reftext: Some("Tigers"),
                                ref_type: crate::document::RefType::Anchor,
                            },
                        )]),
                        reftext_to_id: HashMap::from([("Tigers", "tigers")]),
                    },
                }
            );
        }

        #[test]
        fn mixed_inline_anchor_macro_and_anchor_shorthand_with_empty_reftext() {
            let doc =
                Parser::default().parse("anchor:one[][[two]]anchor:three[][[four]]anchor:five[]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "anchor:one[][[two]]anchor:three[][[four]]anchor:five[]",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: r#"<a id="one"></a><a id="two"></a><a id="three"></a><a id="four"></a><a id="five"></a>"#,
                        },
                        source: Span {
                            data: "anchor:one[][[two]]anchor:three[][[four]]anchor:five[]",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "anchor:one[][[two]]anchor:three[][[four]]anchor:five[]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog {
                        refs: HashMap::from([
                            (
                                "one",
                                RefEntry {
                                    id: "one",
                                    reftext: None,
                                    ref_type: crate::document::RefType::Anchor,
                                },
                            ),
                            (
                                "two",
                                RefEntry {
                                    id: "two",
                                    reftext: None,
                                    ref_type: crate::document::RefType::Anchor,
                                },
                            ),
                            (
                                "three",
                                RefEntry {
                                    id: "three",
                                    reftext: None,
                                    ref_type: crate::document::RefType::Anchor,
                                },
                            ),
                            (
                                "four",
                                RefEntry {
                                    id: "four",
                                    reftext: None,
                                    ref_type: crate::document::RefType::Anchor,
                                },
                            ),
                            (
                                "five",
                                RefEntry {
                                    id: "five",
                                    reftext: None,
                                    ref_type: crate::document::RefType::Anchor,
                                },
                            ),
                        ]),
                        reftext_to_id: HashMap::new(),
                    },
                }
            );
        }

        #[test]
        fn inline_ref_can_start_with_colon() {
            let doc = Parser::default().parse("[[:idname]] text");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "[[:idname]] text",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "<a id=\":idname\"></a> text",
                        },
                        source: Span {
                            data: "[[:idname]] text",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "[[:idname]] text",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog {
                        refs: HashMap::from([(
                            ":idname",
                            RefEntry {
                                id: ":idname",
                                reftext: None,
                                ref_type: crate::document::RefType::Anchor,
                            },
                        )]),
                        reftext_to_id: HashMap::new(),
                    },
                }
            );
        }

        #[test]
        fn inline_ref_cannot_start_with_digit() {
            let doc = Parser::default().parse("[[1-install]] text");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "[[1-install]] text",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "[[1-install]] text",
                        },
                        source: Span {
                            data: "[[1-install]] text",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "[[1-install]] text",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn escaped_inline_ref_square_brackets() {
            let doc = Parser::default().parse("Here you can read about tigers.\\[[tigers]]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "Here you can read about tigers.\\[[tigers]]",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "Here you can read about tigers.[[tigers]]",
                        },
                        source: Span {
                            data: "Here you can read about tigers.\\[[tigers]]",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "Here you can read about tigers.\\[[tigers]]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }

        #[test]
        fn escaped_inline_ref_macro() {
            let doc = Parser::default().parse("Here you can read about tigers.\\anchor:tigers[]");

            assert_eq!(
                doc,
                Document {
                    header: Header {
                        title_source: None,
                        title: None,
                        attributes: &[],
                        author_line: None,
                        revision_line: None,
                        comments: &[],
                        source: Span {
                            data: "",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                    },
                    blocks: &[Block::Simple(SimpleBlock {
                        content: Content {
                            original: Span {
                                data: "Here you can read about tigers.\\anchor:tigers[]",
                                line: 1,
                                col: 1,
                                offset: 0,
                            },
                            rendered: "Here you can read about tigers.anchor:tigers[]",
                        },
                        source: Span {
                            data: "Here you can read about tigers.\\anchor:tigers[]",
                            line: 1,
                            col: 1,
                            offset: 0,
                        },
                        style: SimpleBlockStyle::Paragraph,
                        title_source: None,
                        title: None,
                        caption: None,
                        number: None,
                        anchor: None,
                        anchor_reftext: None,
                        attrlist: None,
                    },),],
                    source: Span {
                        data: "Here you can read about tigers.\\anchor:tigers[]",
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    warnings: &[],
                    source_map: SourceMap(&[]),
                    catalog: Catalog::default(),
                }
            );
        }
    }

    mod bibliography_anchor {
        #![allow(clippy::indexing_slicing)]

        use crate::tests::prelude::*;

        #[test]
        fn recognized_only_when_it_prefixes_the_entry() {
            // A `[[[id]]]` that does not prefix the entry is not a bibliography
            // anchor: it falls through to the regular inline-anchor pass (matching
            // Asciidoctor), rendering as `[<a id="mid"></a>]` rather than the
            // bibliography form `<a id="mid"></a>[mid]`.
            let doc = Parser::default().parse("[bibliography]\n* Smith. See [[[mid]]] inline.\n");

            let rendered = &rendered_paragraphs(&doc)[0];
            assert!(
                rendered.contains("[<a id=\"mid\"></a>]"),
                "unexpected: {rendered}"
            );
            assert!(!rendered.contains("<a id=\"mid\"></a>[mid]"));

            // The entry is registered as a normal anchor, not a bibliography one.
            assert_eq!(
                doc.catalog().get_ref("mid").map(|e| e.ref_type.clone()),
                Some(crate::document::RefType::Anchor)
            );
        }

        #[test]
        fn leading_backslash_is_not_a_bibliography_escape() {
            // A leading backslash does not escape a bibliography anchor (the only
            // documented escape is `[\[[id]]]`). `\[[[id]]]` does not begin with
            // `[[[`, so it is not a bibliography anchor; the backslash stays
            // literal and the inner `[[id]]` becomes a normal inline anchor,
            // matching Asciidoctor's `\[<a id="x"></a>]`.
            let doc = Parser::default().parse("[bibliography]\n* \\[[[x]]] Leading backslash.\n");

            let rendered = &rendered_paragraphs(&doc)[0];
            assert!(
                rendered.starts_with("\\[<a id=\"x\"></a>]"),
                "unexpected: {rendered}"
            );
        }

        #[test]
        fn explicit_style_applies_to_an_ordered_list() {
            // An explicit `[bibliography]` attribute applies to any list type, so
            // an ordered list's entries are recognized as bibliography anchors,
            // matching Asciidoctor (`<div class="olist bibliography">`).
            let doc = Parser::default().parse("[bibliography]\n. [[[ord]]] Ordered entry.\n");

            assert_css(&doc, ".olist.bibliography", 1);
            assert!(rendered_paragraphs(&doc)[0].starts_with("<a id=\"ord\"></a>[ord] "));
        }

        #[test]
        fn section_style_does_not_apply_to_an_ordered_list() {
            // The style inherited from a `bibliography` section applies only to
            // unordered lists, so an ordered list in that section is not a
            // bibliography list; its leading `[[[id]]]` is a regular inline anchor.
            let doc = Parser::default()
                .parse("[bibliography]\n== References\n\n. [[[ord]]] Ordered entry.\n");

            assert_css(&doc, ".bibliography", 0);
            assert!(rendered_paragraphs(&doc)[0].starts_with("[<a id=\"ord\"></a>] "));
        }
    }
}