Class: Wikitext::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/wikitext/parser.rb,
ext/wikitext/wikitext.c

Defined Under Namespace

Classes: Error, Token

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Object



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
# File 'ext/wikitext/parser.c', line 1004

VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
{
    // process arguments
    VALUE options;
    if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
        options = Qnil;

    // defaults
    VALUE autolink                      = Qtrue;
    VALUE line_ending                   = rb_str_new2("\n");
    VALUE external_link_class           = rb_str_new2("external");
    VALUE external_link_rel             = Qnil;
    VALUE mailto_class                  = rb_str_new2("mailto");
    VALUE link_proc                     = Qnil;
    VALUE internal_link_prefix          = rb_str_new2("/wiki/");
    VALUE img_prefix                    = rb_str_new2("/images/");
    VALUE output_style                  = ID2SYM(rb_intern("html"));
    VALUE space_to_underscore           = Qtrue;
    VALUE pre_code                      = Qfalse;
    VALUE minimum_fulltext_token_length = INT2NUM(3);
    VALUE base_heading_level            = INT2NUM(0);

    // process options hash (override defaults)
    if (!NIL_P(options) && TYPE(options) == T_HASH)
    {
#define OVERRIDE_IF_SET(name)   rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
                                rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
        autolink                        = OVERRIDE_IF_SET(autolink);
        line_ending                     = OVERRIDE_IF_SET(line_ending);
        external_link_class             = OVERRIDE_IF_SET(external_link_class);
        external_link_rel               = OVERRIDE_IF_SET(external_link_rel);
        mailto_class                    = OVERRIDE_IF_SET(mailto_class);
        link_proc                       = OVERRIDE_IF_SET(link_proc);
        internal_link_prefix            = OVERRIDE_IF_SET(internal_link_prefix);
        img_prefix                      = OVERRIDE_IF_SET(img_prefix);
        output_style                    = OVERRIDE_IF_SET(output_style);
        space_to_underscore             = OVERRIDE_IF_SET(space_to_underscore);
        pre_code                        = OVERRIDE_IF_SET(pre_code);
        minimum_fulltext_token_length   = OVERRIDE_IF_SET(minimum_fulltext_token_length);
        base_heading_level              = OVERRIDE_IF_SET(base_heading_level);
    }

    // no need to call super here; rb_call_super()
    rb_iv_set(self, "@autolink",                        autolink);
    rb_iv_set(self, "@line_ending",                     line_ending);
    rb_iv_set(self, "@external_link_class",             external_link_class);
    rb_iv_set(self, "@external_link_rel",               external_link_rel);
    rb_iv_set(self, "@mailto_class",                    mailto_class);
    rb_iv_set(self, "@link_proc",                       link_proc);
    rb_iv_set(self, "@internal_link_prefix",            internal_link_prefix);
    rb_iv_set(self, "@img_prefix",                      img_prefix);
    rb_iv_set(self, "@output_style",                    output_style);
    rb_iv_set(self, "@space_to_underscore",             space_to_underscore);
    rb_iv_set(self, "@pre_code",                        pre_code);
    rb_iv_set(self, "@minimum_fulltext_token_length",   minimum_fulltext_token_length);
    rb_iv_set(self, "@base_heading_level",              base_heading_level);
    return self;
}

Class Method Details



923
924
925
926
927
928
929
930
931
# File 'ext/wikitext/parser.c', line 923

VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
{
    parser_t parser;
    parser.space_to_underscore      = false;
    parser.link_target              = str_new_from_string(in);
    GC_WRAP_STR(parser.link_target, link_target_gc);
    wiki_encode_link_target(&parser);
    return string_from_str(parser.link_target);
}


839
840
841
842
843
844
845
846
847
# File 'ext/wikitext/parser.c', line 839

VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
{
    str_t *link_target = str_new_from_string(string);
    GC_WRAP_STR(link_target, link_target_gc);
    str_t *output = str_new();
    GC_WRAP_STR(output, output_gc);
    wiki_append_sanitized_link_target(link_target, output, true);
    return string_from_str(output);
}

.shared_parserObject



28
29
30
# File 'lib/wikitext/parser.rb', line 28

def self.shared_parser
  @@shared_parser_instance ||= new
end

Instance Method Details

#benchmarking_tokenize(string) ⇒ Object

for benchmarking raw tokenization speed only



209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'ext/wikitext/parser.c', line 209

VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
{
    if (NIL_P(string))
        return Qnil;
    string = StringValue(string);
    char *p = RSTRING_PTR(string);
    long len = RSTRING_LEN(string);
    char *pe = p + len;
    token_t token;
    next_token(&token, NULL, p, pe);
    while (token.type != END_OF_FILE)
        next_token(&token, &token, NULL, pe);
    return Qnil;
}

#fulltext_tokenize(*args) ⇒ Object



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
# File 'ext/wikitext/parser.c', line 224

VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
{
    // process arguments
    VALUE string, options;
    if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
        options = Qnil;
    if (NIL_P(string))
        return Qnil;
    string = StringValue(string);
    VALUE tokens = rb_ary_new();

    // check instance variables
    VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");

    // process options hash (can override instance variables)
    if (!NIL_P(options) && TYPE(options) == T_HASH)
    {
        if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
            min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
    }
    int min_len = NIL_P(min) ? 3 : NUM2INT(min);
    if (min_len < 0)
        min_len = 0;

    // set up scanner
    char *p = RSTRING_PTR(string);
    long len = RSTRING_LEN(string);
    char *pe = p + len;
    token_t token;
    token_t *_token = &token;
    next_token(&token, NULL, p, pe);
    while (token.type != END_OF_FILE)
    {
        switch (token.type)
        {
            case URI:
            case MAIL:
            case ALNUM:
                if (TOKEN_LEN(_token) >= min_len)
                    rb_ary_push(tokens, TOKEN_TEXT(_token));
                break;
            default:
                // ignore everything else
                break;
        }
        next_token(&token, &token, NULL, pe);
    }
    return tokens;
}

#parse(*args) ⇒ Object

fall back to default



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
# File 'ext/wikitext/parser.c', line 1074

VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
{
    // process arguments
    VALUE string, options;
    if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
        options = Qnil;
    if (NIL_P(string))
        return Qnil;
    string = StringValue(string);

    // access these once per parse
    VALUE line_ending   = rb_iv_get(self, "@line_ending");
    line_ending         = StringValue(line_ending);
    VALUE link_class    = rb_iv_get(self, "@external_link_class");
    link_class          = NIL_P(link_class) ? Qnil : StringValue(link_class);
    VALUE link_rel      = rb_iv_get(self, "@external_link_rel");
    link_rel            = NIL_P(link_rel) ? Qnil : StringValue(link_rel);
    VALUE link_proc     = rb_iv_get(self, "@link_proc");
    VALUE mailto_class  = rb_iv_get(self, "@mailto_class");
    mailto_class        = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
    VALUE prefix        = rb_iv_get(self, "@internal_link_prefix");
    int output_style    = Wikitext_output_style(rb_iv_get(self, "@output_style"));

    // process options hash
    int base_indent = 0;
    int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
    if (!NIL_P(options) && TYPE(options) == T_HASH)
    {
        // :indent => 0 (or more)
        ID has_key = rb_intern("has_key?");
        ID id = ID2SYM(rb_intern("indent"));
        if (rb_funcall(options, has_key, 1, id) == Qtrue)
        {
            VALUE indent = rb_hash_aref(options, id);
            if (indent == Qfalse)
                base_indent = -1; // indentation disabled
            else
            {
                base_indent = NUM2INT(indent);
                if (base_indent < 0)
                    base_indent = 0;
            }
        }

        // :base_heading_level => 0/1/2/3/4/5/6
        id = ID2SYM(rb_intern("base_heading_level"));
        if (rb_funcall(options, has_key, 1, id) == Qtrue)
            base_heading_level = NUM2INT(rb_hash_aref(options, id));

        // :external_link_rel => 'nofollow'
        id = ID2SYM(rb_intern("external_link_rel"));
        if (rb_funcall(options, has_key, 1, id) == Qtrue)
        {
            link_rel = rb_hash_aref(options, id);
            link_rel = NIL_P(link_rel) ? Qnil : StringValue(link_rel);
        }

        // :output_style => :html/:xml
        id = ID2SYM(rb_intern("output_style"));
        if (rb_funcall(options, has_key, 1, id) == Qtrue)
            output_style = Wikitext_output_style(rb_hash_aref(options, id));

        // :link_proc => lambda { |link_target| ... }
        id = ID2SYM(rb_intern("link_proc"));
        if (rb_funcall(options, has_key, 1, id) == Qtrue)
            link_proc = rb_hash_aref(options, id);
    }

    // normalize, regardless of whether this came from instance variable or override
    if (base_heading_level < 0)
        base_heading_level = 0;
    if (base_heading_level > 6)
        base_heading_level = 6;

    // set up scanner
    char *p = RSTRING_PTR(string);
    long len = RSTRING_LEN(string);
    char *pe = p + len;

    // set up parser struct to make passing parameters a little easier
    parser_t *parser                = parser_new();
    GC_WRAP_PARSER(parser, parser_gc);
    parser->external_link_class     = link_class;
    parser->external_link_rel       = link_rel;
    parser->mailto_class            = mailto_class;
    parser->img_prefix              = rb_iv_get(self, "@img_prefix");
    parser->autolink                = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
    parser->space_to_underscore     = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
    parser->pre_code                = rb_iv_get(self, "@pre_code") == Qtrue ? true : false;
    parser->line_ending             = str_new_from_string(line_ending);
    parser->base_indent             = base_indent;
    parser->base_heading_level      = base_heading_level;
    parser->output_style            = output_style;

    // this simple looping design leads to a single enormous function,
    // but it's faster than doing actual recursive descent and also secure in the face of
    // malicious input that seeks to overflow the stack
    // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
    // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
    // than a straightforward looping translator like this one anyway
    token_t _token;
    _token.type = NO_TOKEN;
    token_t *token = NULL;
    do
    {
        // note that whenever we grab a token we push it into the line buffer
        // this provides us with context-sensitive "memory" of what's been seen so far on this line
#define NEXT_TOKEN()    token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)

        // check to see if we have a token hanging around from a previous iteration of this loop
        if (token == NULL)
        {
            if (_token.type == NO_TOKEN)
            {
                // first time here (haven't started scanning yet)
                token = &_token;
                next_token(token, NULL, p, pe);
                ary_push(parser->line_buffer, token->type);
            }
            else
                // already scanning
                NEXT_TOKEN();
        }
        int type = token->type;

        // can't declare new variables inside a switch statement, so predeclare them here
        long remove_strong          = -1;
        long remove_em              = -1;

        // general purpose counters, flags and pointers
        long i                      = 0;
        long j                      = 0;
        long k                      = 0;
        str_t *output               = NULL;
        str_t _token_str;
        str_t *token_str            = &_token_str;

        // The following giant switch statement contains cases for all the possible token types.
        // In the most basic sense we are emitting the HTML that corresponds to each token,
        // but some tokens require context information in order to decide what to output.
        // For example, does the STRONG token (''') translate to <strong> or </strong>?
        // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
        //
        //  - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
        //  - the line buffer (records tokens seen so far on the current line)
        //  - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
        //
        // Although this is fairly complicated, there is one key simplifying factor:
        // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
        // scope stack (up to the current token) is valid; our translator can take this as a given.
        // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
        // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
        switch (type)
        {
            case PRE:
                if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
                {
                    str_append(parser->output, space, sizeof(space) - 1);
                    break;
                }
                else if (IN(BLOCKQUOTE_START))
                {
                    // this kind of nesting not allowed (to avoid user confusion)
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    output = parser->capture ? parser->capture : parser->output;
                    str_append(output, space, sizeof(space) - 1);
                    break;
                }

                // count number of BLOCKQUOTE tokens in line buffer and in scope stack
                ary_push(parser->line, PRE);
                i = ary_count(parser->line, BLOCKQUOTE);
                j = ary_count(parser->scope, BLOCKQUOTE);
                if (i < j)
                {
                    // must pop (reduce nesting level)
                    for (i = j - i; i > 0; i--)
                        wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
                }

                if (!IN(PRE))
                {
                    parser->pending_crlf = false;
                    wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
                    wiki_indent(parser);
                    str_append(parser->output, pre_start, sizeof(pre_start) - 1);
                    if (parser->pre_code)
                        str_append(parser->output, code_start, sizeof(code_start) - 1);
                    ary_push(parser->scope, PRE);
                }
                break;

            case PRE_START:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
                }
                else if (IN(BLOCKQUOTE_START))
                {
                    wiki_rollback_failed_link(parser); // if any
                    wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
                    wiki_append_pre_start(parser, token);
                }
                else if (IN(BLOCKQUOTE))
                {
                    if (token->column_start == 1) // only allowed in first column
                    {
                        wiki_rollback_failed_link(parser); // if any
                        wiki_pop_all_from_stack(parser);
                        wiki_append_pre_start(parser, token);
                    }
                    else // PRE_START illegal here
                    {
                        output = parser->capture ? parser->capture : parser->output;
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
                    }
                }
                else
                {
                    wiki_rollback_failed_link(parser); // if any
                    wiki_pop_from_stack_up_to(parser, NULL, P, true);
                    wiki_append_pre_start(parser, token);
                }
                break;

            case PRE_END:
                if (IN_EITHER_OF(NO_WIKI_START, PRE))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
                }
                else
                {
                    if (IN(PRE_START))
                        wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
                    else
                    {
                        output = parser->capture ? parser->capture : parser->output;
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
                    }
                }
                break;

            case BLOCKQUOTE:
                if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
                    // no need to check for <pre>; can never appear inside it
                    str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit "&gt;" or "&gt; "
                else if (IN(BLOCKQUOTE_START))
                {
                    // this kind of nesting not allowed (to avoid user confusion)
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    output = parser->capture ? parser->capture : parser->output;
                    str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit "&gt;" or "&gt; "
                    break;
                }
                else
                {
                    ary_push(parser->line, BLOCKQUOTE);

                    // count number of BLOCKQUOTE tokens in line buffer and in scope stack
                    i = ary_count(parser->line, BLOCKQUOTE);
                    j = ary_count(parser->scope, BLOCKQUOTE);

                    // given that BLOCKQUOTE tokens can be nested, peek ahead and see if there are any more which might affect the decision to push or pop
                    while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
                    {
                        ary_push(parser->line, BLOCKQUOTE);
                        i++;
                    }

                    // now decide whether to push, pop or do nothing
                    if (i > j)
                    {
                        // must push (increase nesting level)
                        wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
                        for (i = i - j; i > 0; i--)
                        {
                            wiki_indent(parser);
                            str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
                            str_append_str(parser->output, parser->line_ending);
                            ary_push(parser->scope, BLOCKQUOTE);
                        }
                    }
                    else if (i < j)
                    {
                        // must pop (reduce nesting level)
                        for (i = j - i; i > 0; i--)
                            wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
                    }

                    // jump to top of the loop to process token we scanned during lookahead
                    continue;
                }
                break;

            case BLOCKQUOTE_START:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
                }
                else if (IN(BLOCKQUOTE_START))
                {
                    // nesting is fine here
                    wiki_rollback_failed_link(parser); // if any
                    wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
                    wiki_indent(parser);
                    str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
                    str_append_str(parser->output, parser->line_ending);
                    ary_push(parser->scope, BLOCKQUOTE_START);
                    ary_push(parser->line, BLOCKQUOTE_START);
                }
                else if (IN(BLOCKQUOTE))
                {
                    if (token->column_start == 1) // only allowed in first column
                    {
                        wiki_rollback_failed_link(parser); // if any
                        wiki_pop_all_from_stack(parser);
                        wiki_indent(parser);
                        str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
                        str_append_str(parser->output, parser->line_ending);
                        ary_push(parser->scope, BLOCKQUOTE_START);
                        ary_push(parser->line, BLOCKQUOTE_START);
                    }
                    else // BLOCKQUOTE_START illegal here
                    {
                        output = parser->capture ? parser->capture : parser->output;
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
                    }
                }
                else
                {
                    // would be nice to eliminate the repetition here but it's probably the clearest way
                    wiki_rollback_failed_link(parser); // if any
                    wiki_pop_from_stack_up_to(parser, NULL, P, true);
                    wiki_indent(parser);
                    str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
                    str_append_str(parser->output, parser->line_ending);
                    ary_push(parser->scope, BLOCKQUOTE_START);
                    ary_push(parser->line, BLOCKQUOTE_START);
                }
                break;

            case BLOCKQUOTE_END:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
                }
                else
                {
                    if (IN(BLOCKQUOTE_START))
                        wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
                    else
                    {
                        output = parser->capture ? parser->capture : parser->output;
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
                    }
                }
                break;

            case NO_WIKI_START:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
                }
                else
                {
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    ary_push(parser->scope, NO_WIKI_START);
                    ary_push(parser->line, NO_WIKI_START);
                }
                break;

            case NO_WIKI_END:
                if (IN(NO_WIKI_START))
                    // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
                    wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
                else
                {
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
                }
                break;

            case STRONG_EM:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
                    break;
                }

                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);

                // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
                // otherwise, must open them
                remove_strong  = -1;
                remove_em      = -1;
                j              = parser->scope->count;
                for (j = j - 1; j >= 0; j--)
                {
                    int val = ary_entry(parser->scope, (int)j);
                    if (val == STRONG || val == STRONG_START)
                    {
                        str_append(output, strong_end, sizeof(strong_end) - 1);
                        remove_strong = j;
                    }
                    else if (val == EM || val == EM_START)
                    {
                        str_append(output, em_end, sizeof(em_end) - 1);
                        remove_em = j;
                    }
                }

                if (remove_strong > remove_em)      // must remove strong first
                {
                    ary_pop(parser->scope);
                    if (remove_em > -1)
                        ary_pop(parser->scope);
                    else    // there was no em to remove!, so consider this an opening em tag
                    {
                        str_append(output, em_start, sizeof(em_start) - 1);
                        ary_push(parser->scope, EM);
                        ary_push(parser->line, EM);
                    }
                }
                else if (remove_em > remove_strong) // must remove em first
                {
                    ary_pop(parser->scope);
                    if (remove_strong > -1)
                        ary_pop(parser->scope);
                    else    // there was no strong to remove!, so consider this an opening strong tag
                    {
                        str_append(output, strong_start, sizeof(strong_start) - 1);
                        ary_push(parser->scope, STRONG);
                        ary_push(parser->line, STRONG);
                    }
                }
                else    // no strong or em to remove, so this must be a new opening of both
                {
                    wiki_start_para_if_necessary(parser);
                    str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
                    ary_push(parser->scope, STRONG);
                    ary_push(parser->line, STRONG);
                    ary_push(parser->scope, EM);
                    ary_push(parser->line, EM);
                }
                break;

            case STRONG:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN(STRONG_START))
                        // already in span started with <strong>, no choice but to emit this literally
                        str_append(output, literal_strong, sizeof(literal_strong) - 1);
                    else if (IN(STRONG))
                        // STRONG already seen, this is a closing tag
                        wiki_pop_from_stack_up_to(parser, output, STRONG, true);
                    else
                    {
                        // this is a new opening
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, strong_start, sizeof(strong_start) - 1);
                        ary_push(parser->scope, STRONG);
                        ary_push(parser->line, STRONG);
                    }
                }
                break;

            case STRONG_START:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN_EITHER_OF(STRONG_START, STRONG))
                        str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
                    else
                    {
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, strong_start, sizeof(strong_start) - 1);
                        ary_push(parser->scope, STRONG_START);
                        ary_push(parser->line, STRONG_START);
                    }
                }
                break;

            case STRONG_END:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN(STRONG_START))
                        wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
                    else
                    {
                        // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
                    }
                }
                break;

            case EM:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, literal_em, sizeof(literal_em) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN(EM_START))
                        // already in span started with <em>, no choice but to emit this literally
                        str_append(output, literal_em, sizeof(literal_em) - 1);
                    else if (IN(EM))
                        // EM already seen, this is a closing tag
                        wiki_pop_from_stack_up_to(parser, output, EM, true);
                    else
                    {
                        // this is a new opening
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, em_start, sizeof(em_start) - 1);
                        ary_push(parser->scope, EM);
                        ary_push(parser->line, EM);
                    }
                }
                break;

            case EM_START:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN_EITHER_OF(EM_START, EM))
                        str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
                    else
                    {
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, em_start, sizeof(em_start) - 1);
                        ary_push(parser->scope, EM_START);
                        ary_push(parser->line, EM_START);
                    }
                }
                break;

            case EM_END:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN(EM_START))
                        wiki_pop_from_stack_up_to(parser, output, EM_START, true);
                    else
                    {
                        // no EM_START in scope, so must interpret the EM_END without any special meaning
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
                    }
                }
                break;

            case TT:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, backtick, sizeof(backtick) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN(TT_START))
                        // already in span started with <tt>, no choice but to emit this literally
                        str_append(output, backtick, sizeof(backtick) - 1);
                    else if (IN(TT))
                        // TT (`) already seen, this is a closing tag
                        wiki_pop_from_stack_up_to(parser, output, TT, true);
                    else
                    {
                        // this is a new opening
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, code_start, sizeof(code_start) - 1);
                        ary_push(parser->scope, TT);
                        ary_push(parser->line, TT);
                    }
                }
                break;

            case TT_START:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN_EITHER_OF(TT_START, TT))
                        str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
                    else
                    {
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, code_start, sizeof(code_start) - 1);
                        ary_push(parser->scope, TT_START);
                        ary_push(parser->line, TT_START);
                    }
                }
                break;

            case TT_END:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    if (IN(TT_START))
                        wiki_pop_from_stack_up_to(parser, output, TT_START, true);
                    else
                    {
                        // no TT_START in scope, so must interpret the TT_END without any special meaning
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
                    }
                }
                break;

            case OL:
            case UL:
                if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
                {
                    // no need to check for PRE; can never appear inside it
                    str_append(parser->output, token->start, TOKEN_LEN(token));
                    break;
                }

                // count number of tokens in line and scope stacks
                int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
                i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
                j = parser->scope->count - bq_count;
                k = i;

                // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
                for (;;)
                {
                    type = token->type;
                    if (type == OL || type == UL)
                    {
                        token = NULL;
                        if (i - k >= 2)                             // already seen at least one OL or UL
                        {
                            ary_push(parser->line, NESTED_LIST);    // which means this is a nested list
                            i += 3;
                        }
                        else
                            i += 2;
                        ary_push(parser->line, type);
                        ary_push(parser->line, LI);

                        // want to compare line with scope but can only do so if scope has enough items on it
                        if (j >= i)
                        {
                            if (ary_entry(parser->scope, (int)(i + bq_count - 2)) == type &&
                                ary_entry(parser->scope, (int)(i + bq_count - 1)) == LI)
                            {
                                // line and scope match at this point: do nothing yet
                            }
                            else
                            {
                                // item just pushed onto line does not match corresponding slot of scope!
                                for (; j >= i - 2; j--)
                                    // must pop back before emitting
                                    wiki_pop_from_stack(parser, NULL);

                                // will emit UL or OL, then LI
                                break;
                            }
                        }
                        else        // line stack size now exceeds scope stack size: must increase nesting level
                            break;  // will emit UL or OL, then LI
                    }
                    else
                    {
                        // not a OL or UL token!
                        if (j == i)
                            // must close existing LI and re-open new one
                            wiki_pop_from_stack(parser, NULL);
                        else if (j > i)
                        {
                            // item just pushed onto line does not match corresponding slot of scope!
                            for (; j >= i; j--)
                                // must pop back before emitting
                                wiki_pop_from_stack(parser, NULL);
                        }
                        break;
                    }
                    NEXT_TOKEN();
                }

                // will emit
                if (type == OL || type == UL)
                {
                    // if LI is at the top of a stack this is the start of a nested list
                    if (j > 0 && ary_entry(parser->scope, -1) == LI)
                    {
                        // so we should precede it with a CRLF, and indicate that it's a nested list
                        str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
                        ary_push(parser->scope, NESTED_LIST);
                    }
                    else
                    {
                        // this is a new list
                        if (IN(BLOCKQUOTE_START))
                            wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
                        else
                            wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
                    }

                    // emit
                    wiki_indent(parser);
                    if (type == OL)
                        str_append(parser->output, ol_start, sizeof(ol_start) - 1);
                    else if (type == UL)
                        str_append(parser->output, ul_start, sizeof(ul_start) - 1);
                    ary_push(parser->scope, type);
                    str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
                }
                else if (type == SPACE)
                    // silently throw away the optional SPACE token after final list marker
                    token = NULL;

                wiki_indent(parser);
                str_append(parser->output, li_start, sizeof(li_start) - 1);
                ary_push(parser->scope, LI);

                // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
                if (type == OL || type == UL)
                {
                    k = 0;
                    while (k++, NEXT_TOKEN(), (type = token->type))
                    {
                        if (type == OL || type == UL)
                            str_append(parser->output, token->start, TOKEN_LEN(token));
                        else if (type == SPACE && k == 1)
                        {
                            // silently throw away the optional SPACE token after final list marker
                            token = NULL;
                            break;
                        }
                        else
                            break;
                    }
                }

                // jump to top of the loop to process token we scanned during lookahead
                continue;

            case H6_START:
            case H5_START:
            case H4_START:
            case H3_START:
            case H2_START:
            case H1_START:
                if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
                {
                    // no need to check for PRE; can never appear inside it
                    str_append(parser->output, token->start, TOKEN_LEN(token));
                    break;
                }

                // pop up to but not including the last BLOCKQUOTE on the scope stack
                if (IN(BLOCKQUOTE_START))
                    wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
                else
                    wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);

                // count number of BLOCKQUOTE tokens in line buffer and in scope stack
                ary_push(parser->line, type);
                i = ary_count(parser->line, BLOCKQUOTE);
                j = ary_count(parser->scope, BLOCKQUOTE);

                // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
                if (i < j)
                {
                    // must pop (reduce nesting level)
                    for (i = j - i; i > 0; i--)
                        wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
                }

                // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
                while (NEXT_TOKEN(), (token->type == SPACE))
                    ; // discard

                ary_push(parser->scope, type);
                wiki_indent(parser);

                // take base_heading_level into account
                type += base_heading_level;
                if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
                    type = H6_START;

                // rather than repeat all that code for each kind of heading, share it and use a conditional here
                if (type == H6_START)
                    str_append(parser->output, h6_start, sizeof(h6_start) - 1);
                else if (type == H5_START)
                    str_append(parser->output, h5_start, sizeof(h5_start) - 1);
                else if (type == H4_START)
                    str_append(parser->output, h4_start, sizeof(h4_start) - 1);
                else if (type == H3_START)
                    str_append(parser->output, h3_start, sizeof(h3_start) - 1);
                else if (type == H2_START)
                    str_append(parser->output, h2_start, sizeof(h2_start) - 1);
                else if (type == H1_START)
                    str_append(parser->output, h1_start, sizeof(h1_start) - 1);

                // jump to top of the loop to process token we scanned during lookahead
                continue;

            case H6_END:
            case H5_END:
            case H4_END:
            case H3_END:
            case H2_END:
            case H1_END:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, token->start, TOKEN_LEN(token));
                }
                else
                {
                    wiki_rollback_failed_external_link(parser); // if any
                    if ((type == H6_END && !IN(H6_START)) ||
                        (type == H5_END && !IN(H5_START)) ||
                        (type == H4_END && !IN(H4_START)) ||
                        (type == H3_END && !IN(H3_START)) ||
                        (type == H2_END && !IN(H2_START)) ||
                        (type == H1_END && !IN(H1_START)))
                    {
                        // literal output only if not in appropriate scope (we stay silent in that case)
                        wiki_start_para_if_necessary(parser);
                        str_append(parser->output, token->start, TOKEN_LEN(token));
                    }
                }
                break;

            case MAIL:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, token->start, TOKEN_LEN(token));
                }
                else if (IN(EXT_LINK_START))
                    // must be capturing and this must be part of the link text
                    str_append(parser->capture, token->start, TOKEN_LEN(token));
                else
                {
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    token_str->ptr = token->start;
                    token_str->len = TOKEN_LEN(token);
                    wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, Qnil, true);
                }
                break;

            case URI:
                if (IN(NO_WIKI_START))
                {
                    // user can temporarily suppress autolinking by using <nowiki></nowiki>
                    // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
                    token_str->ptr = token->start;
                    token_str->len = TOKEN_LEN(token);
                    wiki_append_sanitized_link_target(token_str, parser->output, false);
                }
                else if (IN(LINK_START))
                {
                    // if the URI were allowed it would have been handled already in LINK_START
                    wiki_rollback_failed_internal_link(parser);
                    token_str->ptr = token->start;
                    token_str->len = TOKEN_LEN(token);
                    wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
                }
                else if (IN(EXT_LINK_START))
                {
                    if (parser->link_target->len == 0)
                    {
                        // this must be our link target: look ahead to make sure we see the space we're expecting to see
                        token_str->ptr = token->start;
                        token_str->len = TOKEN_LEN(token);
                        NEXT_TOKEN();
                        if (token->type == SPACE)
                        {
                            ary_push(parser->scope, SPACE);
                            str_append_str(parser->link_target, token_str);
                            str_clear(parser->link_text);
                            parser->capture     = parser->link_text;
                            token               = NULL; // silently consume space
                        }
                        else
                        {
                            // didn't see the space! this must be an error
                            wiki_pop_from_stack(parser, NULL);
                            wiki_pop_excess_elements(parser);
                            wiki_start_para_if_necessary(parser);
                            str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
                            wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
                            continue;
                        }
                    }
                    else
                    {
                        token_str->ptr = token->start;
                        token_str->len = TOKEN_LEN(token);
                        wiki_append_sanitized_link_target(token_str, parser->link_text, false);
                    }
                }
                else
                {
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    token_str->ptr = token->start;
                    token_str->len = TOKEN_LEN(token);
                    wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
                }
                break;

            case PATH:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, token->start, TOKEN_LEN(token));
                }
                else if (IN(EXT_LINK_START))
                {
                    if (parser->link_target->len == 0)
                    {
                        // this must be our link target: look ahead to make sure we see the space we're expecting to see
                        token_str->ptr = token->start;
                        token_str->len = TOKEN_LEN(token);
                        NEXT_TOKEN();
                        if (token->type == SPACE)
                        {
                            ary_push(parser->scope, PATH);
                            ary_push(parser->scope, SPACE);
                            str_append_str(parser->link_target, token_str);
                            str_clear(parser->link_text);
                            parser->capture     = parser->link_text;
                            token               = NULL; // silently consume space
                        }
                        else
                        {
                            // didn't see the space! this must be an error
                            wiki_pop_from_stack(parser, NULL);
                            wiki_pop_excess_elements(parser);
                            wiki_start_para_if_necessary(parser);
                            str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
                            str_append_str(parser->output, token_str);
                            continue;
                        }
                    }
                    else
                        str_append(parser->link_text, token->start, TOKEN_LEN(token));
                }
                else
                {
                    output = parser->capture ? parser->capture : parser->output;
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    str_append(output, token->start, TOKEN_LEN(token));
                }
                break;

            // internal links (links to other wiki articles) look like this:
            //      [[another article]] (would point at, for example, "/wiki/another_article")
            //      [[the other article|the link text we'll use for it]]
            //      [[the other article | the link text we'll use for it]]
            // MediaWiki has strict requirements about what it will accept as a link target:
            //      all wikitext markup is disallowed:
            //          example [[foo ''bar'' baz]]
            //          renders [[foo <em>bar</em> baz]]        (ie. not a link)
            //          example [[foo <em>bar</em> baz]]
            //          renders [[foo <em>bar</em> baz]]        (ie. not a link)
            //          example [[foo <nowiki>''</nowiki> baz]]
            //          renders [[foo '' baz]]                  (ie. not a link)
            //          example [[foo <bar> baz]]
            //          renders [[foo &lt;bar&gt; baz]]         (ie. not a link)
            //      HTML entities and non-ASCII, however, make it through:
            //          example [[foo &euro;]]
            //          renders <a href="/wiki/Foo_%E2%82%AC">foo &euro;</a>
            //          example [[foo €]]
            //          renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
            // we'll impose similar restrictions here for the link target; allowed tokens will be:
            //      SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
            // everything else will be rejected
            case LINK_START:
                output = parser->capture ? parser->capture : parser->output;
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(output, link_start, sizeof(link_start) - 1);
                }
                else if (IN(EXT_LINK_START))
                    // already in external link scope! (and in fact, must be capturing link_text right now)
                    str_append(output, link_start, sizeof(link_start) - 1);
                else if (IN(LINK_START))
                {
                    // already in internal link scope! this is a syntax error
                    wiki_rollback_failed_internal_link(parser);
                    str_append(parser->output, link_start, sizeof(link_start) - 1);
                }
                else if (IN(SEPARATOR))
                {
                    // scanning internal link text
                }
                else // not in internal link scope yet
                {
                    // will either emit a link, or the rollback of a failed link, so start the para now
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    ary_push(parser->scope, LINK_START);

                    // look ahead and try to gobble up link target
                    while (NEXT_TOKEN(), (type = token->type))
                    {
                        if (type == SPACE               ||
                            type == SPECIAL_URI_CHARS   ||
                            type == PATH                ||
                            type == PRINTABLE           ||
                            type == ALNUM               ||
                            type == DEFAULT             ||
                            type == QUOT                ||
                            type == QUOT_ENTITY         ||
                            type == AMP                 ||
                            type == AMP_ENTITY          ||
                            type == IMG_START           ||
                            type == IMG_END             ||
                            type == LEFT_CURLY          ||
                            type == RIGHT_CURLY)
                        {
                            // accumulate these tokens into link_target
                            if (parser->link_target->len == 0)
                            {
                                str_clear(parser->link_target);
                                parser->capture = parser->link_target;
                            }
                            if (type == QUOT_ENTITY)
                                // don't insert the entity, insert the literal quote
                                str_append(parser->link_target, quote, sizeof(quote) - 1);
                            else if (type == AMP_ENTITY)
                                // don't insert the entity, insert the literal ampersand
                                str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
                            else
                                str_append(parser->link_target, token->start, TOKEN_LEN(token));
                        }
                        else if (type == LINK_END)
                        {
                            if (parser->link_target->len == 0) // bail for inputs like "[[]]"
                                wiki_rollback_failed_internal_link(parser);
                            break; // jump back to top of loop (will handle this in LINK_END case below)
                        }
                        else if (type == SEPARATOR)
                        {
                            if (parser->link_target->len == 0) // bail for inputs like "[[|"
                                wiki_rollback_failed_internal_link(parser);
                            else
                            {
                                ary_push(parser->scope, SEPARATOR);
                                str_clear(parser->link_text);
                                parser->capture     = parser->link_text;
                                token               = NULL;
                            }
                            break;
                        }
                        else // unexpected token (syntax error)
                        {
                            wiki_rollback_failed_internal_link(parser);
                            break; // jump back to top of loop to handle unexpected token
                        }
                    }

                    // jump to top of the loop to process token we scanned during lookahead (if any)
                    continue;
                }
                break;

            case LINK_END:
                output = parser->capture ? parser->capture : parser->output;
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(output, link_end, sizeof(link_end) - 1);
                }
                else if (IN(EXT_LINK_START))
                    // already in external link scope! (and in fact, must be capturing link_text right now)
                    str_append(output, link_end, sizeof(link_end) - 1);
                else if (IN(LINK_START)) // in internal link scope!
                {
                    if (wiki_blank(parser->link_target))
                    {
                        // special case for inputs like "[[    ]]"
                        wiki_rollback_failed_internal_link(parser);
                        str_append(parser->output, link_end, sizeof(link_end) - 1);
                        break;
                    }
                    if (parser->link_text->len == 0 ||
                        wiki_blank(parser->link_text))
                    {
                        // use link target as link text
                        str_clear(parser->link_text);
                        wiki_append_sanitized_link_target(parser->link_target, parser->link_text, true);
                    }
                    else
                        wiki_trim_link_text(parser);

                    // perform "redlink" check before manipulating link_target
                    if (NIL_P(link_proc))
                        j = Qnil;
                    else
                    {
                        j = rb_funcall(link_proc, rb_intern("call"), 1, string_from_str(parser->link_target));
                        if (!NIL_P(j))
                        {
                            VALUE l = j; // can't cast inside StringValue macro
                            j = StringValue(l);
                        }
                    }
                    wiki_encode_link_target(parser);
                    wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
                    parser->capture = NULL;
                    wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, j, Qnil, false);
                    str_clear(parser->link_target);
                    str_clear(parser->link_text);
                }
                else // wasn't in internal link scope
                {
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    str_append(output, link_end, sizeof(link_end) - 1);
                }
                break;

            // external links look like this:
            //      [http://google.com/ the link text]
            //      [/other/page/on/site see this page]
            // strings in square brackets which don't match this syntax get passed through literally; eg:
            //      he was very angery [sic] about the turn of events
            case EXT_LINK_START:
                output = parser->capture ? parser->capture : parser->output;
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
                }
                else if (IN(EXT_LINK_START))
                    // already in external link scope! (and in fact, must be capturing link_text right now)
                    str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
                else if (IN(LINK_START))
                {
                    // already in internal link scope!
                    if (parser->link_target->len == 0 || !IN(SPACE))
                        str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
                    else // link target has already been scanned
                        str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
                }
                else // not in external link scope yet
                {
                    // will either emit a link, or the rollback of a failed link, so start the para now
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);

                    // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
                    NEXT_TOKEN();
                    if (token->type == URI || token->type == PATH)
                        ary_push(parser->scope, EXT_LINK_START);    // so far so good, jump back to the top of the loop
                    else
                        // only get here if there was a syntax error (missing URI)
                        str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
                    continue; // jump back to top of loop to handle token (either URI or whatever it is)
                }
                break;

            case EXT_LINK_END:
                output = parser->capture ? parser->capture : parser->output;
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
                }
                else if (IN(EXT_LINK_START))
                {
                    if (parser->link_text->len == 0)
                        // syntax error: external link with no link text
                        wiki_rollback_failed_external_link(parser);
                    else
                    {
                        // success!
                        j = IN(PATH) ? Qnil : parser->external_link_class;
                        k = IN(PATH) ? Qnil : parser->external_link_rel;
                        wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
                        parser->capture = NULL;
                        wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, k, false);
                    }
                    str_clear(parser->link_target);
                    str_clear(parser->link_text);
                }
                else
                {
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);
                    str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
                }
                break;

            case SEPARATOR:
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                str_append(output, separator, sizeof(separator) - 1);
                break;

            case SPACE:
                output = parser->capture ? parser->capture : parser->output;
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(output, token->start, TOKEN_LEN(token));
                }
                else
                {
                    // peek ahead to see next token
                    char    *token_ptr  = token->start;
                    long    token_len   = TOKEN_LEN(token);
                    NEXT_TOKEN();
                    type = token->type;
                    if ((type == H6_END && IN(H6_START)) ||
                        (type == H5_END && IN(H5_START)) ||
                        (type == H4_END && IN(H4_START)) ||
                        (type == H3_END && IN(H3_START)) ||
                        (type == H2_END && IN(H2_START)) ||
                        (type == H1_END && IN(H1_START)))
                    {
                        // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
                    }
                    else
                    {
                        // emit the space
                        wiki_pop_excess_elements(parser);
                        wiki_start_para_if_necessary(parser);
                        str_append(output, token_ptr, token_len);
                    }

                    // jump to top of the loop to process token we scanned during lookahead
                    continue;
                }
                break;

            case QUOT_ENTITY:
            case AMP_ENTITY:
            case NAMED_ENTITY:
            case DECIMAL_ENTITY:
                // pass these through unaltered as they are case sensitive
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                str_append(output, token->start, TOKEN_LEN(token));
                break;

            case HEX_ENTITY:
                // normalize hex entities (downcase them)
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                str_append(output, token->start, TOKEN_LEN(token));
                wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
                break;

            case QUOT:
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                str_append(output, quot_entity, sizeof(quot_entity) - 1);
                break;

            case AMP:
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                str_append(output, amp_entity, sizeof(amp_entity) - 1);
                break;

            case LESS:
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                str_append(output, lt_entity, sizeof(lt_entity) - 1);
                break;

            case GREATER:
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                str_append(output, gt_entity, sizeof(gt_entity) - 1);
                break;

            case IMG_START:
                if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
                {
                    wiki_emit_pending_crlf_if_necessary(parser);
                    str_append(parser->output, token->start, TOKEN_LEN(token));
                }
                else if (parser->capture)
                    str_append(parser->capture, token->start, TOKEN_LEN(token));
                else
                {
                    // not currently capturing: will be emitting something on success or failure, so get ready
                    wiki_pop_excess_elements(parser);
                    wiki_start_para_if_necessary(parser);

                    // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
                    // will cheat here and abuse the link_target capture buffer to accumulate text
                    while (NEXT_TOKEN(), (type = token->type))
                    {
                        if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
                            str_append(parser->link_target, token->start, TOKEN_LEN(token));
                        else if (type == IMG_END && parser->link_target->len > 0)
                        {
                            // success
                            wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
                            token = NULL;
                            break;
                        }
                        else // unexpected token or zero-length target (syntax error)
                        {
                            // rollback
                            str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
                            if (parser->link_target->len > 0)
                                str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
                            break;
                        }
                    }

                    // jump to top of the loop to process token we scanned during lookahead
                    str_clear(parser->link_target);
                    continue;
                }
                break;

            case CRLF:
                i = parser->pending_crlf;
                parser->pending_crlf = false;
                wiki_rollback_failed_link(parser); // if any
                if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
                {
                    ary_clear(parser->line_buffer);
                    str_append_str(parser->output, parser->line_ending);
                    break;
                }
                else if (IN(PRE))
                {
                    // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
                    if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
                        // don't emit in this case
                        wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
                    else
                    {
                        if (ary_entry(parser->line_buffer, -2) == PRE)
                        {
                             // only thing on line is the PRE: emit pending line ending (if we had one)
                             if (i)
                                 str_append_str(parser->output, parser->line_ending);
                        }

                        // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
                        ary_clear(parser->line);
                        ary_clear(parser->line_buffer);

                        // peek ahead to see if this is definitely the end of the PRE block
                        NEXT_TOKEN();
                        type = token->type;
                        if (type != BLOCKQUOTE && type != PRE)
                            // this is definitely the end of the block, so don't emit
                            wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
                        else
                            // potentially will emit
                            parser->pending_crlf = true;

                        continue; // jump back to top of loop to handle token grabbed via lookahead
                    }
                }
                else
                {
                    parser->pending_crlf = true;

                    // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
                    // as a side effect, this handles any open span-level elements and unclosed blocks
                    // (with special handling for P blocks and LI elements)
                    i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
                    for (j = parser->scope->count; j > i; j--)
                    {
                        if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
                        {
                            parser->pending_crlf = false;
                            break;
                        }

                        // special handling on last iteration through the loop if the top item on the scope is a P block
                        if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
                        {
                            // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
                            // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
                            // because in those blocks BLOCKQUOTE tokens have no special meaning)
                            if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
                                (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
                                // paragraph break
                                parser->pending_crlf = false;
                            else
                                // not a paragraph break!
                                continue;
                        }
                        wiki_pop_from_stack(parser, NULL);
                    }
                }

                // delete the entire contents of the line scope stack and buffer
                ary_clear(parser->line);
                ary_clear(parser->line_buffer);
                break;

            case SPECIAL_URI_CHARS:
            case PRINTABLE:
            case ALNUM:
            case IMG_END:
            case LEFT_CURLY:
            case RIGHT_CURLY:
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                str_append(output, token->start, TOKEN_LEN(token));
                break;

            case DEFAULT:
                output = parser->capture ? parser->capture : parser->output;
                wiki_pop_excess_elements(parser);
                wiki_start_para_if_necessary(parser);
                wiki_append_entity_from_utf32_char(output, token->code_point);
                break;

            case END_OF_FILE:
                // special case for input like " foo\n " (see pre_spec.rb)
                if (IN(PRE) &&
                    ary_entry(parser->line_buffer, -2) == PRE &&
                    parser->pending_crlf)
                    str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);

                // close any open scopes on hitting EOF
                wiki_rollback_failed_link(parser); // if any
                wiki_pop_all_from_stack(parser);
                goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)

            default:
                break;
        }

        // reset current token; forcing lexer to return another token at the top of the loop
        token = NULL;
    } while (1);
return_output:
    // nasty hack to avoid re-allocating our return value
    str_append(parser->output, null_str, 1); // null-terminate
    len = parser->output->len - 1; // don't count null termination

    VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
    free(RSTRING_PTR(out));
    RSTRING(out)->as.heap.aux.capa = len;
    RSTRING(out)->as.heap.ptr = parser->output->ptr;
    RSTRING(out)->as.heap.len = len;
    parser->output->ptr = NULL; // don't double-free
    return out;
}

#tokenize(string) ⇒ Object

for testing and debugging only



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'ext/wikitext/parser.c', line 188

VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
{
    if (NIL_P(string))
        return Qnil;
    string = StringValue(string);
    VALUE tokens = rb_ary_new();
    char *p = RSTRING_PTR(string);
    long len = RSTRING_LEN(string);
    char *pe = p + len;
    token_t token;
    next_token(&token, NULL, p, pe);
    rb_ary_push(tokens, wiki_token(&token));
    while (token.type != END_OF_FILE)
    {
        next_token(&token, &token, NULL, pe);
        rb_ary_push(tokens, wiki_token(&token));
    }
    return tokens;
}