1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301
|
/*
* Copyright (c) 2008, Natacha Porté
* Copyright (c) 2011, Vicent MartÃ
* Copyright (c) 2014, Xavier Mendez, Devin Torres and the Hoedown authors
* Copyright (c) Kristaps Dzonsons <kristaps@bsd.lv>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "config.h"
#if HAVE_SYS_QUEUE
# include <sys/queue.h>
#endif
#include <assert.h>
#include <ctype.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lowdown.h"
#include "extern.h"
/*
* Make sure these are larger than enum hlist_fl.
*/
#define HLIST_LI_END (1 << 7) /* End of list item. */
/*
* Mask of all list item types.
*/
#define HLIST_FL_MASK (HLIST_FL_DEF | \
HLIST_FL_ORDERED | \
HLIST_FL_UNORDERED)
/*
* Reference to a link.
*/
struct link_ref {
struct lowdown_buf *name; /* id of link (or NULL) */
struct lowdown_buf *link; /* link address */
struct lowdown_buf *title; /* optional title */
struct lowdown_buf *attrs; /* optional attributes */
TAILQ_ENTRY(link_ref) entries;
};
TAILQ_HEAD(link_refq, link_ref);
/*
* Reference to a footnote. This keeps track of all footnotes
* definitions and whether there's both a definition and reference.
*/
struct foot_ref {
size_t num; /* if used, the order */
struct lowdown_node *ref; /* if used, the reference */
struct lowdown_buf name; /* identifier */
struct lowdown_buf contents; /* definition */
TAILQ_ENTRY(foot_ref) entries;
};
TAILQ_HEAD(foot_refq, foot_ref);
struct lowdown_doc {
struct link_refq refq; /* all internal references */
struct foot_refq footq; /* all footnotes */
size_t foots; /* # of used footnotes */
int active_char[256]; /* jump table */
unsigned int ext_flags; /* options */
int in_link_body; /* parsing link body */
int in_footnote; /* prevent nested */
size_t nodes; /* number of nodes */
struct lowdown_node *current; /* current node */
struct lowdown_metaq *metaq; /* raw metadata key/values */
size_t depth; /* current parse tree depth */
size_t maxdepth; /* max parse tree depth */
char **meta; /* primer metadata */
size_t metasz; /* size of meta */
char **metaovr; /* override metadata */
size_t metaovrsz; /* size of metaovr */
};
/*
* Function pointer to render active chars, where "data" is the pointer
* of the beginning of the span and "offset" is the number of valid
* chars before data.
* Returns the number of chars taken care of, or <0 on failure.
*/
typedef ssize_t (*char_trigger)(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_emphasis(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_linebreak(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_codespan(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_escape(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_entity(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_langle_tag(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_autolink_url(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_autolink_email(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_autolink_www(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_link(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_image(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_superscript(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_math(struct lowdown_doc *, char *, size_t, size_t);
static ssize_t char_subscript(struct lowdown_doc *, char *, size_t, size_t);
enum markdown_char_t {
MD_CHAR_NONE = 0,
MD_CHAR_EMPHASIS,
MD_CHAR_CODESPAN,
MD_CHAR_LINEBREAK,
MD_CHAR_LINK,
MD_CHAR_IMAGE,
MD_CHAR_LANGLE,
MD_CHAR_ESCAPE,
MD_CHAR_ENTITY,
MD_CHAR_AUTOLINK_URL,
MD_CHAR_AUTOLINK_EMAIL,
MD_CHAR_AUTOLINK_WWW,
MD_CHAR_SUPERSCRIPT,
MD_CHAR_SUBSCRIPT,
MD_CHAR_QUOTE,
MD_CHAR_MATH
};
static const char_trigger markdown_char_ptrs[] = {
NULL,
&char_emphasis,
&char_codespan,
&char_linebreak,
&char_link,
&char_image,
&char_langle_tag,
&char_escape,
&char_entity,
&char_autolink_url,
&char_autolink_email,
&char_autolink_www,
&char_superscript,
&char_subscript,
NULL,
&char_math
};
static int
parse_block(struct lowdown_doc *, char *, size_t);
static ssize_t
parse_listitem(struct lowdown_buf *, struct lowdown_doc *,
char *, size_t, enum hlist_fl *, size_t);
/*
* Add a node to the parse stack or retrieve a current node if
* requesting multiple similar LOWDOWN_NORMAL_TEXT in sequence. Returns
* the node, initialised to the given type, after adjusting the parse
* position. Returns NULL on memory allocation failure.
*/
static struct lowdown_node *
pushnode_full(struct lowdown_doc *doc, enum lowdown_rndrt t, int fl)
{
struct lowdown_node *n;
/*
* Special case: if we're pushing a NORMAL_TEXT node, see if one
* already exists with the same flags and return that. This
* means that each push for text nodes should be careful to use
* hbuf_push() instead of hbuf_create() when adding text
* content.
*/
if (t == LOWDOWN_NORMAL_TEXT && doc->current != NULL) {
n = TAILQ_LAST(&doc->current->children, lowdown_nodeq);
if (n != NULL &&
n->type == LOWDOWN_NORMAL_TEXT &&
n->rndr_normal_text.flags == fl) {
doc->depth++;
doc->current = n;
return n;
}
}
/* New node. */
if ((doc->depth++ > doc->maxdepth) && doc->maxdepth)
return NULL;
if ((n = calloc(1, sizeof(struct lowdown_node))) == NULL)
return NULL;
n->id = doc->nodes++;
n->type = t;
n->parent = doc->current;
TAILQ_INIT(&n->children);
if (n->parent != NULL)
TAILQ_INSERT_TAIL(&n->parent->children, n, entries);
doc->current = n;
return n;
}
/*
* Push a new node or, if LOWDOWN_NORMAL_TEXT, retrieve the existing one
* if the flags exactly match.
*/
static struct lowdown_node *
pushnode(struct lowdown_doc *doc, enum lowdown_rndrt t)
{
return pushnode_full(doc, t, 0);
}
/*
* Push a new LOWDOWN_NORMAL_TEXT or retrieve the existing one if the
* flags exactly match.
*/
static struct lowdown_node *
pushtext(struct lowdown_doc *doc, int flags)
{
return pushnode_full(doc, LOWDOWN_NORMAL_TEXT, flags);
}
/*
* Sets a buffer with the contents of "data" of size "datasz". The
* buffer must be empty. Return FALSE on failure, TRUE on success.
*/
static int
hbuf_create(struct lowdown_buf *buf, const char *data, size_t datasz)
{
assert(buf->size == 0);
assert(buf->data == NULL);
memset(buf, 0, sizeof(struct lowdown_buf));
if (datasz) {
if ((buf->data = malloc(datasz)) == NULL)
return 0;
buf->unit = 1;
buf->size = buf->maxsize = datasz;
memcpy(buf->data, data, datasz);
}
return 1;
}
/*
* See hbuf_create().
*/
static int
hbuf_createb(struct lowdown_buf *buf, const struct lowdown_buf *nbuf)
{
return hbuf_create(buf, nbuf->data, nbuf->size);
}
/*
* Pushes data into the buffer, which is initialised if empty. Return
* FALSE on failure, TRUE on success.
*/
static int
hbuf_push(struct lowdown_buf *buf, const char *data, size_t datasz)
{
if (buf->size == 0 || buf->data == NULL)
return hbuf_create(buf, data, datasz);
return hbuf_put(buf, data, datasz);
}
/*
* See pushnode().
* Pops the current node on the stack, replacing it with the parent.
*/
static void
popnode(struct lowdown_doc *doc, const struct lowdown_node *n)
{
assert(doc->depth > 0);
doc->depth--;
assert(doc->current == n);
doc->current = doc->current->parent;
}
/*
* Remove the backslash from a text sequence.
* Return zero on failure (memory), non-zero on success.
*/
static int
unscape_text(struct lowdown_buf *ob, struct lowdown_buf *src)
{
size_t i, org;
for (i = 0; i < src->size; i += 2) {
org = i;
while (i < src->size && src->data[i] != '\\')
i++;
if (i > org &&
!hbuf_put(ob, src->data + org, i - org))
return 0;
if (i + 1 >= src->size)
break;
if (!hbuf_putc(ob, src->data[i + 1]))
return 0;
}
return 1;
}
static struct link_ref *
find_link_ref(struct link_refq *q, char *name, size_t length)
{
struct link_ref *ref;
TAILQ_FOREACH(ref, q, entries)
if ((ref->name == NULL && length == 0) ||
(ref->name != NULL &&
ref->name->size == length &&
memcmp(ref->name->data, name, length) == 0))
return ref;
return NULL;
}
static void
free_link_refs(struct link_refq *q)
{
struct link_ref *r;
while ((r = TAILQ_FIRST(q)) != NULL) {
TAILQ_REMOVE(q, r, entries);
hbuf_free(r->link);
hbuf_free(r->name);
hbuf_free(r->title);
hbuf_free(r->attrs);
free(r);
}
}
static void
free_foot_refq(struct foot_refq *q)
{
struct foot_ref *ref;
while ((ref = TAILQ_FIRST(q)) != NULL) {
TAILQ_REMOVE(q, ref, entries);
hbuf_free(&ref->contents);
hbuf_free(&ref->name);
free(ref);
}
}
/*
* Check whether a char is a Markdown spacing char.
* Right now we only consider spaces the actual space and a newline:
* tabs and carriage returns are filtered out during the preprocessing
* phase.
* If we wanted to actually be UTF-8 compliant, we should instead
* extract an Unicode codepoint from this character and check for space
* properties.
*/
static int
xisspace(int c)
{
return c == ' ' || c == '\n';
}
/*
* Returns the number of leading spaces from data starting from offset
* to size.
* If maxlen is greater than zero, only at most maxlen number of leading
* spaces will be counted.
* Otherwise, all leading spaces will be counted.
*/
static size_t
countspaces(const char *data, size_t offset, size_t size, size_t maxlen)
{
size_t i;
for (i = offset; i < size; i++) {
if (maxlen > 0 && i - offset == maxlen)
break;
if (data[i] != ' ')
break;
}
return i;
}
/*
* Replace all spacing characters in data with spaces.
* As a special case, this collapses a newline with the previous space,
* if possible.
* Return zero on failure (memory), non-zero on success.
*/
static int
replace_spacing(struct lowdown_buf *ob, const char *data, size_t size)
{
size_t i, mark;
if (!hbuf_grow(ob, size))
return 0;
for (i = 0; ; i++) {
mark = i;
while (i < size && data[i] != '\n')
i++;
if (!hbuf_put(ob, data + mark, i - mark))
return 0;
if (i >= size)
break;
if (!(i > 0 && data[i - 1] == ' '))
if (!hbuf_putc(ob, ' '))
return 0;
}
return 1;
}
/*
* Looks for the address part of a mail autolink and '>'.
* This is less strict than the original markdown e-mail address
* matching.
*/
static size_t
is_mail_autolink(const char *data, size_t size)
{
size_t i, nb = 0;
/* Assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@'. */
for (i = 0; i < size; ++i) {
if (isalnum((unsigned char)data[i]))
continue;
switch (data[i]) {
case '@':
nb++;
case '-':
case '.':
case '_':
break;
case '>':
return (nb == 1) ? i + 1 : 0;
default:
return 0;
}
}
return 0;
}
/*
* Returns the length of the given tag, or 0 is it's not valid.
*/
static size_t
tag_length(const char *data, size_t size, enum halink_type *ltype)
{
size_t i, j;
/* A valid tag can't be shorter than 3 chars. */
if (size < 3)
return 0;
if (data[0] != '<')
return 0;
/* HTML comment, laxist form. */
if (size > 5 && data[1] == '!' &&
data[2] == '-' && data[3] == '-') {
i = 5;
while (i < size && !(data[i - 2] == '-' &&
data[i - 1] == '-' && data[i] == '>'))
i++;
i++;
if (i <= size)
return i;
}
/*
* Begins with a '<' optionally followed by '/', followed by letter or
* number.
*/
i = (data[1] == '/') ? 2 : 1;
if (!isalnum((unsigned char)data[i]))
return 0;
/* Scheme test. */
*ltype = HALINK_NONE;
/* Try to find the beginning of an URI. */
while (i < size && (isalnum((unsigned char)data[i]) ||
data[i] == '.' || data[i] == '+' || data[i] == '-'))
i++;
if (i > 1 && data[i] == '@')
if ((j = is_mail_autolink(data + i, size - i)) != 0) {
*ltype = HALINK_EMAIL;
return i + j;
}
if (i > 2 && data[i] == ':') {
*ltype = HALINK_NORMAL;
i++;
}
/* Completing autolink test: no spacing or ' or ". */
if (i >= size)
*ltype = HALINK_NONE;
else if (*ltype) {
j = i;
while (i < size) {
if (data[i] == '\\')
i += 2;
else if (data[i] == '>' || data[i] == '\'' ||
data[i] == '"' || data[i] == ' ' ||
data[i] == '\n')
break;
else
i++;
}
if (i >= size)
return 0;
if (i > j && data[i] == '>')
return i + 1;
/* One of the forbidden chars has been found. */
*ltype = HALINK_NONE;
}
/* Looking for something looking like a tag end. */
while (i < size && data[i] != '>')
i++;
if (i >= size)
return 0;
return i + 1;
}
/*
* Parses inline markdown elements.
* This function is important because it handles raw input that we pass
* directly to the output formatter ("normal_text").
* Return zero on failure, non-zero on success.
*/
static int
parse_inline(struct lowdown_doc *doc, char *data, size_t size)
{
size_t i = 0, end = 0, consumed = 0;
ssize_t rc;
struct lowdown_buf work;
const int *active_char = doc->active_char;
struct lowdown_node *n;
memset(&work, 0, sizeof(struct lowdown_buf));
while (i < size) {
/* Copying non-macro chars into the output. */
while (end < size &&
active_char[(unsigned char)data[end]] == 0)
end++;
/* Only allocate if non-empty... */
if (end - i > 0) {
n = pushnode(doc, LOWDOWN_NORMAL_TEXT);
if (n == NULL)
return 0;
if (!hbuf_push(&n->rndr_normal_text.text,
data + i, end - i))
return 0;
popnode(doc, n);
}
/* End of file? */
if (end >= size)
break;
i = end;
rc = markdown_char_ptrs[
active_char[(unsigned char)data[end]]]
(doc, data + i, i - consumed, size - i);
if (rc < 0)
return 0;
end = rc;
/* Check if no action from the callback. */
if (end == 0) {
end = i + 1;
continue;
}
i += end;
end = consumed = i;
}
return 1;
}
/*
* Returns whether special char at data[loc] is escaped by '\\'.
*/
static int
is_escaped(const char *data, size_t loc)
{
size_t i = loc;
while (i >= 1 && data[i - 1] == '\\')
i--;
/* Odd numbers of backslashes escapes data[loc]. */
return (loc - i) % 2;
}
/*
* Test if the buffer "data" of size "sz" might be a pandoc metadata
* block. This consists of at most three lines starting with percent
* marks. It can be more than three lines if lines start with
* whitespace (continuations). Returns zero if not a metadata block,
* otherwise the block length if it may be.
*/
static size_t
is_metadata_block_pandoc(const char *data, size_t sz)
{
size_t i = 0, j;
if (sz == 0 || data[0] != '%')
return 0;
for (i = j = 0; i < sz && j < 3; j++, i++) {
if (data[i] != '%')
break;
for ( ; i < sz; i++)
if (data[i] == '\n' &&
(i + 1 >= sz || data[i + 1] != ' '))
break;
}
/* Run past trailing newlines. */
while (i < sz && data[i] == '\n')
i++;
return i;
}
/*
* Test if the buffer "data" of size "sz" might be a MMD metadata block.
* This only sees if the first line starts with an alnum and contains a
* colon, and that the block ends in two newlines. Alternatively, the
* first line is "---" and last is "---" or "....", which is the YAML
* syntax ("is_yaml" will be set).
* Returns zero if not a metadata block, otherwise the block length if
* it may be.
*/
static size_t
is_metadata_block_mmd(const char *data, size_t sz, int *is_yaml)
{
size_t i = 0;
const char *cp;
if (sz == 0)
return 0;
if (sz > 4 && strncmp(data, "---\n", 4) == 0) {
*is_yaml = 1;
i += 4;
}
if (!isalnum((unsigned char)data[i]))
return 0;
for ( ; i < sz; i++)
if (data[i] == '\n' || data[i] == ':')
break;
if (i == sz || data[i] != ':')
return 0;
/*
* Look for trailing paragraph (if not YAML) or the YAML markers
* otherwise.
*/
if (*is_yaml && sz - i > 5) {
cp = memmem(&data[i], sz - i, "\n---\n", 5);
if (cp == NULL)
cp = memmem(&data[i], sz - i, "\n...\n", 5);
if (cp != NULL)
return (ptrdiff_t)(cp - data) + 5;
} else if (!*is_yaml && sz - i > 2) {
cp = memmem(&data[i], sz - i, "\n\n", 2);
if (cp != NULL)
return (ptrdiff_t)(cp - data) + 2;
}
return 0;
}
/*
* Looks for the next emph char, skipping other constructs.
*/
static size_t
find_emph_char(const char *data, size_t size, char c)
{
size_t i = 0, span_nb, bt, tmp_i;
char cc;
while (i < size) {
while (i < size && data[i] != c &&
data[i] != '[' && data[i] != '`')
i++;
if (i == size)
return 0;
/* Not counting escaped chars. */
if (is_escaped(data, i)) {
i++;
continue;
}
if (data[i] == c)
return i;
/* Skipping a codespan. */
if (data[i] == '`') {
span_nb = 0;
tmp_i = 0;
/* Counting the number of opening backticks. */
while (i < size && data[i] == '`') {
i++;
span_nb++;
}
if (i >= size)
return 0;
/* Finding the matching closing sequence. */
bt = 0;
while (i < size && bt < span_nb) {
if (!tmp_i && data[i] == c)
tmp_i = i;
if (data[i] == '`')
bt++;
else
bt = 0;
i++;
}
/*
* Not a well-formed codespan; use found
* matching emph char.
*/
if (bt < span_nb && i >= size)
return tmp_i;
} else if (data[i] == '[') {
tmp_i = 0;
/* Skipping a link. */
/*
* XXX: it's trivially possible to allow for
* nested links by maintaining a stack depth
* here on the opening and closing bracket.
* However, no other Markdowns appear to support
* this syntax, so don't do so.
*/
i++;
while (i < size && data[i] != ']') {
if (!tmp_i && data[i] == c)
tmp_i = i;
i++;
}
i++;
while (i < size && xisspace(data[i]))
i++;
if (i >= size)
return tmp_i;
switch (data[i]) {
case '[':
cc = ']';
break;
case '(':
cc = ')';
break;
default:
if (tmp_i)
return tmp_i;
else
continue;
}
i++;
while (i < size && data[i] != cc) {
if (!tmp_i && data[i] == c)
tmp_i = i;
i++;
}
if (i >= size)
return tmp_i;
i++;
}
}
return 0;
}
/*
* Parsing single emphase.
* Closed by a symbol not preceded by spacing and not followed by
* symbol.
* Return 0 if not an emphasis, <0 on failure, >0 on success.
*/
static ssize_t
parse_emph1(struct lowdown_doc *doc, char *data, size_t size, char c)
{
size_t i = 0, len;
struct lowdown_node *n;
/* Skipping one symbol if coming from emph3. */
if (size > 1 && data[0] == c && data[1] == c)
i = 1;
while (i < size) {
len = find_emph_char(data + i, size - i, c);
if (!len)
return 0;
i += len;
if (i >= size)
return 0;
if (data[i] == c && !xisspace(data[i - 1])) {
if ((doc->ext_flags & LOWDOWN_NOINTEM) &&
i + 1 < size &&
isalnum((unsigned char)data[i + 1]))
continue;
n = pushnode(doc, LOWDOWN_EMPHASIS);
if (n == NULL)
return -1;
if (!parse_inline(doc, data, i))
return -1;
popnode(doc, n);
return i + 1;
}
}
return 0;
}
/*
* Parsing single emphase.
* Return 0 if not an emphasis, <0 on failure, >0 on success.
*/
static ssize_t
parse_emph2(struct lowdown_doc *doc, char *data, size_t size, char c)
{
size_t i = 0, len;
struct lowdown_node *n;
enum lowdown_rndrt t;
while (i < size) {
len = find_emph_char(data + i, size - i, c);
if (len == 0)
return 0;
i += len;
if (i + 1 < size && data[i] == c &&
data[i + 1] == c && i &&
!xisspace(data[i - 1])) {
if (c == '~')
t = LOWDOWN_STRIKETHROUGH;
else if (c == '=')
t = LOWDOWN_HIGHLIGHT;
else
t = LOWDOWN_DOUBLE_EMPHASIS;
if ((n = pushnode(doc, t)) == NULL)
return -1;
if (!parse_inline(doc, data, i))
return -1;
popnode(doc, n);
return i + 2;
}
i++;
}
return 0;
}
/*
* Parsing single emphase
* Finds the first closing tag, and delegates to the other emph.
* Return 0 if not an emphasis, <0 on failure, >0 on success.
*/
static size_t
parse_emph3(struct lowdown_doc *doc, char *data, size_t size, char c)
{
size_t i = 0, len;
ssize_t rc;
struct lowdown_node *n;
while (i < size) {
len = find_emph_char(data + i, size - i, c);
if (len == 0)
return 0;
i += len;
/* Skip spacing preceded symbols. */
if (data[i] != c || xisspace(data[i - 1]))
continue;
/* Case for triple, double, and single asterisk. */
if (i + 2 < size && data[i + 1] == c &&
data[i + 2] == c) {
n = pushnode(doc, LOWDOWN_TRIPLE_EMPHASIS);
if (n == NULL)
return -1;
if (!parse_inline(doc, data, i))
return -1;
popnode(doc, n);
return i + 3;
} else if (i + 1 < size && data[i + 1] == c) {
rc = parse_emph1(doc, data - 2, size + 2, c);
if (rc < 0)
return -1;
assert(rc == 0 || rc >= 2);
return rc == 0 ? 0 : rc - 2;
} else {
rc = parse_emph2(doc, data - 1, size + 1, c);
if (rc < 0)
return -1;
return rc == 0 ? 0 : rc - 1;
}
}
return 0;
}
/*
* Parses a math span until the given ending delimiter.
* Return 0 if not math, <0 on failure, >0 on success.
*/
static ssize_t
parse_math(struct lowdown_doc *doc, char *data, size_t offset,
size_t size, const char *end, size_t delimsz, int blockmode)
{
size_t i;
struct lowdown_node *n;
/*
* Find ending delimiter.
* All text within the equation is opaque, so we don't need to
* care about embedded macros.
*/
for (i = delimsz; ; i++) {
while (i < size && data[i] != end[0])
i++;
if (i >= size)
return 0;
if (!is_escaped(data, i) && !(i + delimsz > size) &&
memcmp(data + i, end, delimsz) == 0)
break;
}
i += delimsz;
if (!(doc->ext_flags & LOWDOWN_MATH)) {
n = pushnode(doc, LOWDOWN_NORMAL_TEXT);
if (n == NULL)
return -1;
if (!hbuf_push(&n->rndr_normal_text.text, data, i))
return -1;
popnode(doc, n);
return i;
}
n = pushnode(doc, LOWDOWN_MATH_BLOCK);
if (n == NULL)
return -1;
if (!hbuf_create(&n->rndr_math.text,
data + delimsz, i - 2 * delimsz))
return -1;
n->rndr_math.blockmode = blockmode;
popnode(doc, n);
return i;
}
/*
* Single and double emphasis parsing.
*/
static ssize_t
char_emphasis(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
char c = data[0];
ssize_t ret;
if (doc->ext_flags & LOWDOWN_NOINTEM)
if (offset > 0 && !xisspace(data[-1]) &&
data[-1] != '>' && data[-1] != '(')
return 0;
/*
* Spacing cannot follow an opening emphasis: strikethrough and
* highlight only takes '~~'.
*/
if (size > 2 && data[1] != c) {
if (c == '~' || c == '=' || xisspace(data[1]) ||
(ret = parse_emph1
(doc, data + 1, size - 1, c)) == 0)
return 0;
return ret > 0 ? ret + 1 : ret;
}
if (size > 3 && data[1] == c && data[2] != c) {
if (xisspace(data[2]) ||
(ret = parse_emph2
(doc, data + 2, size - 2, c)) == 0)
return 0;
return ret > 0 ? ret + 2 : ret;
}
if (size > 4 && data[1] == c && data[2] == c && data[3] != c) {
if (c == '~' || c == '=' || xisspace(data[3]) ||
(ret = parse_emph3
(doc, data + 3, size - 3, c)) == 0)
return 0;
return ret > 0 ? ret + 3 : ret;
}
return 0;
}
/*
* '\n' preceded by two spaces (assuming linebreak != 0)
*/
static ssize_t
char_linebreak(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
struct lowdown_node *n;
size_t w;
struct lowdown_buf *b;
if (offset < 2 || data[-1] != ' ' || data[-2] != ' ')
return 0;
/* Removing the last space from nodes. */
assert(doc->current != NULL);
n = TAILQ_LAST(&doc->current->children, lowdown_nodeq);
assert(n != NULL && LOWDOWN_NORMAL_TEXT == n->type);
b = &n->rndr_normal_text.text;
while (b->size && b->data[b->size - 1] == ' ')
b->size--;
/*
* Swallow leading white-space of next line.
* XXX: is this just CommonMark?
*/
for (w = 1; w < size; w++)
if (data[w] != ' ')
break;
if ((n = pushnode(doc, LOWDOWN_LINEBREAK)) == NULL)
return -1;
popnode(doc, n);
return w;
}
/*
* '`' parsing a code span (assuming codespan != 0)
*/
static ssize_t
char_codespan(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
struct lowdown_buf work;
struct lowdown_node *n;
size_t end, nb = 0, i, f_begin, f_end;
memset(&work, 0, sizeof(struct lowdown_buf));
/* Counting the number of backticks in the delimiter. */
while (nb < size && data[nb] == '`')
nb++;
/* Finding the next delimiter. */
i = 0;
for (end = nb; end < size && i < nb; end++) {
if (data[end] == '`')
i++;
else
i = 0;
}
if (i < nb && end >= size)
return 0; /* no matching delimiter */
/* Trimming outside spaces. */
f_begin = countspaces(data, nb, end, 0);
f_end = end - nb;
while (f_end > nb && data[f_end-1] == ' ')
f_end--;
/* Real code span. */
if ((n = pushnode(doc, LOWDOWN_CODESPAN)) == NULL)
return -1;
if (f_begin < f_end) {
work.data = data + f_begin;
work.size = f_end - f_begin;
if (!hbuf_createb(&n->rndr_codespan.text, &work))
return -1;
}
popnode(doc, n);
return end;
}
/*
* '\\' backslash escaped text.
* Escaped text isn't handled by smart typography, although it must be
* escaped for output. Mark it as HTEXT_ESCAPED to make sure that we
* don't use smart typography on the node.
*/
static ssize_t
char_escape(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
static const char *escape_chars =
"\\`*_{}[]()#+-.!:|&<>^~=\"$";
struct lowdown_buf work;
size_t w;
ssize_t ret;
const char *end;
struct lowdown_node *n;
memset(&work, 0, sizeof(struct lowdown_buf));
if (size > 1) {
if (data[1] == '\\' &&
(doc->ext_flags & LOWDOWN_MATH) &&
size > 2 &&
(data[2] == '(' || data[2] == '[')) {
end = (data[2] == '[') ? "\\\\]" : "\\\\)";
ret = parse_math(doc, data, offset,
size, end, 3, data[2] == '[');
if (ret != 0)
return ret;
}
/* Swallow leading white-space of next line. */
if (LOWDOWN_COMMONMARK & doc->ext_flags &&
data[1] == '\n') {
for (w = 2; w < size; w++)
if (data[w] != ' ')
break;
n = pushnode(doc, LOWDOWN_LINEBREAK);
if (n == NULL)
return -1;
popnode(doc, n);
return w;
}
if (strchr(escape_chars, data[1]) == NULL)
return 0;
if ((n = pushtext(doc, HTEXT_ESCAPED)) == NULL)
return -1;
n->rndr_normal_text.flags = HTEXT_ESCAPED;
if (!hbuf_push(&n->rndr_normal_text.text, data + 1, 1))
return -1;
popnode(doc, n);
} else if (size == 1) {
if ((n = pushtext(doc, HTEXT_ESCAPED)) == NULL)
return -1;
n->rndr_normal_text.flags = HTEXT_ESCAPED;
if (!hbuf_push(&n->rndr_normal_text.text, data, 1))
return -1;
popnode(doc, n);
}
return 2;
}
/*
* '&': parse entity, or escape if it's not an entity.
* Valid entities are assumed to be anything matching &#?[A-Za-z0-9]+;
*/
static ssize_t
char_entity(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
size_t end = 1;
struct lowdown_node *n;
if (end < size && data[end] == '#')
end++;
while (end < size && isalnum((unsigned char)data[end]))
end++;
if (end < size && data[end] == ';')
end++; /* real entity */
else
return 0; /* lone '&' */
if ((n = pushnode(doc, LOWDOWN_ENTITY)) == NULL)
return -1;
if (!hbuf_create(&n->rndr_entity.text, data, end))
return -1;
popnode(doc, n);
return end;
}
/*
* '<': parse link when tags or autolinks are allowed.
*/
static ssize_t
char_langle_tag(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
struct lowdown_buf work;
struct lowdown_buf *u_link = NULL;
enum halink_type altype = HALINK_NONE;
size_t end = tag_length(data, size, &altype);
int ret = 0;
struct lowdown_node *n;
memset(&work, 0, sizeof(struct lowdown_buf));
work.data = data;
work.size = end;
if (end > 2) {
if (altype != HALINK_NONE) {
if ((u_link = hbuf_new(64)) == NULL)
goto err;
work.data = data + 1;
work.size = end - 2;
if (!unscape_text(u_link, &work))
goto err;
n = pushnode(doc, LOWDOWN_LINK_AUTO);
if (n == NULL)
goto err;
n->rndr_autolink.type = altype;
if (!hbuf_createb(&n->rndr_autolink.link, u_link))
goto err;
popnode(doc, n);
} else {
n = pushnode(doc, LOWDOWN_RAW_HTML);
if (n == NULL)
goto err;
if (!hbuf_create
(&n->rndr_raw_html.text, data, end))
goto err;
popnode(doc, n);
}
ret = 1;
}
hbuf_free(u_link);
return !ret ? 0 : end;
err:
hbuf_free(u_link);
return -1;
}
/*
* 'w': parse URL when autolinking is allowed (from "www").
*/
static ssize_t
char_autolink_www(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
struct lowdown_buf *link = NULL, *link_url = NULL;
size_t link_len, rewind;
struct lowdown_node *n;
ssize_t ret;
if (doc->in_link_body)
return 0;
if ((link = hbuf_new(64)) == NULL)
goto err;
ret = halink_www(&rewind, link, data, offset, size);
if (ret < 0)
goto err;
link_len = ret;
if (link_len > 0) {
if ((link_url = hbuf_new(64)) == NULL)
goto err;
if (!HBUF_PUTSL(link_url, "http://"))
goto err;
if (!hbuf_put(link_url, link->data, link->size))
goto err;
if (doc->current &&
(n = TAILQ_LAST(&doc->current->children,
lowdown_nodeq)) != NULL &&
n->type == LOWDOWN_NORMAL_TEXT) {
if (n->rndr_normal_text.text.size > rewind)
n->rndr_normal_text.text.size -= rewind;
else
n->rndr_normal_text.text.size = 0;
}
if ((n = pushnode(doc, LOWDOWN_LINK_AUTO)) == NULL)
goto err;
n->rndr_autolink.type = HALINK_NORMAL;
if (!hbuf_createb(&n->rndr_autolink.link, link_url))
goto err;
popnode(doc, n);
}
hbuf_free(link);
hbuf_free(link_url);
return link_len;
err:
hbuf_free(link);
hbuf_free(link_url);
return -1;
}
/*
* '@': parse email when autolinking is allowed (from the at sign).
*/
static ssize_t
char_autolink_email(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
struct lowdown_buf *link = NULL;
size_t link_len, rewind;
ssize_t ret;
struct lowdown_node *n;
if (doc->in_link_body)
return 0;
if ((link = hbuf_new(64)) == NULL)
goto err;
ret = halink_email(&rewind, link, data, offset, size);
if (ret < 0)
goto err;
link_len = ret;
if (link_len > 0) {
if (doc->current &&
(n = TAILQ_LAST(&doc->current->children,
lowdown_nodeq)) != NULL &&
n->type == LOWDOWN_NORMAL_TEXT) {
if (n->rndr_normal_text.text.size > rewind)
n->rndr_normal_text.text.size -= rewind;
else
n->rndr_normal_text.text.size = 0;
}
if ((n = pushnode(doc, LOWDOWN_LINK_AUTO)) == NULL)
goto err;
n->rndr_autolink.type = HALINK_EMAIL;
if (!hbuf_createb(&n->rndr_autolink.link, link))
goto err;
popnode(doc, n);
}
hbuf_free(link);
return link_len;
err:
hbuf_free(link);
return -1;
}
/*
* ':': parse URL when autolinking is allowed (from the schema).
*/
static ssize_t
char_autolink_url(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
struct lowdown_buf *link = NULL;
size_t link_len, rewind;
struct lowdown_node *n;
ssize_t ret;
if (doc->in_link_body)
return 0;
if ((link = hbuf_new(64)) == NULL)
goto err;
ret = halink_url(&rewind, link, data, offset, size);
if (ret < 0)
goto err;
link_len = ret;
if (link_len > 0) {
if (doc->current &&
(n = TAILQ_LAST(&doc->current->children,
lowdown_nodeq)) != NULL &&
n->type == LOWDOWN_NORMAL_TEXT) {
if (n->rndr_normal_text.text.size > rewind)
n->rndr_normal_text.text.size -= rewind;
else
n->rndr_normal_text.text.size = 0;
}
if ((n = pushnode(doc, LOWDOWN_LINK_AUTO)) == NULL)
goto err;
n->rndr_autolink.type = HALINK_NORMAL;
if (!hbuf_createb(&n->rndr_autolink.link, link))
goto err;
popnode(doc, n);
}
hbuf_free(link);
return link_len;
err:
hbuf_free(link);
return -1;
}
/*
* '!': parse an image.
*/
static ssize_t
char_image(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
ssize_t ret;
if (size < 2 || data[1] != '[')
return 0;
ret = char_link(doc, data + 1, offset + 1, size - 1);
return ret <= 0 ? ret : ret + 1;
}
/*
* Parse extended attributes from the buffer "data". The buffer should
* not have any enclosing characters, e.g., { foo }. Return 0 on
* failure or position of *next* word.
*/
static size_t
parse_ext_attrs(const char *data, size_t size,
struct lowdown_buf **attrid,
struct lowdown_buf **attrcls,
struct lowdown_buf **attrwidth,
struct lowdown_buf **attrheight)
{
size_t word_b, word_e;
word_b = 0;
while (word_b < size) {
while (word_b < size && data[word_b] == ' ')
word_b++;
word_e = word_b;
while (word_e < size && data[word_e] != ' ')
word_e++;
/* Classes. */
if (attrid != NULL &&
word_e > word_b + 1 &&
data[word_b] == '#') {
if (*attrid == NULL &&
(*attrid = hbuf_new(64)) == NULL)
return 0;
hbuf_truncate(*attrid);
if (!hbuf_put(*attrid,
data + word_b + 1, word_e - word_b - 1))
return 0;
}
if (attrwidth != NULL &&
word_e > word_b + 7 &&
strncasecmp(&data[word_b], "width=", 6) == 0) {
if (*attrwidth == NULL &&
(*attrwidth = hbuf_new(64)) == NULL)
return 0;
hbuf_truncate(*attrwidth);
if (!hbuf_put(*attrwidth,
data + word_b + 6, word_e - word_b - 6))
return 0;
}
if (attrheight != NULL &&
word_e > word_b + 8 &&
strncasecmp(&data[word_b], "height=", 7) == 0) {
if (*attrheight == NULL &&
(*attrheight = hbuf_new(64)) == NULL)
return 0;
hbuf_truncate(*attrheight);
if (!hbuf_put(*attrheight,
data + word_b + 7, word_e - word_b - 7))
return 0;
}
if (attrcls != NULL &&
word_e > word_b + 1 &&
data[word_b] == '.') {
if (*attrcls != NULL &&
!hbuf_putc(*attrcls, ' '))
return 0;
if (*attrcls == NULL &&
(*attrcls = hbuf_new(64)) == NULL)
return 0;
if (!hbuf_put(*attrcls,
data + word_b + 1, word_e - word_b - 1))
return 0;
}
word_b = word_e + 1;
}
return word_b;
}
/*
* Parse a header's extended attributes. Return FALSE on failure, TRUE
* on success.
*/
static int
parse_header_ext_attrs(struct lowdown_node *n)
{
struct lowdown_node *nn;
struct lowdown_buf *b, *attrid = NULL, *attrcls = NULL;
size_t i;
int rc = 0;
/*
* The last node on the line must be non-empty normal text and
* must end with a '}'.
*/
nn = TAILQ_LAST(&n->children, lowdown_nodeq);
if (nn == NULL ||
nn->type != LOWDOWN_NORMAL_TEXT ||
nn->rndr_normal_text.text.size == 0 ||
nn->rndr_normal_text.text.data
[nn->rndr_normal_text.text.size - 1] != '}')
return 1;
/* Scan from the trailing '}' to the opening '{'. */
b = &nn->rndr_normal_text.text;
assert(b->size && b->data[b->size - 1] == '}');
for (i = b->size - 1; i > 0; i--)
if (b->data[i] == '{')
break;
if (b->data[i] != '{')
return 1;
/* Parse the extended attributes. */
if (!parse_ext_attrs(&b->data[i + 1], b->size - i - 2,
&attrid, &attrcls, NULL, NULL))
goto out;
if (attrid != NULL &&
!hbuf_createb(&n->rndr_header.attr_id, attrid))
goto out;
if (attrcls != NULL &&
!hbuf_createb(&n->rndr_header.attr_cls, attrcls))
goto out;
b->size = i;
while (b->size && b->data[b->size - 1] == ' ')
b->size--;
/* Is there nothing left? */
if (b->size == 0) {
TAILQ_REMOVE(&n->children, nn, entries);
lowdown_node_free(nn);
}
rc = 1;
out:
hbuf_free(attrid);
hbuf_free(attrcls);
return rc;
}
/*
* '[': parsing a link, footnote, metadata, or image.
*/
static ssize_t
char_link(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
struct lowdown_buf *content = NULL, *link = NULL,
*title = NULL, *u_link = NULL,
*dims = NULL, *idp = NULL,
*linkp = NULL, *titlep = NULL,
*attrcls = NULL, *attrid = NULL,
*attrwidth = NULL, *attrheight = NULL;
size_t i = 1, j, txt_e, link_b = 0, link_e = 0,
title_b = 0, title_e = 0, nb_p,
dims_b = 0, dims_e = 0;
int ret = 0, in_title = 0, qtype = 0,
is_img, is_footnote, is_metadata;
struct lowdown_buf id;
struct link_ref *lr = NULL;
struct foot_ref *fr;
struct lowdown_node *n;
struct lowdown_meta *m;
is_img = offset && data[-1] == '!' &&
!is_escaped(data - offset, offset - 1);
is_footnote = (doc->ext_flags & LOWDOWN_FOOTNOTES) &&
data[1] == '^';
is_metadata = (doc->ext_flags & LOWDOWN_METADATA) &&
data[1] == '%';
/*
* XXX: immediately disregard nested links. CommonMark
* is contradictory here, saying "links may not contain links",
* but follows by saying "if they are...". Follow what pandoc
* does instead and only parse the top-level link, letting all
* sub-content be rendered as text.
*/
if (!is_img && doc->in_link_body)
goto cleanup;
/* Looking for the matching closing bracket. */
i += find_emph_char(data + i, size - i, ']');
txt_e = i;
if (i < size && data[i] == ']')
i++;
else
goto cleanup;
/*
* If we start as an image then change into metadata or a
* footnote, make sure to emit the exclamation mark.
*/
if (is_img && (is_footnote || is_metadata)) {
n = pushnode(doc, LOWDOWN_NORMAL_TEXT);
if (n == NULL)
goto err;
if (!hbuf_push(&n->rndr_normal_text.text, &data[-1], 1))
goto err;
popnode(doc, n);
}
/*
* Footnote (in footer): look up footnote by its key in our
* queue of footnotes. This queue was created in the first pass
* of the compiler. If we've already listed the footnote, don't
* render it twice. Don't allow embedded footnotes as well.
*/
if (is_footnote) {
memset(&id, 0, sizeof(struct lowdown_buf));
if (txt_e < 3)
goto cleanup;
id.data = data + 2;
id.size = txt_e - 2;
TAILQ_FOREACH(fr, &doc->footq, entries)
if (hbuf_eq(&fr->name, &id))
break;
/* Override. */
if (doc->in_footnote)
fr = NULL;
/*
* Mark footnote used. If it's NULL, then there was no
* footnote found. If it is NULL and the reference is
* defined, then we've already registered the footnote.
* XXX: Markdown, as is, can only use one footnote
* reference per definition. This is stupid.
*/
if (fr != NULL && fr->ref == NULL) {
n = pushnode(doc, LOWDOWN_FOOTNOTE);
if (n == NULL)
goto err;
fr->num = ++doc->foots;
fr->ref = n;
assert(doc->in_footnote == 0);
doc->in_footnote = 1;
if (!parse_block(doc,
fr->contents.data, fr->contents.size))
goto err;
assert(doc->in_footnote);
doc->in_footnote = 0;
} else {
n = pushnode(doc, LOWDOWN_NORMAL_TEXT);
if (n == NULL)
goto err;
if (!hbuf_push(&n->rndr_normal_text.text,
data, txt_e + 1))
goto err;
}
popnode(doc, n);
ret = 1;
goto cleanup;
}
/*
* Metadata: simply copy the variable (if found) into our
* stream. It's raw text, so we need to pass it into our
* "normal text" formatter.
*/
if (is_metadata) {
memset(&id, 0, sizeof(struct lowdown_buf));
if (txt_e < 3)
goto cleanup;
id.data = data + 2;
id.size = txt_e - 2;
/* FIXME: slow O(n). */
TAILQ_FOREACH(m, doc->metaq, entries) {
if (!hbuf_streq(&id, m->key))
continue;
assert(m->value != NULL);
n = pushnode(doc, LOWDOWN_NORMAL_TEXT);
if (n == NULL)
goto err;
if (!hbuf_push(&n->rndr_normal_text.text,
m->value, strlen(m->value)))
goto err;
popnode(doc, n);
break;
}
ret = 1;
goto cleanup;
}
/*
* Skip any amount of spacing. (This is much more laxist than
* original markdown syntax.)
*/
while (i < size && xisspace(data[i]))
i++;
/* Different style of links (regular, reference, shortcut. */
if (i < size && data[i] == '(') {
i++;
while (i < size && xisspace(data[i]))
i++;
link_b = i;
/*
* Looking for link end: ' " )
* Count the number of open parenthesis.
*/
nb_p = 0;
while (i < size) {
if (data[i] == '\\') {
i += 2;
} else if (data[i] == '(' && i != 0) {
nb_p++;
i++;
} else if (data[i] == ')') {
if (nb_p == 0)
break;
else
nb_p--;
i++;
} else if (i >= 1 && xisspace(data[i-1]) &&
(data[i] == '\'' ||
data[i] == '=' ||
data[i] == '"'))
break;
else
i++;
}
if (i >= size)
goto cleanup;
link_e = i;
/*
* We might be at the end of the link, or we might be at
* the title of the link.
* In the latter case, progress til link-end.
*/
again:
if (data[i] == '\'' || data[i] == '"') {
/*
* Looking for title end if present.
* This is a quoted part after the image.
*/
qtype = data[i];
in_title = 1;
i++;
title_b = i;
for ( ; i < size; i++)
if (data[i] == '\\')
i++;
else if (data[i] == qtype)
in_title = 0;
else if ((data[i] == '=') && !in_title)
break;
else if ((data[i] == ')') && !in_title)
break;
if (i >= size)
goto cleanup;
/* Skipping spacing after title. */
title_e = i - 1;
while (title_e > title_b &&
xisspace(data[title_e]))
title_e--;
/* Checking for closing quote presence. */
if (data[title_e] != '\'' &&
data[title_e] != '"') {
title_b = title_e = 0;
link_e = i;
}
/*
* If we're followed by a dimension string, then
* jump back into the parsing engine for it.
*/
if (data[i] == '=')
goto again;
} else if (data[i] == '=') {
dims_b = ++i;
for ( ; i < size; i++)
if (data[i] == '\\')
i++;
else if ('\'' == data[i] || '"' == data[i])
break;
else if (data[i] == ')')
break;
if (i >= size)
goto cleanup;
/* Skipping spacing after dimensions. */
dims_e = i;
while (dims_e > dims_b &&
xisspace(data[dims_e]))
dims_e--;
/*
* If we're followed by a title string, then
* jump back into the parsing engine for it.
*/
if (data[i] == '"' || data[i] == '\'')
goto again;
}
/* Remove spacing at the end of the link. */
while (link_e > link_b && xisspace(data[link_e - 1]))
link_e--;
/* Remove optional angle brackets around the link. */
if (data[link_b] == '<' && data[link_e - 1] == '>') {
link_b++;
link_e--;
}
/* building escaped link and title */
if (link_e > link_b) {
link = linkp = hbuf_new(64);
if (linkp == NULL)
goto err;
if (!hbuf_put(link,
data + link_b, link_e - link_b))
goto err;
}
if (title_e > title_b) {
title = titlep = hbuf_new(64);
if (titlep == NULL)
goto err;
if (!hbuf_put(title,
data + title_b, title_e - title_b))
goto err;
}
if (dims_e > dims_b) {
if ((dims = hbuf_new(64)) == NULL)
goto err;
if (!hbuf_put(dims,
data + dims_b, dims_e - dims_b))
goto err;
}
i++;
} else if (i < size && data[i] == '[') {
if ((idp = hbuf_new(64)) == NULL)
goto err;
/* Looking for the id. */
i++;
link_b = i;
while (i < size && data[i] != ']')
i++;
if (i >= size)
goto cleanup;
link_e = i;
/* Finding the link_ref. */
if (link_b == link_e) {
if (!replace_spacing
(idp, data + 1, txt_e - 1))
goto err;
} else
if (!hbuf_put(idp,
data + link_b, link_e - link_b))
goto err;
lr = find_link_ref(&doc->refq, idp->data, idp->size);
if (lr == NULL)
goto cleanup;
/* Keeping link and title from link_ref. */
link = lr->link;
title = lr->title;
if (lr->attrs != NULL && parse_ext_attrs
(lr->attrs->data, lr->attrs->size,
&attrid, &attrcls, &attrwidth, &attrheight) == 0)
goto err;
i++;
} else {
/*
* Shortcut reference style link.
*/
if ((idp = hbuf_new(64)) == NULL)
goto err;
/* Crafting the id. */
if (!replace_spacing(idp, data + 1, txt_e - 1))
goto err;
/* Finding the link_ref. */
lr = find_link_ref(&doc->refq, idp->data, idp->size);
if (lr == NULL)
goto cleanup;
/* Keeping link and title from link_ref. */
link = lr->link;
title = lr->title;
if (lr->attrs != NULL && parse_ext_attrs
(lr->attrs->data, lr->attrs->size,
&attrid, &attrcls, &attrwidth, &attrheight) == 0)
goto err;
/* Rewinding the spacing. */
i = txt_e + 1;
}
/* PHP markdown extra attributes (if not ref link). */
if ((doc->ext_flags & LOWDOWN_ATTRS) && lr == NULL &&
i + 2 < size && data[i] == '{') {
i++;
/* Find trailing marker. */
for (j = i; j < size && data[j] != '}'; j++)
continue;
j = parse_ext_attrs(&data[i], j - i,
&attrid, &attrcls, &attrwidth, &attrheight);
if (j == 0)
goto err;
i += j;
if (i < size && data[i] == '}')
i++;
}
n = pushnode(doc, is_img ? LOWDOWN_IMAGE : LOWDOWN_LINK);
if (n == NULL)
goto err;
/*
* Building content: img alt is kept, only link content is
* parsed.
*/
if (txt_e > 1) {
if ( ! is_img) {
/*
* Disable autolinking when parsing inline the
* content of a link.
*/
doc->in_link_body = 1;
if (!parse_inline(doc, data + 1, txt_e - 1))
goto err;
doc->in_link_body = 0;
} else {
if ((content = hbuf_new(64)) == NULL)
goto err;
if (!hbuf_put(content, data + 1, txt_e - 1))
goto err;
}
}
if (link) {
if ((u_link = hbuf_new(64)) == NULL)
goto err;
if (!unscape_text(u_link, link))
goto err;
}
/* Calling the relevant rendering function. */
if (is_img) {
if (u_link != NULL &&
!hbuf_createb(&n->rndr_image.link, u_link))
goto err;
if (title != NULL &&
!hbuf_createb(&n->rndr_image.title, title))
goto err;
if (dims != NULL &&
!hbuf_createb(&n->rndr_image.dims, dims))
goto err;
if (content != NULL &&
!hbuf_createb(&n->rndr_image.alt, content))
goto err;
if (attrcls != NULL &&
!hbuf_createb(&n->rndr_image.attr_cls, attrcls))
goto err;
if (attrid != NULL &&
!hbuf_createb(&n->rndr_image.attr_id, attrid))
goto err;
if (attrwidth != NULL &&
!hbuf_createb(&n->rndr_image.attr_width, attrwidth))
goto err;
if (attrheight != NULL &&
!hbuf_createb(&n->rndr_image.attr_height, attrheight))
goto err;
ret = 1;
} else {
if (u_link != NULL &&
!hbuf_createb(&n->rndr_link.link, u_link))
goto err;
if (title != NULL &&
!hbuf_createb(&n->rndr_link.title, title))
goto err;
if (attrcls != NULL &&
!hbuf_createb(&n->rndr_link.attr_cls, attrcls))
goto err;
if (attrid != NULL &&
!hbuf_createb(&n->rndr_link.attr_id, attrid))
goto err;
ret = 1;
}
popnode(doc, n);
goto cleanup;
err:
ret = -1;
cleanup:
hbuf_free(attrid);
hbuf_free(attrcls);
hbuf_free(attrheight);
hbuf_free(attrwidth);
hbuf_free(linkp);
hbuf_free(titlep);
hbuf_free(dims);
hbuf_free(idp);
hbuf_free(content);
hbuf_free(u_link);
return ret > 0 ? (ssize_t)i : ret;
}
/*
* Parsing a superscript or subscript.
*/
static ssize_t
char_supsubscript(struct lowdown_doc *doc, char *data, size_t offset,
size_t size, char token)
{
size_t sup_start, sup_len, end;
struct lowdown_node *n;
assert(token == '^' || token == '~');
if (size < 2)
return 0;
/*
* The traditional syntax for superscripts is incompatible with
* pandoc's (from GFM). Calling the traditional syntax "short":
* first check if not using that, then fall back on the
* traditional syntaxes.
*/
if (!(doc->ext_flags & LOWDOWN_SUPER_SHORT)) {
sup_start = sup_len = 1;
while (sup_len < size && data[sup_len] != token)
if (xisspace(data[sup_len++]))
return 0;
/*
* FIXME: a standalone "~~" results in noting at all
* being printed instead of the ~~.
*/
if (sup_len == size)
return 0;
end = sup_len + 1;
if (sup_len - sup_start == 0)
return 2;
} else if (data[1] == '(') {
sup_start = 2;
sup_len = find_emph_char(data + 2, size - 2, ')') + 2;
if (sup_len == size)
return 0;
end = sup_len + 1;
if (sup_len - sup_start == 0)
return 3;
} else {
sup_start = sup_len = 1;
while (sup_len < size && !xisspace(data[sup_len]))
sup_len++;
end = sup_len;
if (sup_len - sup_start == 0)
return 0;
}
if ((n = pushnode(doc, token == '^' ?
LOWDOWN_SUPERSCRIPT : LOWDOWN_SUBSCRIPT)) == NULL)
return -1;
if (!parse_inline(doc, data + sup_start, sup_len - sup_start))
return -1;
popnode(doc, n);
return end;
}
static ssize_t
char_superscript(struct lowdown_doc *doc, char *data, size_t offset,
size_t size)
{
return char_supsubscript(doc, data, offset, size, '^');
}
static ssize_t
char_subscript(struct lowdown_doc *doc, char *data, size_t offset,
size_t size)
{
if ((doc->ext_flags & LOWDOWN_STRIKE) && size > 0 &&
data[1] == '~')
return char_emphasis(doc, data, offset, size);
return char_supsubscript(doc, data, offset, size, '~');
}
static ssize_t
char_math(struct lowdown_doc *doc,
char *data, size_t offset, size_t size)
{
return size > 1 && data[1] == '$' ?
parse_math(doc, data, offset, size, "$$", 2, 1) :
parse_math(doc, data, offset, size, "$", 1, 0);
}
/*
* Returns the line length when it is empty, 0 otherwise.
*/
static size_t
is_empty(const char *data, size_t size)
{
size_t i;
for (i = 0; i < size && data[i] != '\n'; i++)
if (data[i] != ' ')
return 0;
return i + 1;
}
/*
* Returns whether a line is a horizontal rule.
*/
static int
is_hrule(const char *data, size_t size)
{
size_t i = 0, n = 0;
char c;
/* Skipping initial spaces. */
if (size < 3)
return 0;
i = countspaces(data, 0, size, 3);
/* Looking at the hrule char. */
if (i + 2 >= size ||
(data[i] != '*' && data[i] != '-' && data[i] != '_'))
return 0;
c = data[i];
/* The whole line must be the char or space. */
while (i < size && data[i] != '\n') {
if (data[i] == c)
n++;
else if (data[i] != ' ')
return 0;
i++;
}
return n >= 3;
}
/*
* Check if a line is a code fence; return the end of the code fence.
* If passed, width of the fence rule and character will be returned.
*/
static size_t
is_codefence(const char *data, size_t size, size_t *width, char *chr)
{
size_t i = 0, n = 1;
char c;
/* Skipping initial spaces. */
if (size < 3)
return 0;
i = countspaces(data, 0, size, 3);
/* Looking at the hrule char. */
c = data[i];
if (i + 2 >= size || !(c == '~' || c == '`'))
return 0;
/* The fence must be that same character. */
while (++i < size && data[i] == c)
++n;
if (n < 3)
return 0;
if (width)
*width = n;
if (chr)
*chr = c;
return i;
}
/*
* Expects single line, checks if it's a codefence and extracts
* language.
* Return zero if not a code-fence, >0 offset otherwise.
*/
static size_t
parse_codefence(char *data, size_t size,
struct lowdown_buf *lang, size_t *width, char *chr)
{
size_t i, w, lang_start;
i = w = is_codefence(data, size, width, chr);
if (i == 0)
return 0;
while (i < size && xisspace(data[i]))
i++;
lang_start = i;
while (i < size && !xisspace(data[i]))
i++;
lang->data = data + lang_start;
lang->size = i - lang_start;
/* Avoid parsing a codespan as a fence */
i = lang_start + 2;
while (i < size &&
!(data[i] == *chr &&
data[i-1] == *chr &&
data[i-2] == *chr))
i++;
return i < size ? 0 : w;
}
/*
* Returns whether the line is a hash-prefixed header.
* Return zero if not an at-header, non-zero otherwise.
*/
static int
is_atxheader(const struct lowdown_doc *doc,
const char *data, size_t size)
{
size_t level;
if (data[0] != '#')
return 0;
/*
* CommonMark requires a space.
* Classical Markdown does not.
*/
if (doc->ext_flags & LOWDOWN_COMMONMARK) {
level = 0;
while (level < size && level < 6 && data[level] == '#')
level++;
if (level < size && data[level] != ' ')
return 0;
}
return 1;
}
/*
* Tests for level 1 setext-style header ("=") or level 2 ("-").
* Returns zero if it's not, non-zero otherwise.
*/
static int
is_headerline(const char *data, size_t size)
{
size_t i;
char hchr;
int level;
if ('=' == *data || '-' == *data) {
level = '=' == *data ? 1 : 2;
hchr = *data;
} else
return 0;
for (i = 1; i < size && data[i] == hchr; i++)
continue;
i = countspaces(data, i, size, 0);
return (i >= size || data[i] == '\n') ? level : 0;
}
static int
is_next_headerline(const char *data, size_t size)
{
size_t i = 0;
while (i < size && data[i] != '\n')
i++;
if (++i >= size)
return 0;
return is_headerline(data + i, size - i);
}
/*
* Returns unordered list item prefix.
* This does nothing if LOWDOWN_DEFLIST is not set.
*/
static size_t
prefix_dli(const struct lowdown_doc *doc, const char *data, size_t size)
{
size_t i;
if (!(doc->ext_flags & LOWDOWN_DEFLIST))
return 0;
i = countspaces(data, 0, size, 3);
if (i + 1 >= size || data[i] != ':' || data[i + 1] != ' ')
return 0;
if (is_next_headerline(data + i, size - i))
return 0;
return i + 2;
}
/*
* Returns blockquote prefix length.
*/
static size_t
prefix_quote(const char *data, size_t size)
{
size_t i;
i = countspaces(data, 0, size, 3);
if (i < size && data[i] == '>')
return countspaces(data, i + 1, size, 1);
return 0;
}
/*
* Returns prefix length for block code.
*/
static size_t
prefix_code(const char *data, size_t size)
{
if (countspaces(data, 0, size, 4) == 4)
return 4;
return 0;
}
/*
* Returns ordered list item prefix.
* On success (return value >0) and if "value" is not NULL *and* we're
* also commonmark processing, copy and NUL-terminate the value into it.
* If all of those except for commonmark, simply NUL-terminate the
* string.
*/
static size_t
prefix_oli(const struct lowdown_doc *doc,
const char *data, size_t size, char *value)
{
size_t i, st, vsize;
const char *vdata;
i = countspaces(data, 0, size, 3);
if (i >= size || !isdigit((unsigned char)data[i]))
return 0;
st = i;
vdata = &data[i];
while (i < size && isdigit((unsigned char)data[i]))
i++;
/* Commonmark limits us to nine characters. */
vsize = i - st;
if ((doc->ext_flags & LOWDOWN_COMMONMARK) && vsize > 9)
return 0;
/*
* Commonmark accepts ')' and '.' following the numeric prefix,
* while regular markdown only has '.'.
*/
if (doc->ext_flags & LOWDOWN_COMMONMARK) {
if (i + 1 >= size ||
(data[i] != '.' && data[i] != ')') ||
data[i + 1] != ' ')
return 0;
} else if (i + 1 >= size || data[i] != '.' || data[i + 1] != ' ')
return 0;
if (is_next_headerline(data + i, size - i))
return 0;
if (value != NULL) {
if (doc->ext_flags & LOWDOWN_COMMONMARK) {
assert(vsize > 0);
assert(vsize < 10);
memcpy(value, vdata, vsize);
value[vsize] = '\0';
} else
value[0] = '\0';
}
return i + 2;
}
/*
* Returns unordered list item prefix, including a GFM checkbox. The
* "checked" pointer, if not NULL, is set to whether the check is set
* (>0), unset (=0), or not there (<0).
*/
static size_t
prefix_uli(const struct lowdown_doc *doc,
const char *data, size_t size, int *checked)
{
size_t i;
if (checked != NULL)
*checked = -1;
i = countspaces(data, 0, size, 3);
if (i + 1 >= size ||
(data[i] != '*' && data[i] != '+' &&
data[i] != '-') ||
data[i + 1] != ' ')
return 0;
if (is_next_headerline(data + i, size - i))
return 0;
if (!(doc->ext_flags & LOWDOWN_TASKLIST) || i + 5 >= size)
return i + 2;
if (data[i + 2] == '[' &&
(data[i + 3] == ' ' ||
data[i + 3] == 'x' ||
data[i + 3] == 'X') &&
data[i + 4] == ']' &&
data[i + 5] == ' ') {
if (checked != NULL)
*checked = data[i + 3] != ' ';
return i + 6;
}
return i + 2;
}
/*
* Handles parsing of a blockquote fragment.
* Return <0 on failure, otherwise the end offset.
*/
static ssize_t
parse_blockquote(struct lowdown_doc *doc, char *data, size_t size)
{
size_t beg = 0, end = 0, pre, work_size = 0;
char *work_data = NULL;
struct lowdown_node *n, *nn, *nnn;
while (beg < size) {
for (end = beg + 1;
end < size && data[end - 1] != '\n';
end++)
continue;
pre = prefix_quote(data + beg, end - beg);
/* Skip prefix or empty line followed by non-quote. */
if (pre)
beg += pre;
else if (is_empty(data + beg, end - beg) &&
(end >= size ||
(prefix_quote(data + end, size - end) == 0 &&
!is_empty(data + end, size - end))))
break;
if (beg < end) {
if (!work_data)
work_data = data + beg;
else if (data + beg != work_data + work_size)
memmove(work_data + work_size,
data + beg, end - beg);
work_size += end - beg;
}
beg = end;
}
n = pushnode(doc, LOWDOWN_BLOCKQUOTE);
if (n == NULL)
return -1;
if (!parse_block(doc, work_data, work_size))
return -1;
popnode(doc, n);
if (!(doc->ext_flags & LOWDOWN_CALLOUTS))
return end;
/*
* See if we're a GitHub or MDN admonition. Begin by seeing if
* the first node is a paragraph containing an initial double
* emphasis with a specific word therein.
*/
if (TAILQ_EMPTY(&n->children))
return end;
nn = TAILQ_FIRST(&n->children);
if (nn->type != LOWDOWN_PARAGRAPH ||
(nn = TAILQ_FIRST(&nn->children)) == NULL)
return end;
if (nn->type != LOWDOWN_DOUBLE_EMPHASIS ||
(nnn = TAILQ_FIRST(&nn->children)) == NULL)
return end;
if (nnn->type != LOWDOWN_NORMAL_TEXT ||
TAILQ_NEXT(nnn, entries) != NULL)
return end;
/*
* GitHub uses the term on its own, while MDN uses the word, a
* colon, and more text afterward. Accept both. (GitHub
* doesn't support a "callout" admonition.)
*/
if (hbuf_streq(&nnn->rndr_normal_text.text, "Note"))
n->rndr_blockquote.admonition = ADMONITION_NOTE;
else if (hbuf_streq(&nnn->rndr_normal_text.text, "Note:"))
n->rndr_blockquote.admonition = ADMONITION_NOTE;
else if (hbuf_streq(&nnn->rndr_normal_text.text, "Callout:"))
n->rndr_blockquote.admonition = ADMONITION_CALLOUT;
else if (hbuf_streq(&nnn->rndr_normal_text.text, "Warning"))
n->rndr_blockquote.admonition = ADMONITION_WARNING;
else if (hbuf_streq(&nnn->rndr_normal_text.text, "Warning:"))
n->rndr_blockquote.admonition = ADMONITION_WARNING;
else
return end;
n->rndr_blockquote.type = BLOCKQUOTE_ADMONITION_BLOCK;
/* If the starting is just its own paragraph, done. */
if ((nn = TAILQ_NEXT(nn, entries)) == NULL)
return end;
/* ...or on its own line. */
if (nn->type == LOWDOWN_NORMAL_TEXT &&
hbuf_strprefix(&nn->rndr_normal_text.text, "\n"))
n->rndr_blockquote.type = BLOCKQUOTE_ADMONITION;
return end;
}
/*
* Handles parsing of a regular paragraph, which terminates at sections
* or blank lines.
* Returns <0 on failure or the number of characters parsed from the
* paragraph input.
*/
static ssize_t
parse_paragraph(struct lowdown_doc *doc, char *data, size_t size)
{
struct lowdown_buf work;
struct lowdown_node *n;
size_t i = 0, end = 0, beg, lines = 0;
int level = 0, beoln = 0;
memset(&work, 0, sizeof(struct lowdown_buf));
work.data = data;
while (i < size) {
/* Parse ahead to the next newline. */
for (end = i + 1;
end < size && data[end - 1] != '\n'; end++)
continue;
/*
* Empty line: end of paragraph.
* However, check if we have a dli prefix following
* that, which means that we're a block-mode dli.
*/
if (is_empty(data + i, size - i)) {
beoln = 1;
break;
}
/* Header line: end of paragraph. */
if ((level = is_headerline(data + i, size - i)) != 0)
break;
/* Other ways of ending a paragraph. */
if (is_atxheader(doc, data + i, size - i) ||
is_hrule(data + i, size - i) ||
(lines == 1 &&
prefix_dli(doc, data + i, size - i)) ||
prefix_quote(data + i, size - i)) {
end = i;
break;
}
lines++;
i = end;
}
work.size = i;
while (work.size && data[work.size - 1] == '\n')
work.size--;
/*
* The paragraph isn't ending on a header line.
* So it's a regular paragraph.
*/
if (!level) {
n = pushnode(doc, LOWDOWN_PARAGRAPH);
if (n == NULL)
return -1;
n->rndr_paragraph.lines = lines;
n->rndr_paragraph.beoln = beoln;
if (!parse_inline(doc, work.data, work.size))
return -1;
popnode(doc, n);
return end;
}
/* Paragraph material prior to header break. */
if (work.size) {
i = work.size;
work.size -= 1;
while (work.size && data[work.size] != '\n')
work.size -= 1;
beg = work.size + 1;
while (work.size && data[work.size - 1] == '\n')
work.size -= 1;
if (work.size > 0) {
n = pushnode(doc, LOWDOWN_PARAGRAPH);
if (n == NULL)
return -1;
n->rndr_paragraph.lines = lines - 1;
n->rndr_paragraph.beoln = beoln;
if (!parse_inline(doc, work.data, work.size))
return -1;
popnode(doc, n);
work.data += beg;
work.size = i - beg;
} else
work.size = i;
}
/* Definition data parts. */
if ((n = pushnode(doc, LOWDOWN_HEADER)) == NULL)
return -1;
assert(level > 0);
n->rndr_header.level = level - 1;
if (!parse_inline(doc, work.data, work.size))
return -1;
popnode(doc, n);
if ((doc->ext_flags & LOWDOWN_ATTRS) &&
!parse_header_ext_attrs(n))
return -1;
return end;
}
/*
* Handles parsing of a block-level code fragment.
* Return <0 on failure, 0 if not a fragment, >0 on success.
*/
static ssize_t
parse_fencedcode(struct lowdown_doc *doc, char *data, size_t size)
{
struct lowdown_buf text, lang;
size_t i = 0, text_start, line_start,
w, w2, width, width2;
char chr, chr2;
struct lowdown_node *n;
memset(&text, 0, sizeof(struct lowdown_buf));
memset(&lang, 0, sizeof(struct lowdown_buf));
/* Parse codefence line. */
while (i < size && data[i] != '\n')
i++;
if ((w = parse_codefence(data, i, &lang, &width, &chr)) == 0)
return 0;
/* Search for end. */
i++;
text_start = i;
while ((line_start = i) < size) {
while (i < size && data[i] != '\n')
i++;
w2 = is_codefence(data + line_start,
i - line_start, &width2, &chr2);
if (w == w2 &&
width == width2 &&
chr == chr2 &&
is_empty(data +
(line_start+w), i - (line_start+w)))
break;
i++;
}
text.data = data + text_start;
text.size = line_start - text_start;
if ((n = pushnode(doc, LOWDOWN_BLOCKCODE)) == NULL)
return -1;
if (!hbuf_create(&n->rndr_blockcode.text,
data + text_start, line_start - text_start))
return -1;
if (!hbuf_createb(&n->rndr_blockcode.lang, &lang))
return -1;
popnode(doc, n);
return i;
}
static ssize_t
parse_blockcode(struct lowdown_doc *doc, char *data, size_t size)
{
size_t beg = 0, end, pre;
struct lowdown_buf *work = NULL;
struct lowdown_node *n;
if ((work = hbuf_new(256)) == NULL)
goto err;
while (beg < size) {
for (end = beg + 1;
end < size && data[end - 1] != '\n';
end++)
continue;
pre = prefix_code(data + beg, end - beg);
/*
* Skip prefix or non-empty non-prefixed line breaking
* the pre.
*/
if (pre)
beg += pre;
else if (!is_empty(data + beg, end - beg))
break;
/*
* Verbatim copy to the working buffer, escaping
* entities.
*/
if (beg < end) {
if (is_empty(data + beg, end - beg)) {
if (!hbuf_putc(work, '\n'))
goto err;
} else {
if (!hbuf_put(work,
data + beg, end - beg))
goto err;
}
}
beg = end;
}
while (work->size && work->data[work->size - 1] == '\n')
work->size -= 1;
if (!hbuf_putc(work, '\n'))
goto err;
if ((n = pushnode(doc, LOWDOWN_BLOCKCODE)) == NULL)
goto err;
if (!hbuf_createb(&n->rndr_blockcode.text, work))
goto err;
popnode(doc, n);
hbuf_free(work);
return beg;
err:
hbuf_free(work);
return -1;
}
/*
* Parsing of a single list item assuming initial prefix is already
* removed.
*/
static ssize_t
parse_listitem(struct lowdown_buf *ob, struct lowdown_doc *doc,
char *data, size_t size, enum hlist_fl *flags, size_t num)
{
struct lowdown_buf *work = NULL;
size_t beg = 0, end, pre, sublist = 0,
orgpre, i, has_next_uli = 0, dli_lines,
has_next_oli = 0, has_next_dli = 0;
int in_empty = 0, has_block = 0,
in_fence = 0, ff, checked = -1,
has_initial_newline = -1;
struct lowdown_node *n;
/* Keeping track of the first indentation prefix. */
orgpre = countspaces(data, 0, size, 3);
beg = prefix_uli(doc, data, size, &checked);
if (!beg)
beg = prefix_oli(doc, data, size, NULL);
if (!beg)
beg = prefix_dli(doc, data, size);
if (!beg)
return 0;
/* Skipping to the beginning of the following line. */
end = beg;
while (end < size && data[end - 1] != '\n')
end++;
/* Getting working buffers. */
if ((work = hbuf_new(64)) == NULL)
goto err;
/* Putting the first line into the working buffer. */
if (!hbuf_put(work, data + beg, end - beg))
goto err;
beg = end;
dli_lines = 1;
/*
* Process the following lines.
* Use the "dli_lines" variable to see if we should consider an
* opening dli prefix to be a valid dli token.
*/
while (beg < size) {
has_next_uli = has_next_oli = has_next_dli = 0;
end++;
while (end < size && data[end - 1] != '\n')
end++;
/*
* Process an empty line. If this has followed text on
* its own, set has_initial_newline to 1, meaning that
* we've had an empty line following regular text.
*/
if (is_empty(data + beg, end - beg)) {
if (has_initial_newline <= 0)
has_initial_newline = 1;
in_empty = 1;
beg = end;
dli_lines = 0;
continue;
}
dli_lines++;
/* Calculating the indentation. */
/*
* FIXME: by passing "4" to countspaces(), nested lists
* that are indented by less than this aren't properly
* parsed. E.g.,
*
* - list
*
* with paragraph
*
* - inner list
*
* inner para
*
* If we reduce this to "3", then these lists are
* handled properly. However, this breaks existing
* functionality with respect to tabbed lists, as tabs
* are expanded before this function into 4 tabsteps.
*
* It's not clear to me why this is the case.
*/
pre = i = countspaces(data, beg, end, 4) - beg;
if (doc->ext_flags & LOWDOWN_FENCED)
if (is_codefence(data + beg + i,
end - beg - i, NULL, NULL))
in_fence = !in_fence;
/*
* Only check for new list items if we are **not**
* inside a fenced code block.
* We only allow dli if we've had a single line of
* content beforehand.
*/
if (!in_fence) {
has_next_uli = prefix_uli(doc,
data + beg + i, end - beg - i, NULL);
has_next_dli = dli_lines <= 2 && prefix_dli
(doc, data + beg + i, end - beg - i);
has_next_oli = prefix_oli
(doc, data + beg + i, end - beg - i, NULL);
if (has_next_uli || has_next_dli || has_next_oli)
dli_lines = 0;
}
/* Checking for a new item. */
if ((has_next_uli &&
!is_hrule(data + beg + i, end - beg - i)) ||
has_next_oli || has_next_dli) {
/*
* If there's space before the ruler, mark us as
* a block---but only at the top level of
* the list.
*/
if (in_empty && sublist == 0)
has_block = 1;
/*
* The following item must have the same (or
* less) indentation.
*/
if (pre <= orgpre) {
/*
* If the following item has different
* list type, we end this list.
* If we haven't had a paragraph break,
* mark this as not having a block.
*/
ff = *flags & HLIST_FL_MASK;
assert(ff == HLIST_FL_ORDERED ||
ff == HLIST_FL_UNORDERED ||
ff == HLIST_FL_DEF);
if (((ff == HLIST_FL_ORDERED) &&
(has_next_uli || has_next_dli)) ||
((ff == HLIST_FL_UNORDERED) &&
(has_next_oli || has_next_dli)) ||
((ff == HLIST_FL_DEF) &&
(has_next_oli || has_next_uli))) {
*flags |= HLIST_LI_END;
if (has_initial_newline < 2)
has_block = 0;
}
break;
} else if (sublist == 0) {
/*
* If we've had an empty line and we're
* at a new list type, mark it as if
* we've seen a paragraph break.
*/
if (has_initial_newline == 1)
has_initial_newline = 2;
}
if (sublist == 0)
sublist = work->size;
} else if (in_empty && pre == 0) {
/*
* Joining only indented stuff after empty
* lines; note that now we only require 1 space
* of indentation to continue a list.
*/
*flags |= HLIST_LI_END;
break;
} else {
/*
* If we haven't had an initial empty line, mark
* that we're still receiving text prior to an
* empty line; otherwise, if we've had an empty
* line, mark that we've had a paragraph break.
*/
if (has_initial_newline == -1)
has_initial_newline = 0;
if (has_initial_newline == 1)
has_initial_newline = 2;
}
if (in_empty) {
if (!hbuf_putc(work, '\n'))
goto err;
if (sublist == 0)
has_block = 1;
in_empty = 0;
}
/*
* Adding the line without prefix into the working
* buffer.
*/
if (!hbuf_put(work, data + beg + i, end - beg - i))
goto err;
beg = end;
}
/* Increment number of items in parent. */
if (doc->current != NULL && doc->current->type == LOWDOWN_LIST)
doc->current->rndr_list.items++;
/* Render of list item contents. */
if (has_block)
*flags |= HLIST_FL_BLOCK;
#if 0
/*
* If we're in a block but we weren't offset by a newline (e.g.,
* by having a list immediately following the list instead of
* separated by a newline), then mark this as a "semiblock" that
* is a block without whitespace. TODO: this still needs work.
*/
if (has_block && has_initial_newline < 2)
*flags |= HLIST_FL_SEMIBLOCK;
#endif
if ((n = pushnode(doc, LOWDOWN_LISTITEM)) == NULL)
goto err;
n->rndr_listitem.flags = *flags;
n->rndr_listitem.num = num;
if (checked > 0)
n->rndr_listitem.flags |= HLIST_FL_CHECKED;
else if (checked == 0)
n->rndr_listitem.flags |= HLIST_FL_UNCHECKED;
if (*flags & HLIST_FL_BLOCK) {
if (sublist && sublist < work->size) {
if (!parse_block(doc,
work->data, sublist))
goto err;
if (!parse_block(doc,
work->data + sublist,
work->size - sublist))
goto err;
} else {
if (!parse_block(doc,
work->data, work->size))
goto err;
}
} else {
if (sublist && sublist < work->size) {
if (!parse_inline(doc,
work->data, sublist))
goto err;
if (!parse_block(doc,
work->data + sublist,
work->size - sublist))
goto err;
} else {
if (!parse_inline(doc,
work->data, work->size))
goto err;
}
}
popnode(doc, n);
hbuf_free(work);
return beg;
err:
hbuf_free(work);
return -1;
}
/*
* Parse definition list.
* This must follow a single-line paragraph, which it integrates as the
* title of the list.
* (The paragraph can contain arbitrary styling.)
*/
static ssize_t
parse_definition(struct lowdown_doc *doc, char *data, size_t size)
{
struct lowdown_buf *work = NULL;
size_t i = 0, k = 1;
ssize_t ret;
enum hlist_fl flags = HLIST_FL_DEF;
struct lowdown_node *n, *nn, *cur, *prev;
if ((work = hbuf_new(256)) == NULL)
goto err;
/* Record whether we want to start in block mode. */
cur = TAILQ_LAST(&doc->current->children, lowdown_nodeq);
if (cur->rndr_paragraph.beoln)
flags |= HLIST_FL_BLOCK;
/* Do we need to merge into a previous definition list? */
prev = TAILQ_PREV(cur, lowdown_nodeq, entries);
if (prev != NULL && prev->type == LOWDOWN_DEFINITION) {
n = doc->current = prev;
flags |= n->rndr_definition.flags;
doc->depth++;
} else {
n = pushnode(doc, LOWDOWN_DEFINITION);
if (n == NULL)
goto err;
n->rndr_definition.flags = flags;
}
TAILQ_REMOVE(&cur->parent->children, cur, entries);
TAILQ_INSERT_TAIL(&n->children, cur, entries);
cur->type = LOWDOWN_DEFINITION_TITLE;
cur->parent = n;
while (i < size) {
nn = pushnode(doc, LOWDOWN_DEFINITION_DATA);
if (nn == NULL)
goto err;
ret = parse_listitem(work, doc,
data + i, size - i, &flags, k++);
if (ret < 0)
goto err;
i += ret;
popnode(doc, nn);
if (ret == 0 || (flags & HLIST_LI_END))
break;
}
if (flags & HLIST_FL_BLOCK)
n->rndr_definition.flags |= HLIST_FL_BLOCK;
popnode(doc, n);
hbuf_free(work);
return i;
err:
hbuf_free(work);
return -1;
}
/*
* Parsing ordered or unordered list block.
* If "oli_data" is not NULL, it's the numeric string prefix of the
* ordered entry. It's either zero-length or well-formed.
*/
static ssize_t
parse_list(struct lowdown_doc *doc,
char *data, size_t size, const char *oli_data)
{
struct lowdown_buf *work = NULL;
size_t i = 0, pos;
ssize_t ret;
enum hlist_fl flags;
struct lowdown_node *n;
flags = oli_data != NULL ?
HLIST_FL_ORDERED : HLIST_FL_UNORDERED;
if ((work = hbuf_new(256)) == NULL)
goto err;
if ((n = pushnode(doc, LOWDOWN_LIST)) == NULL)
goto err;
n->rndr_list.start = 1;
n->rndr_list.flags = flags;
if (oli_data != NULL && oli_data[0] != '\0') {
n->rndr_list.start = strtonum
(oli_data, 0, UINT32_MAX, NULL);
if (n->rndr_list.start == 0)
n->rndr_list.start = 1;
}
pos = n->rndr_list.start;
while (i < size) {
ret = parse_listitem(work, doc,
data + i, size - i, &flags, pos++);
if (ret < 0)
goto err;
i += ret;
if (ret == 0 || (flags & HLIST_LI_END))
break;
}
if (flags & HLIST_FL_BLOCK)
n->rndr_list.flags |= HLIST_FL_BLOCK;
popnode(doc, n);
hbuf_free(work);
return i;
err:
hbuf_free(work);
return -1;
}
/*
* Parsing of atx-style headers.
*/
static ssize_t
parse_atxheader(struct lowdown_doc *doc, char *data, size_t size)
{
size_t level = 0, i, end, skip;
struct lowdown_node *n;
while (level < size && level < 6 && data[level] == '#')
level++;
i = countspaces(data, level, size, 0);
for (end = i; end < size && data[end] != '\n'; end++)
continue;
skip = end;
while (end && data[end - 1] == '#')
end--;
while (end && data[end - 1] == ' ')
end--;
if (end > i) {
if ((n = pushnode(doc, LOWDOWN_HEADER)) == NULL)
return -1;
assert(level > 0);
n->rndr_header.level = level - 1;
if (!parse_inline(doc, data + i, end - i))
return -1;
popnode(doc, n);
if ((doc->ext_flags & LOWDOWN_ATTRS) &&
!parse_header_ext_attrs(n))
return -1;
}
return skip;
}
/*
* Check for end of HTML block : </tag>( *)\n
* Returns tag length on match, 0 otherwise.
* Assumes data starts with "<".
*/
static size_t
html_is_end(const char *tag, size_t tag_len,
struct lowdown_doc *doc, const char *data, size_t size)
{
size_t i = tag_len + 3, w;
/*
* Try to match the end tag
* Note: we're not considering tags like "</tag >" which are
* still valid.
*/
if (i > size ||
data[1] != '/' ||
strncasecmp(data + 2, tag, tag_len) != 0 ||
data[tag_len + 2] != '>')
return 0;
/* Rest of the line must be empty. */
if ((w = is_empty(data + i, size - i)) == 0 && i < size)
return 0;
return i + w;
}
/*
* Try to find HTML block ending tag.
* Returns the length on match, 0 otherwise.
*/
static size_t
html_find_end(const char *tag, size_t tag_len,
struct lowdown_doc *doc, const char *data, size_t size)
{
size_t i, w = 0;
for (i = 0; ; i++) {
while (i < size && data[i] != '<')
i++;
if (i >= size)
return 0;
w = html_is_end(tag, tag_len, doc, data + i, size - i);
if (w)
break;
}
return i + w;
}
/*
* Try to find end of HTML block in strict mode (it must be an
* unindented line, and have a blank line afterwards).
* Returns the length on match, 0 otherwise.
*/
static size_t
html_find_end_strict(const char *tag, size_t tag_len,
struct lowdown_doc *doc, const char *data, size_t size)
{
size_t i = 0, mark;
while (1) {
mark = i;
while (i < size && data[i] != '\n')
i++;
if (i < size)
i++;
if (i == mark)
return 0;
if (data[mark] == ' ' && mark > 0)
continue;
mark += html_find_end(tag, tag_len,
doc, data + mark, i - mark);
if (mark == i &&
(is_empty(data + i, size - i) || i >= size))
break;
}
return i;
}
/*
* See if the sequence of length "len" bytes in "str" is a void element.
* Return zero if not, else the number of bytes until one after end of
* the HTML string.
*/
static size_t
html_is_void_element(const char *str, size_t len)
{
size_t i, sz;
static const char *tags[] = {
"br",
"hr",
"link",
"meta",
NULL
};
for (i = 0; tags[i] != NULL; i++) {
sz = strlen(tags[i]);
if (len < sz || strncasecmp(tags[i], str, sz) != 0)
continue;
for ( ; sz < len && str[sz] != '>'; sz++)
/* Do nothing. */ ;
return sz < len ? sz + 1 : 0;
}
return 0;
}
/*
* Canonicalise a sequence of length "len" bytes in "str". This returns
* NULL if the sequence is not recognised, or a NUL-terminated string of
* the sequence otherwise.
*/
static const char *
html_find_block(const char *str, size_t len)
{
size_t i;
static const char *tags[] = {
"address",
"article",
"aside",
"blockquote",
"del",
"details",
"dialog",
"dd",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"iframe",
"ins",
"li",
"main",
"math",
"nav",
"noscript",
"ol",
"p",
"pre",
"section",
"script",
"style",
"table",
"ul",
NULL,
};
for (i = 0; tags[i] != NULL; i++)
if (strncasecmp(tags[i], str, len) == 0)
return tags[i];
return NULL;
}
/*
* Parsing of inline HTML block.
* Return <0 on failure, >0 on success, 0 if not a block.
*/
static ssize_t
parse_htmlblock(struct lowdown_doc *doc, char *data, size_t size)
{
struct lowdown_buf work;
size_t i, j = 0, tag_len, tag_end;
const char *curtag = NULL;
struct lowdown_node *n;
memset(&work, 0, sizeof(struct lowdown_buf));
work.data = data;
/* Identification of the opening tag. */
if (size < 2 || data[0] != '<')
return 0;
i = 1;
while (i < size && data[i] != '>' && data[i] != ' ')
i++;
if (i < size)
curtag = html_find_block(data + 1, i - 1);
/* Handling of special cases. */
if (curtag == NULL) {
/*
* HTML comment.
* This is anything between <!-- and -->.
*/
if (size > 5 && data[1] == '!' &&
data[2] == '-' && data[3] == '-') {
i = 5;
while (i < size && !(data[i - 2] == '-' &&
data[i - 1] == '-' && data[i] == '>'))
i++;
i++;
if (i < size)
j = is_empty(data + i, size - i);
if (j) {
n = pushnode(doc, LOWDOWN_BLOCKHTML);
if (n == NULL)
return -1;
work.size = i + j;
if (!hbuf_createb
(&n->rndr_blockhtml.text, &work))
return -1;
popnode(doc, n);
return work.size;
}
}
/*
* Void elements. These can either end directly in ">"
* or "/>". Push everything between the brackets.
*/
i = html_is_void_element(data + 1, size - 1);
if (i > 0) {
i++;
j = is_empty(data + i, size - i);
if (j) {
n = pushnode(doc, LOWDOWN_BLOCKHTML);
if (n == NULL)
return -1;
work.size = i + j;
if (!hbuf_createb
(&n->rndr_blockhtml.text, &work))
return -1;
popnode(doc, n);
return work.size;
}
}
/* No special case recognised. */
return 0;
}
/* Looking for a matching closing tag in strict mode. */
tag_len = strlen(curtag);
tag_end = html_find_end_strict
(curtag, tag_len, doc, data, size);
/*
* If not found, trying a second pass looking for indented match
* but not if tag is "ins" or "del" (following original
* Markdown.pl).
*/
if (!tag_end &&
strcmp(curtag, "ins") != 0 && strcmp(curtag, "del") != 0)
tag_end = html_find_end
(curtag, tag_len, doc, data, size);
if (!tag_end)
return 0;
/* The end of the block has been found. */
n = pushnode(doc, LOWDOWN_BLOCKHTML);
if (n == NULL)
return -1;
work.size = tag_end;
if (!hbuf_createb(&n->rndr_blockhtml.text, &work))
return -1;
popnode(doc, n);
return tag_end;
}
/*
* Parse a table row.
* Return zero on failure, non-zero on success.
*/
static int
parse_table_row(struct lowdown_buf *ob, struct lowdown_doc *doc,
char *data, size_t size, size_t columns,
const enum htbl_flags *col_data, enum htbl_flags header_flag)
{
size_t i = 0, col, len, cell_start, cell_end;
struct lowdown_buf empty_cell;
struct lowdown_node *n, *nn;
if (i < size && data[i] == '|')
i++;
if ((n = pushnode(doc, LOWDOWN_TABLE_ROW)) == NULL)
return 0;
for (col = 0; col < columns && i < size; ++col) {
while (i < size && xisspace(data[i]))
i++;
cell_start = i;
len = find_emph_char(data + i, size - i, '|');
/*
* Two possibilities for len == 0:
* (1) No more pipe char found in the current line.
* (2) The next pipe is right after the current one,
* i.e. empty cell.
* For case 1, we skip to the end of line; for case 2 we
* just continue.
*/
if (len == 0 && i < size && data[i] != '|')
len = size - i;
i += len;
cell_end = i - 1;
while (cell_end > cell_start &&
xisspace(data[cell_end]))
cell_end--;
nn = pushnode(doc, LOWDOWN_TABLE_CELL);
if (nn == NULL)
return 0;
nn->rndr_table_cell.flags = col_data[col] | header_flag;
nn->rndr_table_cell.col = col;
nn->rndr_table_cell.columns = columns;
if (!parse_inline(doc,
data + cell_start, 1 + cell_end - cell_start))
return 0;
popnode(doc, nn);
i++;
}
for ( ; col < columns; ++col) {
memset(&empty_cell, 0, sizeof(struct lowdown_buf));
nn = pushnode(doc, LOWDOWN_TABLE_CELL);
if (nn == NULL)
return 0;
nn->rndr_table_cell.flags = col_data[col] | header_flag;
nn->rndr_table_cell.col = col;
nn->rndr_table_cell.columns = columns;
popnode(doc, nn);
}
popnode(doc, n);
return 1;
}
/*
* Parse the initial line of a table.
* Return <0 on failure, 0 if not a table row, >0 for the offset.
*/
static ssize_t
parse_table_header(struct lowdown_node **np,
struct lowdown_buf *ob, struct lowdown_doc *doc,
char *data, size_t size, size_t *columns,
enum htbl_flags **column_data)
{
size_t i = 0, col, header_end, under_end,
dashes;
ssize_t pipes = 0;
struct lowdown_node *n;
/*
* Parse the number of cells in the header by looking at the
* number of delimiters (pipes). Disregard those on the
* beginning and end of the line, and escaped ones.
*/
for ( ; i < size && data[i] != '\n'; i++)
if (data[i] == '|' &&
(i == 0 || data[i - 1] != '\\'))
pipes++;
if (i == size || pipes == 0)
return 0;
header_end = i;
while (header_end > 0 && xisspace(data[header_end - 1]))
header_end--;
if (data[0] == '|')
pipes--;
if (header_end && data[header_end - 1] == '|' &&
(header_end < 2 || data[header_end - 2] != '\\'))
pipes--;
if (pipes < 0)
return 0;
*columns = pipes + 1;
*column_data = calloc(*columns, sizeof(enum htbl_flags));
if (*column_data == NULL)
return -1;
/* Parse the header underline */
i++;
if (i < size && data[i] == '|')
i++;
under_end = i;
while (under_end < size && data[under_end] != '\n')
under_end++;
for (col = 0; col < *columns && i < under_end; ++col) {
dashes = 0;
i = countspaces(data, i, under_end, 0);
if (data[i] == ':') {
i++;
(*column_data)[col] |= HTBL_FL_ALIGN_LEFT;
dashes++;
}
while (i < under_end && data[i] == '-') {
i++;
dashes++;
}
if (i < under_end && data[i] == ':') {
i++;
(*column_data)[col] |= HTBL_FL_ALIGN_RIGHT;
dashes++;
}
i = countspaces(data, i, under_end, 0);
if (i < under_end && data[i] != '|' && data[i] != '+')
break;
/*
* At one point, three dashes/colons were required for a
* cell to register. At some point, this restriction
* was lifted and now only one is required.
*/
if (dashes == 0)
break;
i++;
}
if (col < *columns)
return 0;
/* (This calls pushnode for the table row.) */
*np = pushnode(doc, LOWDOWN_TABLE_BLOCK);
if (*np == NULL)
return -1;
(*np)->rndr_table.columns = *columns;
n = pushnode(doc, LOWDOWN_TABLE_HEADER);
if (n == NULL)
return -1;
n->rndr_table_header.flags = calloc
(*columns, sizeof(enum htbl_flags));
if (n->rndr_table_header.flags == NULL)
return -1;
for (i = 0; i < *columns; i++)
n->rndr_table_header.flags[i] = (*column_data)[i];
n->rndr_table_header.columns = *columns;
if (!parse_table_row(ob, doc, data, header_end,
*columns, *column_data, HTBL_FL_HEADER))
return -1;
popnode(doc, n);
return under_end + 1;
}
/*
* Parse a table block.
* Return <0 on failure, zero if not a table, >0 offset otherwise.
*/
static ssize_t
parse_table(struct lowdown_doc *doc, char *data, size_t size)
{
size_t i, columns, row_start, pipes;
ssize_t ret;
struct lowdown_buf *header_work = NULL, *body_work = NULL;
enum htbl_flags *col_data = NULL;
struct lowdown_node *n = NULL, *nn;
if ((header_work = hbuf_new(64)) == NULL ||
(body_work = hbuf_new(256)) == NULL)
goto err;
ret = parse_table_header(&n, header_work,
doc, data, size, &columns, &col_data);
if (ret < 0)
goto err;
if ((i = ret) > 0) {
nn = pushnode(doc, LOWDOWN_TABLE_BODY);
if (nn == NULL)
goto err;
while (i < size) {
pipes = 0;
row_start = i;
while (i < size && data[i] != '\n')
if (data[i++] == '|')
pipes++;
if (pipes == 0 || i == size) {
i = row_start;
break;
}
if (!parse_table_row(body_work,
doc, data + row_start, i - row_start,
columns, col_data, 0))
goto err;
i++;
}
popnode(doc, nn);
popnode(doc, n);
}
free(col_data);
hbuf_free(header_work);
hbuf_free(body_work);
return i;
err:
free(col_data);
hbuf_free(header_work);
hbuf_free(body_work);
return -1;
}
/*
* Parsing of one block, returning next char to parse.
* We can assume, entering the block, that our output is newline
* aligned.
* Return zero on failure, non-zero on success.
*/
static int
parse_block(struct lowdown_doc *doc, char *data, size_t size)
{
size_t beg = 0, end, i;
char *txt_data;
char oli_data[10];
struct lowdown_node *n;
ssize_t rc;
/*
* What kind of block are we?
* Go through all types of blocks, one by one.
*/
while (beg < size) {
txt_data = data + beg;
end = size - beg;
/* We are at a #header. */
if (is_atxheader(doc, txt_data, end)) {
rc = parse_atxheader(doc, txt_data, end);
if (rc < 0)
return 0;
assert(rc > 0);
beg += rc;
continue;
}
/* We have some <HTML>. */
if (data[beg] == '<') {
rc = parse_htmlblock(doc, txt_data, end);
if (rc > 0) {
beg += rc;
continue;
} else if (rc < 0)
return 0;
}
/* Empty line. */
if ((i = is_empty(txt_data, end)) != 0) {
beg += i;
continue;
}
/* Horizontal rule. */
if (is_hrule(txt_data, end)) {
n = pushnode(doc, LOWDOWN_HRULE);
if (n == NULL)
return 0;
while (beg < size && data[beg] != '\n')
beg++;
beg++;
popnode(doc, n);
continue;
}
/* Fenced code. */
if (doc->ext_flags & LOWDOWN_FENCED) {
rc = parse_fencedcode(doc, txt_data, end);
if (rc > 0) {
beg += rc;
continue;
} else if (rc < 0)
return 0;
}
/* Table parsing. */
if (doc->ext_flags & LOWDOWN_TABLES) {
rc = parse_table(doc, txt_data, end);
if (rc > 0) {
beg += rc;
continue;
} else if (rc < 0)
return 0;
}
/* We're a > block quote. */
if (prefix_quote(txt_data, end)) {
rc = parse_blockquote(doc, txt_data, end);
if (rc < 0)
return 0;
beg += rc;
continue;
}
/* Prefixed code (like block-quotes). */
if (!(doc->ext_flags & LOWDOWN_NOCODEIND) &&
prefix_code(txt_data, end)) {
rc = parse_blockcode(doc, txt_data, end);
if (rc < 0)
return 0;
beg += rc;
continue;
}
/* Some sort of unordered list. */
if (prefix_uli(doc, txt_data, end, NULL)) {
rc = parse_list(doc, txt_data, end, NULL);
if (rc < 0)
return 0;
beg += rc;
continue;
}
/*
* A definition list.
* Only use this is preceded by a one-line paragraph.
*/
if (doc->current != NULL &&
prefix_dli(doc, txt_data, end)) {
n = TAILQ_LAST(&doc->current->children,
lowdown_nodeq);
if (n != NULL &&
n->type == LOWDOWN_PARAGRAPH &&
n->rndr_paragraph.lines == 1) {
rc = parse_definition(doc, txt_data, end);
if (rc < 0)
return 0;
beg += rc;
continue;
}
}
/* An ordered list. */
if (prefix_oli(doc, txt_data, end, oli_data)) {
rc = parse_list(doc, txt_data, end, oli_data);
if (rc < 0)
return 0;
beg += rc;
continue;
}
/* No match: just a regular paragraph. */
if ((rc = parse_paragraph(doc, txt_data, end)) < 0)
return 0;
beg += rc;
}
return 1;
}
/*
* Returns >0 if a line is a footnote definition, 0 if not, <0 on
* failure. This gathers any footnote content into the footq footnote
* queue.
*/
static int
is_footnote(struct lowdown_doc *doc, const char *data,
size_t beg, size_t end, size_t *last)
{
size_t i = 0, ind = 0, start = 0,
id_offs, id_end;
struct lowdown_buf *contents = NULL;
int in_empty = 0;
struct foot_ref *ref = NULL;
/* up to 3 optional leading spaces */
if (beg + 3 >= end)
return 0;
i = countspaces(data, beg, end, 3);
/* id part: caret followed by anything between brackets */
if (data[i] != '[')
return 0;
i++;
if (i >= end || data[i] != '^')
return 0;
i++;
id_offs = i;
while (i < end && data[i] != '\n' && data[i] != ']')
i++;
if (i >= end || data[i] != ']')
return 0;
id_end = i;
/* spacer: colon (space | tab)* newline? (space | tab)* */
i++;
if (i >= end || data[i] != ':')
return 0;
i++;
/* getting content buffer */
if ((contents = hbuf_new(64)) == NULL)
return -1;
start = i;
/* process lines similar to a list item */
while (i < end) {
while (i < end && data[i] != '\n')
i++;
/* process an empty line */
if (is_empty(data + start, i - start)) {
in_empty = 1;
if (i < end && data[i] == '\n')
i++;
start = i;
continue;
}
/* calculating the indentation */
ind = countspaces(data, start, end, 4) - start;
/* joining only indented stuff after empty lines;
* note that now we only require 1 space of indentation
* to continue, just like lists */
if (ind == 0) {
if (start == id_end + 2 &&
data[start] == '\t') {
/* XXX: wtf? */
} else
break;
} else if (in_empty)
if (!hbuf_putc(contents, '\n'))
goto err;
in_empty = 0;
/* adding the line into the content buffer */
if (!hbuf_put(contents,
data + start + ind, i - start - ind))
goto err;
/* add carriage return */
if (i < end) {
if (!hbuf_putc(contents, '\n'))
goto err;
if (i < end && data[i] == '\n')
i++;
}
start = i;
}
if (last)
*last = start;
if ((ref = calloc(1, sizeof(struct foot_ref))) == NULL)
goto err;
TAILQ_INSERT_TAIL(&doc->footq, ref, entries);
if (!hbuf_createb(&ref->contents, contents))
return -1;
if (!hbuf_create(&ref->name, data + id_offs, id_end - id_offs))
return -1;
hbuf_free(contents);
return 1;
err:
hbuf_free(contents);
return -1;
}
/*
* Returns >0 if the line is a reference, 0 if not, <0 on failure.
*/
static int
is_ref(struct lowdown_doc *doc, const char *data,
size_t beg, size_t end, size_t *last)
{
size_t i, id_offset, id_end, link_offset, link_end,
title_offset = 0, title_end = 0, line_end,
garbage, attr_offset = 0, attr_end = 0;
struct link_ref *ref;
/* Up to 3 optional leading spaces. */
if (beg + 3 >= end)
return 0;
i = countspaces(data, beg, end, 3);
/* Id part: anything but a newline between brackets. */
if (data[i] != '[')
return 0;
i++;
id_offset = i;
while (i < end && data[i] != '\n' && data[i] != ']')
i++;
if (i >= end || data[i] != ']')
return 0;
id_end = i;
/* Spacer: colon (space | tab)* newline? (space | tab)* */
i++;
if (i >= end || data[i] != ':')
return 0;
i++;
i = countspaces(data, i, end, 0);
if (i < end && data[i] == '\n')
i++;
i = countspaces(data, i, end, 0);
if (i >= end)
return 0;
/*
* Link: spacing-free sequence, optionally between angle
* brackets.
*/
if (data[i] == '<')
i++;
link_offset = i;
while (i < end && data[i] != ' ' && data[i] != '\n')
i++;
if (data[i - 1] == '>')
link_end = i - 1;
else
link_end = i;
/*
* Space: (space | tab)* (newline | '\'' | '"' | '(' )
* Optionally '{' for attributes.
*/
i = countspaces(data, i, end, 0);
if (doc->ext_flags & LOWDOWN_ATTRS) {
if (i < end && data[i] != '\n' &&
data[i] != '\'' && data[i] != '"' &&
data[i] != '(' && data[i] != '{')
return 0;
} else {
if (i < end && data[i] != '\n' &&
data[i] != '\'' && data[i] != '"' &&
data[i] != '(')
return 0;
}
line_end = 0;
/* computing end-of-line */
if (i >= end || data[i] == '\n')
line_end = i;
/* optional (space|tab)* spacer after a newline */
if (line_end)
i = countspaces(data, line_end + 1, end, 0);
/*
* Optional title: any non-newline sequence enclosed in '"()
* alone on its line. This is... confusing, because we can have
* any number of embedded delimiters in the text and only the
* last one is valid.
*
* [link1]: moo.com "hello "world" (hi) there
* ^last
*
* The rule is that there must be only spaces between the last
* delimiter, whatever it is, and the newline OR opening curly
* brace (if parsing), which signifies extended attributes.
*/
if (i + 1 < end &&
(data[i] == '\'' || data[i] == '"' || data[i] == '(')) {
title_offset = ++i;
for (garbage = 0; i < end; i++) {
if (data[i] == '\'' || data[i] == '"' ||
data[i] == ')') {
title_end = i;
garbage = 0;
continue;
}
if (data[i] == '\n' ||
((doc->ext_flags & LOWDOWN_ATTRS) &&
data[i] == '{'))
break;
if (data[i] != ' ')
garbage = 1;
}
if (garbage)
return 0;
}
/*
* Now optionally the attributes. These use similar semantics
* where there can be any number of embedded delimiters: only
* the last one is recorded, and there may be no garbage between
* it and the newline.
*/
if ((doc->ext_flags & LOWDOWN_ATTRS) &&
i + 1 < end && data[i] == '{') {
attr_offset = ++i;
for (garbage = 0; i < end; i++) {
if (data[i] == '}') {
attr_end = i;
garbage = 0;
continue;
}
if (data[i] == '\n')
break;
if (data[i] != ' ')
garbage = 1;
}
if (garbage)
return 0;
}
line_end = i;
/* Garbage after the link or empty link. */
if (!line_end || link_end == link_offset)
return 0;
/* A valid ref has been found, filling-in return structures. */
if (last)
*last = line_end;
if ((ref = calloc(1, sizeof(struct link_ref))) == NULL)
return -1;
TAILQ_INSERT_TAIL(&doc->refq, ref, entries);
if (id_end - id_offset) {
ref->name = hbuf_new(id_end - id_offset);
if (ref->name == NULL)
return -1;
if (!hbuf_put(ref->name,
data + id_offset, id_end - id_offset))
return -1;
}
ref->link = hbuf_new(link_end - link_offset);
if (ref->link == NULL)
return -1;
if (!hbuf_put(ref->link,
data + link_offset, link_end - link_offset))
return -1;
if (title_end > title_offset) {
ref->title = hbuf_new(title_end - title_offset);
if (ref->title == NULL)
return -1;
if (!hbuf_put(ref->title,
data + title_offset, title_end - title_offset))
return -1;
}
if (attr_end > attr_offset) {
ref->attrs = hbuf_new(attr_end - attr_offset);
if (ref->attrs == NULL)
return -1;
if (!hbuf_put(ref->attrs,
data + attr_offset, attr_end - attr_offset))
return -1;
}
return 1;
}
/*
* Replace tabs with 4 spaces.
* Return zero on failure (memory), non-zero on success.
*/
static int
expand_tabs(struct lowdown_buf *ob, const char *line, size_t size)
{
size_t i, tab = 0, org;
/*
* This code makes two assumptions:
*
* (1) Input is valid UTF-8. (Any byte with top two bits 10 is
* skipped, whether or not it is a valid UTF-8 continuation
* byte.)
* (2) Input contains no combining characters. (Combining
* characters should be skipped but are not.)
*/
for (i = 0; i < size; i++) {
org = i;
while (i < size && line[i] != '\t') {
/* ignore UTF-8 continuation bytes */
if ((line[i] & 0xc0) != 0x80)
tab++;
i++;
}
if (i > org && !hbuf_put(ob, line + org, i - org))
return 0;
if (i >= size)
break;
do {
if (!hbuf_putc(ob, ' '))
return 0;
tab++;
} while (tab % 4);
}
return 1;
}
struct lowdown_doc *
lowdown_doc_new(const struct lowdown_opts *opts)
{
struct lowdown_doc *doc;
size_t i;
doc = calloc(1, sizeof(struct lowdown_doc));
if (doc == NULL)
return NULL;
doc->ext_flags = opts == NULL ? 0 : opts->feat;
doc->maxdepth = opts == NULL ? 128 : opts->maxdepth;
doc->active_char['*'] = MD_CHAR_EMPHASIS;
doc->active_char['_'] = MD_CHAR_EMPHASIS;
if (doc->ext_flags & LOWDOWN_HILITE)
doc->active_char['='] = MD_CHAR_EMPHASIS;
doc->active_char['`'] = MD_CHAR_CODESPAN;
doc->active_char['\n'] = MD_CHAR_LINEBREAK;
doc->active_char['['] = MD_CHAR_LINK;
doc->active_char['!'] = MD_CHAR_IMAGE;
doc->active_char['<'] = MD_CHAR_LANGLE;
doc->active_char['\\'] = MD_CHAR_ESCAPE;
doc->active_char['&'] = MD_CHAR_ENTITY;
if (doc->ext_flags & LOWDOWN_AUTOLINK) {
doc->active_char[':'] = MD_CHAR_AUTOLINK_URL;
doc->active_char['@'] = MD_CHAR_AUTOLINK_EMAIL;
doc->active_char['w'] = MD_CHAR_AUTOLINK_WWW;
}
if (doc->ext_flags & LOWDOWN_SUPER) {
doc->active_char['^'] = MD_CHAR_SUPERSCRIPT;
doc->active_char['~'] = MD_CHAR_SUBSCRIPT;
} else if (doc->ext_flags & LOWDOWN_STRIKE)
doc->active_char['~'] = MD_CHAR_EMPHASIS;
if (doc->ext_flags & LOWDOWN_MATH)
doc->active_char['$'] = MD_CHAR_MATH;
if (opts != NULL && opts->metasz > 0) {
doc->meta = calloc(opts->metasz, sizeof(char *));
if (doc->meta == NULL)
goto err;
doc->metasz = opts->metasz;
for (i = 0; i < doc->metasz; i++) {
doc->meta[i] = strdup(opts->meta[i]);
if (doc->meta[i] == NULL)
goto err;
}
}
if (opts != NULL && opts->metaovrsz > 0) {
doc->metaovr = calloc(opts->metaovrsz, sizeof(char *));
if (doc->metaovr == NULL)
goto err;
doc->metaovrsz = opts->metaovrsz;
for (i = 0; i < doc->metaovrsz; i++) {
doc->metaovr[i] = strdup(opts->metaovr[i]);
if (doc->metaovr[i] == NULL)
goto err;
}
}
return doc;
err:
lowdown_doc_free(doc);
return NULL;
}
/*
* Add a metadata key-value pair. The value is either length of "vsz"
* or, if zero, it's calculated from strlen(). Existing entries by the
* same key name are removed both from doc->metaq and the document tree.
* Returns zero on failure (memory allocation), non-zero on success.
*/
static int
add_metadata(struct lowdown_doc *doc, const char *key,
const char *val, size_t vsz)
{
struct lowdown_meta *m;
struct lowdown_node *n, *nn;
size_t nksz, nvsz;
nksz = strlen(key);
nvsz = vsz == 0 ? strlen(val) : vsz;
TAILQ_FOREACH(m, doc->metaq, entries)
if (strcmp(m->key, key) == 0) {
TAILQ_REMOVE(doc->metaq, m, entries);
free(m->key);
free(m->value);
free(m);
break;
}
assert(doc->current->type == LOWDOWN_DOC_HEADER);
TAILQ_FOREACH(n, &doc->current->children, entries) {
assert(n->type == LOWDOWN_META);
if (!hbuf_streq(&n->rndr_meta.key, key))
continue;
TAILQ_REMOVE(&doc->current->children, n, entries);
lowdown_node_free(n);
break;
}
if ((n = pushnode(doc, LOWDOWN_META)) == NULL)
return 0;
if (!hbuf_create(&n->rndr_meta.key, key, nksz))
return 0;
if ((m = calloc(1, sizeof(struct lowdown_meta))) == NULL)
return 0;
TAILQ_INSERT_TAIL(doc->metaq, m, entries);
if ((m->key = strndup(key, nksz)) == NULL)
return 0;
if ((m->value = strndup(val, nvsz)) == NULL)
return 0;
/* In case there are NUL values... */
nvsz = strlen(m->value);
/* Strip trailing newlines. */
while (nvsz > 0 && m->value[nvsz - 1] == '\n')
nvsz--;
if (nvsz > 0) {
if ((nn = pushnode(doc, LOWDOWN_NORMAL_TEXT)) == NULL)
return 0;
if (!hbuf_push(&nn->rndr_normal_text.text, val, nvsz))
return 0;
popnode(doc, nn);
}
popnode(doc, n);
return 1;
}
/*
* Parse a MMD metadata value. If the value spans multiple lines,
* leading whitespace from the first line will be stripped and any
* following lines will be taken as is. Returns a pointer to the value
* within the data * and the length of the value will be written to
* "len". Never returns NULL.
*/
static const char *
parse_metadata_mmd_val(const char *data, size_t sz, size_t *len)
{
const char *val;
size_t i, peek = 0;
int startws;
/* Skip leading whitespace. */
i = countspaces(data, 0, sz, 0);
val = data;
sz -= i;
/* Find end of line. */
for (i = 0; i < sz && data[i] != '\n'; i++)
continue;
*len = i;
/*
* Iterate through zero or more following multilines.
* Multilines are terminated by a line containing a colon (that
* is not offset by whitespace) or a blank line.
*/
startws = i + 1 < sz &&
(data[i + 1] == ' ' ||
data[i + 1] == '\t');
for (i++; i < sz; i++) {
/*
* This block is executed within the line.
* We use "peek" to see how far into the line we are;
* thus, if we encounter a colon without leading
* whitespace, we know that we're in the next metadata
* and should stop.
*/
if (startws == 0 && data[i] == ':')
break;
peek++;
if (data[i] != '\n')
continue;
/*
* We're at a newline: start the loop again by seeing if
* the next line starts with whitespace.
*/
*len += peek;
peek = 0;
/*
* YAML blocks may contain superfluous newlines. If
* we're at such a line, continue after all the
* newlines: we'll strip them out when parsing.
*/
if (i + 1 < sz && data[i + 1] == '\n') {
for (++i; i < sz && data[i] == '\n'; i++)
(*len)++;
break;
}
/* Check if the next line has leading whitespace. */
startws = i + 1 < sz &&
(data[i + 1] == ' ' ||
data[i + 1] == '\t');
}
/* Last metadata in section. */
if (i == sz && peek)
*len += peek + 1;
return val;
}
/*
* Parse key-value metadata pairs from a MMD metadata block "data" of
* size "sz". Store the output in the doc's "metaq" as well as in the
* tree. If "is_yaml" is non-zero, the block passed in is bracketed by
* YAML markers; otherwise, it's optionally trailed by newlines.
* Returns 0 if this is not MMD metadata, >0 of it is, <0 on failure.
*/
static int
parse_metadata_mmd(struct lowdown_doc *doc, const char *data,
size_t sz, int is_yaml)
{
size_t i, j, pos = 0, vsz, keysz;
const char *val, *key;
char *cp, *buf;
/*
* If a YAML block, strip the leading and ending delimiter.
* Otherwise, strip trailing newlines.
*/
if (is_yaml) {
assert(sz > 9);
data += 4;
sz -= 9;
} else
while (sz && (data[sz - 1] == '\n'))
sz--;
if (sz == 0)
return 0;
/*
* Check the first line for a colon to see if we should do
* metadata parsing at all.
* This is a convenience for regular markdown so that initial
* lines (not headers) don't get sucked into metadata.
*/
for (pos = 0; pos < sz; pos++)
if (data[pos] == '\n' || data[pos] == ':')
break;
if (pos == sz || data[pos] == '\n')
return 0;
/* Extract all keys and values... */
for (pos = 0; pos < sz; ) {
key = &data[pos];
for (i = pos; i < sz; i++)
if (data[i] == ':')
break;
keysz = i - pos;
if ((cp = buf = malloc(keysz + 1)) == NULL)
return -1;
/*
* Normalise the key to lowercase alphanumerics, "-",
* and "_" by discarding whitespace and replacing
* non-conforming characters with an underscore.
*/
for (j = 0; j < keysz; j++) {
if (isalnum((unsigned char)key[j]) ||
'-' == key[j] || '_' == key[j]) {
*cp++ = tolower((unsigned char)key[j]);
continue;
} else if (isspace((unsigned char)key[j]))
continue;
*cp++ = '_';
}
*cp = '\0';
/*
* Skip over the colon and subsequent space. If already
* at the end of line, do nothing.
*/
assert(i == sz || data[i] == ':');
i++;
while (i < sz && isspace((unsigned char)data[i]))
i++;
/* Add the metadata or a blank value if not given. */
if (i >= sz) {
vsz = 0;
if (!add_metadata(doc, buf, "", 0)) {
free(buf);
return -1;
}
} else {
val = parse_metadata_mmd_val
(&data[i], sz - i, &vsz);
assert(val != NULL);
if (!add_metadata(doc, buf, val, vsz)) {
free(buf);
return -1;
}
}
free(buf);
/*
* This will just tip over the size if we've gone beyond
* our boundaries, ending the loop w/o side effects.
*/
pos = i + vsz + 1;
}
return 1;
}
/*
* Parse a pandoc metadata value. Returns an allocated pointer to the
* value and the length of the value will be written to "pos". If
* "strip_semis" is set, semicolons are converted to double-spaces.
* Returns NULL on allocation failure. If the entry is empty (just a
* percent sign) or omitted, an empty allocated string is returned.
*/
static char *
parse_metadata_pandoc_val(const char *data, size_t *pos, size_t sz,
int strip_semis)
{
size_t sv, i, nsz, end;
char *val = NULL;
if (*pos == sz || data[*pos] != '%')
return ((val = strdup("")) == NULL) ? NULL : val;
/* Read after initial spaces. */
for ((*pos)++; *pos < sz; (*pos)++)
if (data[*pos] != ' ')
break;
/* Read until the next line that doesn't start with space. */
for (sv = *pos; *pos < sz; (*pos)++)
if (data[*pos] == '\n' &&
(*pos + 1 >= sz || data[*pos + 1] != ' '))
break;
end = (*pos)++;
/*
* If we're stripping semicolons, double the amount of space
* because a semicolon is written into two characters.
* (Doubling is easier than counting semicolons, and it's not
* like this is going to break the bank...)
*/
nsz = end - sv;
if (strip_semis)
nsz *= 2;
if ((val = malloc(nsz + 1)) == NULL)
return NULL;
/*
* If we're stripping semicolons, normalise from pandoc into mmd format:
* remove multiple spaces and convert semicolons to two spaces.
*/
for (i = 0; sv < end; sv++) {
if (data[sv] == '\n') {
val[i++] = ' ';
} else if (data[sv] == ' ') {
val[i++] = data[sv];
while (sv + 1 < end && data[sv + 1] == ' ')
sv++;
} else if (strip_semis && data[sv] == ';') {
val[i++] = ' ';
val[i++] = ' ';
} else
val[i++] = data[sv];
}
val[i] = '\0';
return val;
}
/*
* Test whether the pandoc title is a "man title", i.e.,
*
* title(section)...
*
* This just tests that a proper title(section) is found: a non-empty
* title (no checks), opening paren, digit followed by optional alpha,
* then closing paren.
*/
static int
is_metadata_pandoc_mantitle(const struct lowdown_doc *doc,
const char *title)
{
const char *cp;
if (!(doc->ext_flags & LOWDOWN_MANTITLE))
return 0;
if (title == NULL || *title == '\0')
return 0;
if ((cp = strchr(title, '(')) == NULL || cp == title)
return 0;
if (!isdigit((unsigned char)*++cp) && *cp != 'n')
return 0;
for (cp++; *cp != '\0'; cp++)
if (*cp == ')')
return 1;
else if (!isalpha((unsigned char)*cp))
return 0;
return 0;
}
/*
* Parse the title, optional author, and optional date from a pandoc
* metadata block "data" of length "sz". Store the output in the doc's
* "metaq" as well as in the tree.
* Return <0 on failure (memory failure) or >1 on success. This never
* returns 0.
*/
static int
parse_metadata_pandoc(struct lowdown_doc *doc, const char *data,
size_t sz)
{
char *title = NULL, *author = NULL,
*date = NULL, *cp, *ccp;
const char *sec = NULL, *source = NULL,
*volume = NULL;
size_t pos = 0;
int rc = -1;
title = parse_metadata_pandoc_val(data, &pos, sz, 0);
if (title == NULL)
goto err;
author = parse_metadata_pandoc_val(data, &pos, sz, 1);
if (author == NULL)
goto err;
date = parse_metadata_pandoc_val(data, &pos, sz, 0);
if (date == NULL)
goto err;
/*
* Parse title, section, source, and volume from the title alone
* IFF we have a title(nxx). This mimics how Pandoc
* automatically parses these values from its metadata but
* tightens it a little bit.
*
* title: PANDOC(1) Pandoc User Manuals | Version 4.0
* ^title | | |
* section^ | |
* ^source ^volume
*
* NB: this was a poor choice by pandoc because it performs
* additional parsing based upon the *output*. So a document
* in -tman has one title; the same document for -thtml has
* another. This is confusing for folks managing manpage
* outputs for multiple media. lowdown enables this parsing
* *always* and depends upon a parse-level flag to control
* whether or not it's enabled.
*/
if (is_metadata_pandoc_mantitle(doc, title)) {
cp = ccp = strchr(title, '(');
assert(cp != NULL && cp > title);
*cp++ = '\0';
while (ccp > title && ccp[-1] == ' ')
*--ccp = '\0';
while (*cp != '\0' && *cp == ' ')
cp++;
sec = cp;
if ((cp = strchr(sec, ')')) != NULL) {
*cp++ = '\0';
while (*cp != '\0' && *cp == ' ')
cp++;
source = cp;
cp = ccp = strchr(source, '|');
while (ccp > source && ccp[-1] == ' ')
*--ccp = '\0';
if (cp != NULL) {
*cp++ = '\0';
while (*cp != '\0' && *cp == ' ')
cp++;
volume = cp;
}
}
if (volume != NULL && *volume == '\0')
volume = NULL;
if (source != NULL && *source == '\0')
source = NULL;
if (sec != NULL && *sec == '\0')
sec = NULL;
}
if (title[0] != '\0' &&
!add_metadata(doc, "title", title, 0))
goto err;
if (author[0] != '\0' &&
!add_metadata(doc, "author", author, 0))
goto err;
if (date[0] != '\0' &&
!add_metadata(doc, "date", date, 0))
goto err;
if (sec != NULL && !add_metadata(doc, "section", sec, 0))
goto err;
if (volume != NULL && !add_metadata(doc, "volume", volume, 0))
goto err;
if (source != NULL && !add_metadata(doc, "source", source, 0))
goto err;
rc = 1;
err:
free(title);
free(author);
free(date);
return rc;
}
/*
* Parse the buffer in data of length size.
* If both mp and mszp are not NULL, set them with the meta information
* instead of locally destroying it.
* (Obviously only applicable if LOWDOWN_METADATA has been set.)
*/
struct lowdown_node *
lowdown_doc_parse(struct lowdown_doc *doc, size_t *maxn,
const char *data, size_t size, struct lowdown_metaq *metaq)
{
static const char UTF8_BOM[] = { 0xEF, 0xBB, 0xBF };
char *newbuf = NULL;
struct lowdown_buf *text = NULL;
size_t beg, end, i, j;
struct lowdown_node *n, *root = NULL;
struct lowdown_metaq mq;
int c, rc = 0, is_yaml = 0;
/*
* Have a temporary "mq" if "metaq" is not set. We clear this
* automatically at the tail of the function.
*/
TAILQ_INIT(&mq);
if (metaq == NULL)
metaq = &mq;
/* Initialise the parser. */
doc->nodes = 0;
doc->depth = 0;
doc->current = NULL;
doc->in_link_body = 0;
doc->foots = 0;
doc->metaq = metaq;
TAILQ_INIT(doc->metaq);
TAILQ_INIT(&doc->refq);
TAILQ_INIT(&doc->footq);
/* Strip out DOS CRLF, if detected at the first line. */
if ((newbuf = memchr(data, '\n', size)) != NULL &&
newbuf > data &&
newbuf[-1] == '\r') {
if ((newbuf = malloc(size)) == NULL)
goto out;
for (i = j = 0; i < size; i++)
if (data[i] != '\r')
newbuf[j++] = data[i];
data = newbuf;
size = j;
} else
newbuf = NULL;
if ((text = hbuf_new(64)) == NULL)
goto out;
if (!hbuf_grow(text, size))
goto out;
if ((root = pushnode(doc, LOWDOWN_ROOT)) == NULL)
goto out;
/*
* Skip a possible UTF-8 BOM, even though the Unicode standard
* discourages having these in UTF-8 documents.
*/
beg = 0;
if (size >= 3 && memcmp(data, UTF8_BOM, 3) == 0)
beg += 3;
/*
* Zeroth pass: metadata. First process given metadata, then
* in-document metadata, then overriding metadata. The
* in-document metadata is conditionally processed.
*/
if ((n = pushnode(doc, LOWDOWN_DOC_HEADER)) == NULL)
goto out;
for (i = 0; i < doc->metasz; i++)
if (parse_metadata_mmd(doc,
doc->meta[i], strlen(doc->meta[i]), 0) < 0)
goto out;
if (doc->ext_flags & LOWDOWN_METADATA) {
c = 0;
if ((end = is_metadata_block_pandoc
(&data[beg], size - beg)) > 0)
c = parse_metadata_pandoc
(doc, &data[beg], end - beg);
else if ((end = is_metadata_block_mmd
(&data[beg], size - beg, &is_yaml)) > 0)
c = parse_metadata_mmd
(doc, &data[beg], end - beg, is_yaml);
if (c > 0)
beg = end;
else if (c < 0)
goto out;
}
for (i = 0; i < doc->metaovrsz; i++)
if (parse_metadata_mmd(doc,
doc->metaovr[i], strlen(doc->metaovr[i]), 0) < 0)
goto out;
popnode(doc, n);
/*
* First pass: looking for references and footnotes, copying
* everything else.
*/
while (beg < size) {
if (doc->ext_flags & LOWDOWN_FOOTNOTES) {
c = is_footnote(doc, data, beg, size, &end);
if (c > 0) {
beg = end;
continue;
} else if (c < 0)
goto out;
}
if ((c = is_ref(doc, data, beg, size, &end)) > 0) {
beg = end;
continue;
} else if (c < 0)
goto out;
/* Skipping to the next line. */
end = beg;
while (end < size && data[end] != '\n')
end++;
/* Adding the line body if present. */
if (end > beg &&
!expand_tabs(text, data + beg, end - beg))
goto out;
/* Add one \n per newline. */
while (end < size && data[end] == '\n') {
if (data[end] == '\n' ||
(end + 1 < size && data[end + 1] != '\n'))
if (!hbuf_putc(text, '\n'))
goto out;
end++;
}
beg = end;
}
/*
* Second pass (after header): rendering the document body and
* footnotes.
*/
if (text->size) {
/* Adding a final newline if not already present. */
if (text->data[text->size - 1] != '\n')
if (!hbuf_putc(text, '\n'))
goto out;
if (!parse_block(doc, text->data, text->size))
goto out;
}
rc = 1;
out:
hbuf_free(text);
free_link_refs(&doc->refq);
free_foot_refq(&doc->footq);
lowdown_metaq_free(&mq);
free(newbuf);
if (rc) {
if (maxn != NULL)
*maxn = doc->nodes;
popnode(doc, root);
assert(doc->depth == 0);
} else {
lowdown_node_free(root);
root = NULL;
}
return root;
}
void
lowdown_node_free(struct lowdown_node *p)
{
struct lowdown_node *n;
if (p == NULL)
return;
switch (p->type) {
case LOWDOWN_BLOCKCODE:
hbuf_free(&p->rndr_blockcode.text);
hbuf_free(&p->rndr_blockcode.lang);
break;
case LOWDOWN_BLOCKHTML:
hbuf_free(&p->rndr_blockhtml.text);
break;
case LOWDOWN_CODESPAN:
hbuf_free(&p->rndr_codespan.text);
break;
case LOWDOWN_ENTITY:
hbuf_free(&p->rndr_entity.text);
break;
case LOWDOWN_HEADER:
hbuf_free(&p->rndr_header.attr_cls);
hbuf_free(&p->rndr_header.attr_id);
break;
case LOWDOWN_IMAGE:
hbuf_free(&p->rndr_image.link);
hbuf_free(&p->rndr_image.title);
hbuf_free(&p->rndr_image.dims);
hbuf_free(&p->rndr_image.alt);
hbuf_free(&p->rndr_image.attr_width);
hbuf_free(&p->rndr_image.attr_height);
hbuf_free(&p->rndr_image.attr_cls);
hbuf_free(&p->rndr_image.attr_id);
break;
case LOWDOWN_LINK:
hbuf_free(&p->rndr_link.link);
hbuf_free(&p->rndr_link.title);
hbuf_free(&p->rndr_link.attr_cls);
hbuf_free(&p->rndr_link.attr_id);
break;
case LOWDOWN_LINK_AUTO:
hbuf_free(&p->rndr_autolink.link);
break;
case LOWDOWN_MATH_BLOCK:
hbuf_free(&p->rndr_math.text);
break;
case LOWDOWN_META:
hbuf_free(&p->rndr_meta.key);
break;
case LOWDOWN_NORMAL_TEXT:
hbuf_free(&p->rndr_normal_text.text);
break;
case LOWDOWN_RAW_HTML:
hbuf_free(&p->rndr_raw_html.text);
break;
case LOWDOWN_TABLE_HEADER:
free(p->rndr_table_header.flags);
break;
default:
break;
}
while ((n = TAILQ_FIRST(&p->children)) != NULL) {
TAILQ_REMOVE(&p->children, n, entries);
lowdown_node_free(n);
}
free(p);
}
void
lowdown_metaq_free(struct lowdown_metaq *q)
{
struct lowdown_meta *m;
if (q == NULL)
return;
while ((m = TAILQ_FIRST(q)) != NULL) {
TAILQ_REMOVE(q, m, entries);
free(m->key);
free(m->value);
free(m);
}
}
void
lowdown_doc_free(struct lowdown_doc *doc)
{
size_t i;
if (doc == NULL)
return;
for (i = 0; i < doc->metasz; i++)
free(doc->meta[i]);
for (i = 0; i < doc->metaovrsz; i++)
free(doc->metaovr[i]);
free(doc->meta);
free(doc->metaovr);
free(doc);
}
|