/usr/share/perl5/Syntax/Highlight/Perl/Improved.pm is in libsyntax-highlight-perl-improved-perl 1.01-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | package Syntax::Highlight::Perl::Improved;
#
# Syntax::Highlight::Perl::Improved
#
# Created 01-23-2001 by Cory Johns
# Last Modified 05-03-2004 by David C.Y. Liu
#
# (See end of file (or POD) for revision history.)
#
# Freely distributable under the same conditions as Perl itself.
#
our ($VERSION) = '1.01' =~ /([.,\d]+)/;
=head1 NAME
Syntax::Highlight::Perl::Improved - Highlighting of Perl Syntactical Structures
=head1 VERSION
This file documents Syntax::Highlight::Perl::Improved version B<1.0>.
=head1 SYNOPSIS
# simple procedural
use Syntax::Highlight::Perl::Improved ':BASIC'; # or ':FULL'
print format_string($my_string);
# OO
use Syntax::Highlight::Perl::Improved;
my $formatter = new Syntax::Highlight::Perl::Improved;
print $formatter->format_string($my_string);
=head1 DESCRIPTION
This module provides syntax highlighting for Perl code. The design bias is roughly line-oriented
and streamed (ie, processing a file line-by-line in a single pass). Provisions I<may> be made
in the future for tasks related to "back-tracking" (ie, re-doing a single line in the middle of
a stream) such as speeding up state copying.
=over 4
=head2 Constructors
The only constructor provided is C<new()>. When called on an existing object, C<new()> will
create a new I<B<copy>> of that object. Otherwise, C<new()> creates a new copy of the (internal)
I<Default Object>. Note that the use of the procedural syntax modifies the I<Default Object>
and that those changes I<will> be reflected in any subsequent C<new()> calls.
=head2 Formatting
Formatting is done using the C<format_string()> method. Call C<format_string()> with one or more
strings to format, or it will default to using C<$_>.
=head2 Setting and Getting Formats
You can set the text used for formatting a syntax element using C<set_format()> (or set
the start and end format individually using C<set_start_format()> and C<set_end_format()>,
respectively).
You can also retrieve the text used for formatting for an element via C<get_start_format()>
or C<get_end_format>. Bulk retrieval of the names or values of defined formats is possible
via C<get_format_names_list()> (names), C<get_start_format_values_list()> and C<get_end_format_values_list()>.
See L<"FORMAT TYPES"> later in this document for information on what format elements can be used.
=head2 Checking and Setting the State
You can check certain aspects of the state of the formatter via the methods: C<in_heredoc()>,
C<in_string()>, C<in_pod()>, C<was_pod()>, C<in_data()>, and C<line_count()>.
You can reset all of the above states (and a few other internal ones) using C<reset()>.
=head2 Stable and Unstable Formatting Modes
You can set or check the stability of formatting via C<unstable()>.
In unstable (TRUE) mode, formatting is not considered to be persistent with nested formats.
Or, put another way, when unstable, the formatter can only "remember" one format at a time
and must reinstate formatting for each token. An example of unstable formatting is using
ANSI color escape sequences in a terminal.
In stable (FALSE) mode (the default), formatting is considered persistent within arbitrarily
nested formats. Even in stable mode, however, formatting is never allowed to span multiple lines;
it is always fully closed at the end of the line and reinstated at the beginning of a new line,
if necessary. This is to ensure properly balanced tags when only formatting a partial code snippet.
An example of stable formatting is HTML.
=head2 Substitutions
Using C<define_substitution()>, you can have the formatter substitute certain strings with others,
after the original string has been parsed (but before formatting is applied). This is useful
for escaping characters special to the output mode (eg, E<gt> and E<lt> in HTML) without them
affecting the way the code is parsed.
You can retrieve the current substitutions (as a hash-ref) via C<substitutions()>.
=back
=head1 FORMAT TYPES
The Syntax::Highlight::Perl::Improved formatter recognizes and differentiates between many Perl syntactical
elements. Each type of syntactical element has a Format Type associated with it. There is also a
'DEFAULT' type that is applied to any element who's Format Type does not have a value.
Several of the Format Types have underscores in their name. This underscore is special, and
indicates that the Format Type can be "generalized." This means that you can assign a value to
just the first part of the Format Type name (the part before the underscore) and that value will
be applied to all Format Types with the same first part. For example, the Format Types for all
types of variables begin with "Variable_". Thus, if you assign a value to the Format Type "Variable",
it will be applied to any type of variable. Generalized Format Types take precedence over
non-generalized Format Types. So the value assigned to "Variable" would be applied to
"Variable_Scalar", even if "Variable_Scalar" had a value explicitly assigned to it.
You can also define a "short-cut" name for each Format Type that can be generalized. The short-cut
name would be the part of the Format Type name after the underscore. For example, the short-cut
for "Variable_Scalar" would be "Scalar". Short-cut names have the least precedence and are only
assigned if neither the generalized Type name, nor the full Type name have values.
Following is a list of all the syntactical elements that Syntax::Highlight::Perl::Improved currently
recognizes, along with a short description of what each would be applied to.
=over 4
=item Comment_Normal
A normal Perl comment. Starts with '#' and goes until the end of the line.
=item Comment_POD
Inline documentation. Starts with a line beginning with an equal sign ('=') followed by
a word (eg: '=pod') and continuing until a line beginning with '=cut'.
=item Directive
Either the "she-bang" line at the beginning of the file, or a line directive altering what
the compiler thinks the current line and file is.
=item Label
A loop or statement label (to be the target of a goto, next, last or redo).
=item Quote
Any string or character that begins or ends a String. Including, but not necessarily limited to:
quote-like regular expression operators (C<m//>, C<s///>, C<tr///>, etc), a Here-Document terminating
line, the lone period terminating a format, and, of course, normal quotes (C<'>, C<">, C<`>, C<q{}>,
C<qq{}>, C<qr{}>, C<qx{}>).
=item String
Any text within quotes, C<format>s, Here-Documents, Regular Expressions, and the like.
=item Subroutine
The identifier used to define, identify, or call a subroutine (or method). Note that
Syntax::Highlight::Perl::Improved cannot recognize a subroutine if it is called without using parentheses
or an ampersand, or methods called using the indirect object syntax. It formats those as barewords.
=item Variable_Scalar
A scalar variable.
Note that (theoretically) this format is not applied to non-scalar variables that are
being used as scalars (ie: array or hash lookups, nor references to anything other than scalars).
Syntax::Highlight::Perl::Improved figures out (or at least tries to) the actual I<type> of the variable
being used (by looking at how you're subscripting it) and formats it accordingly. The first
character of the variable (ie, the C<$>, C<@>, C<%>, or C<*>) tells you the type of value being
used, and the color (hopefully) tells you the type of variable being used to get that value.
(See L<"KNOWN ISSUES"> for information about when this doesn't work quite right.)
=item Variable_Array
An array variable (but not usually a slice; see above).
=item Variable_Hash
A hash variable.
=item Variable_Typeglob
A typeglob. Note that typeglobs not beginning with an asterisk (*) (eg: filehandles) are formatted
as barewords. This is because, well, they are.
=item Whitespace
Whitespace. Not usually formatted but it can be.
=item Character
A special, or backslash-escaped, character. For example: C<\n> (newline), or C<\d> (digits).
Only occurs within strings or regular expressions.
=item Keyword
A Perl keyword. Some examples include: my, local, sub, next.
Note that Perl does not make any distinction between keywords and built-in functions (at least
not in the documentation). Thus I had to make a subjective call as to what would be considered
keywords and what would be built-in functions.
The list of keywords can be found (and overloaded) in the variable
C<$Syntax::Highlight::Perl::Improved::keyword_list_re> as a pre-compiled regular expression.
=item Builtin_Function
A Perl built-in function, called as a function (ie, using parentheses).
The list of built-in functions can be found (and overloaded) in the variable
C<$Syntax::Highlight::Perl::Improved::builtin_list_re> as a pre-compiled regular expression.
=item Builtin_Operator
A Perl built-in function, called as a list or unary operator (ie, without using parentheses).
The list of built-in functions can be found (and overloaded) in the variable
C<$Syntax::Highlight::Perl::Improved::builtin_list_re> as a pre-compiled regular expression.
=item Operator
A Perl operator.
The list of operators can be found (and overloaded) in the variable
C<$Syntax::Highlight::Perl::Improved::operator_list_re> as a pre-compiled regular expression.
=item Bareword
A bareword. This can be user-defined subroutine called without parentheses, a typeglob used
without an asterisk (*), or just a plain old bareword.
=item Package
The name of a package or pragmatic module.
Note that this does not apply to the package portion of a fully qualified variable name.
=item Number
A numeric literal.
=item Symbol
A symbol (ie, non-operator punctuation).
=item CodeTerm
The special tokens that signal the end of executable code and the begining of the
DATA section. Specifically, 'C<__END__>' and 'C<__DATA__>'.
=item DATA
Anything in the DATA section (see C<CodeTerm>).
=back
=head1 PROCEDURAL vs. OBJECT ORIENTED
Syntax::Highlight::Perl::Improved uses OO method-calls internally (and actually defines a Default Object
that is used when the functions are invoked procedurally) so you will not gain anything
(efficiency-wise) by using the procedural interface. It is just a matter of style.
It is actually recommended that you use the OO interface, as this allows you to instantiate
multiple, concurrent-yet-separate formatters. Though I cannot think of I<why> you would I<need>
multiple formatters instantiated. :-)
One point to note: the C<new()> method uses the Default Object to initialize new objects. This
means that any changes to the state of the Default Object (including Format definitions) made by
using the procedural interface will be reflected in any subsequently created objects. This can
be useful in some cases (eg, call C<set_format()> procedurally just before creating a batch of new
objects to define default Formats for them all) but will most likely lead to trouble.
=cut
use strict;
#===================================================================================================
# Yay constants!
#===================================================================================================
use constant FALSE => 0;
use constant TRUE => not FALSE;
#===================================================================================================
# Setup package exportation.
#===================================================================================================
use base 'Exporter';
use vars qw(@EXPORT_OK %EXPORT_TAGS);
@EXPORT_OK = qw(
reset
unstable
in_heredoc
in_string
in_pod
was_pod
in_data
line_count
substitutions
define_substitution
set_start_format
set_end_format
set_format
get_start_format
get_end_format
get_format_names_list
get_start_format_values_list
get_end_format_values_list
format_string
format_token
);
%EXPORT_TAGS = (
BASIC => [ qw(
set_format
format_string
) ],
FULL => [ @EXPORT_OK ],
);
#===================================================================================================
# Define package globals.
#===================================================================================================
#
# This is the (overloadable) name of the current object.
# Used to bless new objects.
#
use vars qw($THIS_CLASS);
$THIS_CLASS = __PACKAGE__;
#
# These regular expressions do much of the work for this package. They recognize and separate
# the lines into small, meaningful (and usefull) tokens.
#
use vars qw($quotes_re $heredoc_re $identifier_re $builtin_vars_re $number_re);
use vars qw($keyword_list_re $builtin_list_re $operator_list_re);
#
# Quotes and quote-like constructs.
#
# Note: This regex primarily matches quote _instigators_ (as opposed to terminators)
# (when it can tell the difference). For example, given:
#
# qw (blah blah blah)
#
# it will match 'qw ('. It matches up to the open parenthesis so that we will
# be able to tell later on what we should look for to close the quote (ie ')').
#
$quotes_re = qr/(?: q[qxwr]? | m | s | tr | y ) (?: \s+ [^\s\#] | [^\w\s] ) | [\'\"\`] /x;
#
# Here-document instigators.
#
$heredoc_re = qr/<<(?:\s*['"`]\w+['"`]|\w+)?/;
#
# Identifiers (variables, subroutines, and packages).
#
$identifier_re = qr/(?:(?:[A-Za-z_]|::)(?:\w|::)*)/;
#
# Variable class specifiers.
#
my $varchars = qr/(?:(?:[\@\%\*]|\$\#?)\$*)/;
#
# Perl builtin variables.
#
$builtin_vars_re =
qr/ \$\#?_
| \$(?:\^[LAECDFHIMOPRSTWX]|[0-9&`'+*.\/|,\\";#%=\-~^:?!@\$<>()\[\]])
| \$\#?ARGV(?:\s*\[)?
| \$\#?INC\s*\[
| \$(?:ENV|SIG|INC)\s*\{
| \@(?:_|ARGV|INC)
| \%(?:INC|ENV|SIG)
/x;
#
# Numbers.
#
$number_re = qr/0x[\da-fA-F]+|[_.\d]+([eE][-+]?\d+)?/;
#
# The list of keywords. Okay, so it's ugly.
#
$keyword_list_re =
qr/ continue
| foreach
| require
| package
| scalar
| format
| unless
| local
| until
| while
| elsif
| next
| last
| goto
| else
| redo
| sub
| for
| use
| our
| no
| if
| my
/x;
#
# The list of builtin functions. Damn, that's ugly.
#
$builtin_list_re =
qr/ getprotobynumber
| getprotobyname
| getservbyname
| gethostbyaddr
| gethostbyname
| getservbyport
| getnetbyaddr
| getnetbyname
| getsockname
| getpeername
| setpriority
| getprotoent
| setprotoent
| getpriority
| endprotoent
| getservent
| setservent
| endservent
| sethostent
| socketpair
| getsockopt
| gethostent
| endhostent
| setsockopt
| setnetent
| quotemeta
| localtime
| prototype
| getnetent
| endnetent
| rewinddir
| wantarray
| getpwuid
| closedir
| getlogin
| readlink
| endgrent
| getgrgid
| getgrnam
| shmwrite
| shutdown
| readline
| endpwent
| setgrent
| readpipe
| formline
| truncate
| dbmclose
| syswrite
| setpwent
| getpwnam
| getgrent
| getpwent
| ucfirst
| sysread
| setpgrp
| shmread
| sysseek
| sysopen
| telldir
| defined
| opendir
| connect
| lcfirst
| getppid
| binmode
| syscall
| sprintf
| getpgrp
| readdir
| seekdir
| waitpid
| reverse
| unshift
| symlink
| dbmopen
| semget
| msgrcv
| rename
| listen
| chroot
| msgsnd
| shmctl
| accept
| unpack
| exists
| fileno
| shmget
| system
| unlink
| printf
| gmtime
| msgctl
| semctl
| values
| rindex
| substr
| splice
| length
| msgget
| select
| socket
| return
| caller
| delete
| alarm
| ioctl
| index
| undef
| lstat
| times
| srand
| chown
| fcntl
| close
| write
| umask
| rmdir
| study
| sleep
| chomp
| untie
| print
| utime
| mkdir
| atan2
| split
| crypt
| flock
| chmod
| BEGIN
| bless
| chdir
| semop
| shift
| reset
| link
| stat
| chop
| grep
| fork
| dump
| join
| open
| tell
| pipe
| exit
| glob
| warn
| each
| bind
| sort
| pack
| eval
| push
| keys
| getc
| kill
| seek
| sqrt
| send
| wait
| rand
| tied
| read
| time
| exec
| recv
| eof
| chr
| int
| ord
| exp
| pos
| pop
| sin
| log
| abs
| oct
| hex
| tie
| cos
| vec
| END
| ref
| map
| die
| \-C
| \-b
| \-S
| \-u
| \-t
| \-p
| \-l
| \-d
| \-f
| \-g
| \-s
| \-z
| uc
| \-k
| \-e
| \-O
| \-T
| \-B
| \-M
| do
| \-A
| \-X
| \-W
| \-c
| \-R
| \-o
| \-x
| lc
| \-w
| \-r
/x;
#
# The list of operators. Also pretty ugly.
#
$operator_list_re =
qr/ xor
| \.\.\.
| and
| not
| \|\|\=
| cmp
| \>\>\=
| \<\<\=
| \<\=\>
| \&\&\=
| or
| \=\>
| \!\~
| \^\=
| \&\=
| \|\=
| \.\=
| x\=
| \%\=
| \/\=
| \*\=
| \-\=
| \+\=
| \=\~
| \*\*
| \-\-
| \.\.
| \|\|
| \&\&
| \+\+
| \-\>
| ne
| eq
| \!\=
| \=\=
| ge
| le
| gt
| lt
| \>\=
| \<\=
| \>\>
| \<\<
| \,
| \=
| \:
| \?
| \^
| \|
| x
| \%
| \/
| \*
| \<
| \&
| \\
| \~
| \!
| \>
| \.
| \-
| \+
/x;
#===================================================================================================
# Package-private variables.
#
# Basically, just defaults.
#===================================================================================================
#
# The default object variable.
#
# Note that all of these values (including Formats) will be *COPIED* (recursively)
# into any newly created object.
#
# Also note that any changes made to this object (via procedural-style calls to almost
# any of the exported functions) _will be reflected in any objects created after those
# changes are made_. In other words, you probably don't want to mix OO-style and
# Procedural-style unless you really know what you're doing.
#
# Further note that this object is blessed when this package is 'use'd (or 'require'd)
# (ie, before you have a chance to overload the $THIS_CLASS package-global variable).
# If you're inheriting from this package, you'll probably want to re-bless this object.
# Although it is perhaps not totally necessary as long as you overload the $THIS_CLASS
# package-global since new() re-blesses any copies of this object using that class.
#
use vars qw($Default_Object);
$Default_Object = bless {
#
# State variables.
#
'in_string' => FALSE, # Boolean.
'awaiting_multi' => FALSE, # Boolean. Waiting for second part of Multipart construct.
'found_multi' => FALSE, # Boolean.
'awaiting_options' => FALSE, # Boolean. Waiting for options for a Optioned construct.
'quote_instigator' => '',
'quote_terminator' => '',
'quote_type' => '', # Any in (Interpolated, Multipart, Optioned)
'nested_quote' => 0, # Anything >= 0.
'awaiting_variable' => FALSE, # Boolean. Indicates we're awaiting a variable identifier.
'awaiting_class' => '', # Any in (Scalar, Array, Hash). Class of the variable we're waiting on.
'in_heredoc' => 0, # Anything >= 0 (boolean count).
'here_terminator' => [], # List of Here-Doc terminators that we're waiting for.
'in_pod' => FALSE, # Boolean. Indicates that we're inside a POD.
'was_pod' => FALSE, # Boolean. Indicates that we _were_ inside a POD. (For in_pod() method.)
'in_data' => FALSE, # Boolean. We don't format __DATA__.
'in_comment' => FALSE, # Boolean. Indicates we're inside a normal comment.
'last_token' => '', # The last (non-whitespace, non-comment) token processed.
'last_token_type' => '', # Type of the last token.
'reentrant' => FALSE, # Boolean. Indicates we're formatting a sub-token.
'line_count' => 0, # The number of lines that have been processed.
'unstable' => FALSE, # Boolean. Indicates formats are not persistent (eg. terminal colors).
#
# Option tables.
#
'Substitution Table'=> {}, # Table of characters to replace before formatting.
'Formats' => {
'DEFAULT' => ['', ''],
},
}, $THIS_CLASS;
#===================================================================================================
# Public Methods
#
# The stuff.
#===================================================================================================
=head1 METHODS
=over 4
=item new PACKAGE
=item new OBJECT
Creates a new object. If called on an existing object, creates a new copy of that
object (which is thenceforth totally separate from the original).
=cut
sub new {
my $class = shift;
my $true_class = ref($class) || $class; # We don't want our class being the string version of a reference.
my $source = ref($class) ? $class : $Default_Object; # If called as method of exisiting object, copy.
#
# Hrm. Maybe I'll eventually take a look inside Data::Dumper and see how
# it goes about descending the complex structures and write a non-eval
# deep-copy routine. :-)
#
# Seems kinda silly to put that much work onto the perl parser when we could
# just copy it in-memory.
#
use Data::Dumper; # For deep-copy.
use Carp; # For croak().
local $SIG{__WARN__} = sub { chomp($@ = $_[0]) }; # eval() sometimes doesn't put all it's errors in $@
local $Data::Dumper::Deepcopy = 1; # Descend into nested (complex) structures.
local $Data::Dumper::Terse = 1; # Don't print variable names and assignments.
local $Data::Dumper::Purity = 1; # Ensure nested references are correctly recreated.
my $code = Dumper($source); # Save in case of errors.
my $self = eval($code) or
croak "Deepcopy failed in $true_class\::new() with the error:\n $@\non the code:\n$code";
return bless($self, $true_class);
}
=item reset
Resets the object's internal state. This breaks out of strings and here-docs, ends PODs,
resets the line-count, and otherwise gets the object back into a "normal" state to begin
processing a new stream.
Note that this does B<I<not>> reset any user options (including formats and format stability).
=cut
sub reset {
my $self = ref($_[0]) ? shift : $Default_Object;
$self->{'in_string'} = FALSE;
$self->{'awaiting_multi'} = FALSE;
$self->{'found_multi'} = FALSE;
$self->{'awaiting_options'} = FALSE;
$self->{'quote_instigator'} = '';
$self->{'quote_terminator'} = '';
$self->{'quote_type'} = '';
$self->{'awaiting_variable'} = FALSE;
$self->{'awaiting_class'} = '';
$self->{'in_heredoc'} = 0;
@{$self->{'here_terminator'}} = (); # No need for a whole new anon. array. Just empty this one.
$self->{'in_pod'} = FALSE;
$self->{'was_pod'} = FALSE;
$self->{'in_data'} = FALSE;
$self->{'in_comment'} = FALSE;
$self->{'last_token'} = '';
$self->{'last_token_type'} = '';
$self->{'reentrant'} = FALSE;
$self->{'line_count'} = 0;
}
=item unstable EXPR
=item unstable
Returns true if the formatter is in unstable mode.
If called with a non-zero number, puts the formatter into unstable formatting mode.
In unstable mode, it is assumed that formatting is not persistent one token to the
next and that each token must be explicitly formatted.
=cut
sub unstable {
my $self = ref($_[0]) ? shift : $Default_Object;
return @_ ? $self->{'unstable'} = shift : $self->{'unstable'};
}
=item in_heredoc
Returns true if the next string to be formatted will be inside a Here-Document.
=cut
sub in_heredoc {
my $self = ref($_[0]) ? shift : $Default_Object;
return $self->{'in_heredoc'};
}
=item in_string
Returns true if the next string to be formatted will be inside a multi-line string.
=cut
sub in_string {
my $self = ref($_[0]) ? shift : $Default_Object;
return $self->{'in_string'};
}
=item in_pod
Returns true if the formatter would consider the next string passed to it as begin within
a POD structure. This is false immediately before any POD instigators
(C<=pod>, C<=head1>, C<=item>, etc), true immediately after an instigator, throughout the POD and
immediately before the POD terminator (C<=cut>), and false immediately after the POD terminator.
=cut
sub in_pod {
my $self = ref($_[0]) ? shift : $Default_Object;
return $self->{'in_pod'};
}
=item was_pod
Returns true if the last line of the string just formatted was part of a POD structure.
This includes the C</^=\w+/> POD instigators and terminators.
=cut
sub was_pod {
my $self = ref($_[0]) ? shift : $Default_Object;
return $self->{'was_pod'};
}
=item in_data
Returns true if the next string to be formatted will be inside
the DATA section (ie, follows a C<__DATA__> or C<__END__> tag).
=cut
sub in_data {
my $self = ref($_[0]) ? shift : $Default_Object;
return $self->{'in_data'};
}
=item line_count
Returns the number of lines processed by the formatter.
=cut
sub line_count {
my $self = ref($_[0]) ? shift : $Default_Object;
return $self->{'line_count'};
}
=item substitutions
Returns a reference to the substitution table used. The substitution
table is a hash whose keys are the strings to be replaced, and whose values
are what to replace them with.
=cut
sub substitutions {
my $self = ref($_[0]) ? shift : $Default_Object;
return $self->{'Substitution Table'};
}
=item define_substitution HASH_REF
=item define_substitution LIST
Allows user to define certain characters that will be substituted
before formatting is done (but after they have been processed for
meaning).
If the first parameter is a reference to a hash, the formatter
will replace it's own hash with the given one, and subsequent
changes to the hash outside the formatter will be reflected.
Otherwise, it will copy the arguments passed into it's own
hash, and any substitutions already defined (but not in the
parameter list) will be preserved. (ie, the new substitutions
will be added, without destroying what was there already.)
=cut
sub define_substitution {
my $self = ref($_[0]) ? shift : $Default_Object;
if(ref($_[0]) eq 'HASH') {
$self->{'Substitution Table'} = $_[0];
} else {
my %tmphash = @_;
@{$self->{'Substitution Table'}}{keys %tmphash} = values %tmphash;
}
}
=item set_start_format HASH_REF
=item set_start_format LIST
Given either a list of keys/values, or a reference to a hash of keys/values,
copy them into the object's Formats list.
=cut
sub set_start_format {
my $self = ref($_[0]) ? shift : $Default_Object;
my %tmphash = ref($_[0]) ? %{$_[0]} : @_;
$self->{'Formats'}{$_}[0] = $tmphash{$_} foreach(keys %tmphash);
}
=item set_end_format HASH_REF
=item set_end_format LIST
Given either a list of keys/values, or a reference to a hash of keys/values,
copy them into the object's Formats list.
=cut
sub set_end_format {
my $self = ref($_[0]) ? shift : $Default_Object;
my %tmphash = ref($_[0]) ? %{$_[0]} : @_;
$self->{'Formats'}{$_}[1] = $tmphash{$_} foreach(keys %tmphash);
}
=item set_format LIST
Sets the formatting string for one or more formats.
You should pass a list of keys/values where the keys are the format names and the values
are references to arrays containing the starting and ending formatting strings (in that order)
for that format.
=cut
sub set_format {
my $self = ref($_[0]) ? shift : $Default_Object;
my %tmphash = ref($_[0]) ? %{$_[0]} : @_;
foreach(keys %tmphash) {
@{$self->{'Formats'}{$_}}[0 .. $#{$tmphash{$_}}] = @{$tmphash{$_}}[0 .. $#{$tmphash{$_}}];
}
}
=item get_start_format LIST
Retrieve the string that is inserted to begin a given format type (starting format string).
The names are looked for in the following order:
B<First:> Prefer the names joined by underscore, from most general to least. For example, given
("Variable", "Scalar"): "Variable" then "Variable_Scalar".
B<Second:> Then try each name singly, in reverse order. For example,
"Scalar" then "Variable".
See L<"FORMAT TYPES"> for more information.
=cut
sub get_start_format {
my $self = (@_ && ref($_[0]) ? shift : $Default_Object);
#
# Prefer the names joined by an underscore from most general to least.
# For example, the parameters:
# 'Identifier', 'Variable', 'Scalar'
# tries 'Identifier' first, then 'Identifier_Variable', and finally 'Identifier_Variable_Scalar'.
#
my $format_id = '';
foreach my $format (@_) {
$format_id .= '_' if($format_id ne '');
$format_id .= $format;
return $self->{'Formats'}{$format_id}[0] if(exists $self->{'Formats'}{$format_id});
}
#
# Otherwise, look for each name singly, in reverse order.
# In other words, if they say:
# 'Variable', 'Scalar'
# look for 'Scalar' first, then 'Variable'.
#
foreach my $i (-$#_ .. 0) {
return $self->{'Formats'}{$_[$i]}[0] if(exists $self->{'Formats'}{$_[$i]});
}
#
# Otherwise, return the DEFAULT.
#
return $self->{'Formats'}{'DEFAULT'}[0];
}
=item get_end_format LIST
Retrieve the string that is inserted to end a given format type (ending format string).
=cut
sub get_end_format {
my $self = (@_ && ref($_[0]) ? shift : $Default_Object);
#
# Prefer the names joined by an underscore from most general to least.
# For example, the parameters:
# 'Identifier', 'Variable', 'Scalar'
# tries 'Identifier' first, then 'Identifier_Variable', and finally 'Identifier_Variable_Scalar'.
#
my $format_id = '';
foreach my $format (@_) {
$format_id .= '_' if($format_id ne '');
$format_id .= $format;
return $self->{'Formats'}{$format_id}[1] if(exists $self->{'Formats'}{$format_id});
}
#
# Otherwise, look for each name in reverse order.
# In other words, if they say:
# 'Variable', 'Scalar'
# look for 'Scalar' first, then 'Variable'.
#
for my $i (-$#_ .. 0) {
return $self->{'Formats'}{$_[$i]}[1] if(exists $self->{'Formats'}{$_[$i]});
}
#
# Otherwise, return the DEFAULT.
#
return $self->{'Formats'}{'DEFAULT'}[1];
}
=item get_format_names_list
Returns a list of the I<names> of all the Formats defined.
=cut
sub get_format_names_list {
my $self = (@_ && ref $_[0] ? shift : $Default_Object);
return keys %{$self->{'Formats'}};
}
=item get_start_format_values_list
Returns a list of the I<values> of all the start Formats defined (in the same order
as the names returned by C<get_format_names_list()>).
=cut
sub get_start_format_values_list {
my $self = (@_ && ref $_[0] ? shift : $Default_Object);
return map $$_[0], values %{$self->{'Formats'}};
}
=item get_end_format_values_list
Returns a list of the I<values> of all the end Formats defined (in the same order
as the names returned by C<get_format_names_list()>).
=cut
sub get_end_format_values_list {
my $self = (@_ && ref $_[0] ? shift : $Default_Object);
return map $$_[1], values %{$self->{'Formats'}};
}
=item format_string LIST
Formats one or more strings of Perl code. If no strings are specified, defaults to C<$_>.
Returns the list of formatted strings (or the first string formatted if called in scalar context).
B<Note:> The end of the string is considered to be the end of a line, regardless of whether
or not there is a trailing line-break (but trailing line-breaks will I<not> cause an extra, empty
line).
B<Another Note:> The function actually uses C<$/> to determine line-breaks, unless C<$/> is
set to C<\n> (newline). If C<$/> I<is> C<\n>, then it looks for the first match
of C<m/\r?\n|\n?\r/> in the string and uses that to determine line-breaks. This is to make
it easy to handle non-unix text. Whatever characters it ends up using as line-breaks are
preserved.
=cut
sub format_string {
my $self = (@_ && ref($_[0]) ? shift : $Default_Object);
@_ or push @_, $_; # Default to $_ if no strings passed.
splice(@_, 1) unless(wantarray); # Ignore all but the first string passed if called in scalar context.
my @results = ();
foreach (@_) {
my $string = $_; # Have to do this to avoid "Modification of a read-only value..." errors.
#
# We support any funky kind of line terminator but it must be
# consistant throughout the string (though not between strings).
#
# Unless $/ is custom. Then we use it.
#
my $line_sep = ($/ eq "\n" and $string =~ /(\r\n?|\n\r?)/) ? $1 : $/;
#
# Don't treat trailing $line_sep's as an extra, blank line.
# But do save it, because we'll re-add it later.
#
my $chomped = ($string =~ s/\Q$line_sep\E$//s) ? $line_sep : '';
my @lines = split quotemeta($line_sep), $string, -1; # Split on $line_sep...
#
# Compensate for a "problem" w/ split. Specifically:
#
# $str = <any non-empty string>;
# split('-', $str, -1); # returns ($str)
#
# $str = '';
# split('-', $str, -1) # does _not_ return ($str); returns () instead!
#
@lines = ('') unless(@lines); # Replace empty list with list of 1 empty string.
$_ = $self->_format_line($_) foreach(@lines); # Format. Note that this modifies @lines!
push @results, join($line_sep, @lines) . $chomped; # And recombine.
}
#
# If we're called in scalar context and not given anything to work with,
# avoid "uninitialized value" warnings by returning an empty string.
#
return (wantarray ? @results : (@results ? $results[0] : ''));
}
=item format_token TOKEN, LIST
Returns TOKEN wrapped in the start and end Formats corresponding to LIST
(as would be returned by C<get_start_format( LIST )> and C<get_end_format( LIST )>,
respectively).
No syntax checking is done on TOKEN but substitutions defined with C<define_substitution()>
are performed.
=cut
sub format_token {
my $self = (@_ && ref($_[0]) ? shift : $Default_Object);
my $token = shift;
return '' if(not(defined $token) or $token eq '');
#
# Do any substitutions that are defined.
#
my %tmp_table = %{$self->{'Substitution Table'}};
my $keys = join('|', map qr/\Q$_\E/, keys %tmp_table);
$token =~ s/($keys)/$tmp_table{$1}/eg if(defined $keys and $keys ne '');
#
# Pointer to the array containing the formats, so we don't have to look them up twice.
#
my $ra_formats = undef;
#
# Prefer the names joined by an underscore from most general to least.
# For example, the parameters:
# 'Identifier', 'Variable', 'Scalar'
# tries 'Identifier' first, then 'Identifier_Variable', and finally 'Identifier_Variable_Scalar'.
#
my $format_id = '';
foreach my $format (@_) {
$format_id .= '_' if($format_id ne '');
$format_id .= $format;
if(exists $self->{'Formats'}{$format_id}) {
$ra_formats = $self->{'Formats'}{$format_id};
last;
}
}
#
# Otherwise, look for each name singly, in reverse order.
# In other words, if they say:
# 'Variable', 'Scalar'
# look for 'Scalar' first, then 'Variable'.
#
unless(defined $ra_formats) {
foreach my $i (-$#_ .. 0) {
if(exists $self->{'Formats'}{$_[$i]}) {
$ra_formats = $self->{'Formats'}{$_[$i]};
last;
}
}
}
#
# Otherwise, if nothing found, use the DEFAULT.
#
unless(defined $ra_formats) {
$ra_formats = $self->{'Formats'}{'DEFAULT'};
}
return $ra_formats->[0] . $token . $ra_formats->[1];
}
#===================================================================================================
# Private Methods
#
# Don't call these, please (unless you really want to).
#===================================================================================================
#
# Define typeglob aliases for internal use (to save typing).
#
{
no strict 'refs';
my $pkg = __PACKAGE__;
*{ "$pkg\::_start" } = \&{ "$pkg\::get_start_format" };
*{ "$pkg\::_end" } = \&{ "$pkg\::get_end_format" };
*{ "$pkg\::_wrap" } = \&{ "$pkg\::format_token" };
}
#
# *The* method. :-)
#
# Formats a line of Perl code.
#
# Note:
#
# When I say "line", I mean that the whole string will be treated
# as a *single line*. Regardless of embedded newlines. In fact,
# embedded newlines will be treated as whitespace and will not affect
# the parsing of anything, *EVEN COMMENTS*! Yes, I do realize that
# this is wrong from Perl's point of view. Deal. I might fix that
# later. Who knows. You should be using format_string() anyway.
#
# Another Note:
#
# This method only processes a *single* line (scalar variable) at a time.
# Any aditional parameters will be ignored/lost. Defaults to $_ if no
# parameters are given.
#
sub _format_line {
my $self = (@_ && ref($_[0]) ? shift : $Default_Object);
my $line = (@_ ? shift : $_); # Default to $_.
my $new_line = ''; # Buffer variable for holding the processed part of the line.
#
# Check for special case of recursive call indicating an incorrectly tokenized line-piece.
# (ie, don't do start-of-line stuff)
#
unless($self->{'reentrant'}) {
#
# Increase the line-count.
#
++$self->{'line_count'};
#
# After parsing __END__ or __DATA__, we do no more formatting.
#
# Note: I just figured out that Here-Documents actually "override"
# __END__ and __DATA__. By "override", I mean that, though you
# can specify __END__ or __DATA__ on the same line as another
# statement (and it affects anything on the following lines),
# if the statements before the __(END|DATA)__ cause perl to expect
# a Here-Document, it will process the Here-Document lines before
# instating the DATA section. Consider the following code as an
# example (it will print the string "This will be printed\n"):
#
# print << "HEREDOC"; __END__ This is not processed as code but cannot be read from DATA.
# This will be printed
# HEREDOC
# This is data and can be read from DATA.
#
# The formatter will handle such insanity correctly.
#
return $self->_wrap($line, 'DATA') if($self->{'in_data'} and not $self->{'in_heredoc'});
#
# Do POD stuff.
#
if(not $self->{'in_string'} and not $self->{'in_heredoc'} and
($line =~ /^=\w+/ and $self->{'last_token'} =~ /^[;\}]?$/)) {
$self->{'was_pod'} = $self->{'in_pod'} = TRUE;
}
if($self->{'in_pod'}) {
#
# Check for end of POD (if we're in one).
#
$self->{'in_pod'} = FALSE if($line =~ /^=cut/);
#
# Format as a comment.
# Note that even the instigator and terminator get formatted as comment.
#
return $self->_wrap($line, 'Comment', 'POD');
} else {
$self->{'was_pod'} = FALSE;
}
#
# Check for "here-doc" terminator. It must be the ONLY thing on the line.
#
if($self->{'in_heredoc'} and $line =~ /^$self->{'here_terminator'}[0]$/) {
#
# We found one. Decrement the here-doc level and remove the terminator from the list.
#
--$self->{'in_heredoc'};
shift @{$self->{'here_terminator'}};
$self->{'last_token'} = $line;
$self->{'last_token_type'} = 'Quote';
return $self->_wrap($line, 'Quote'); # Mark here-doc terminators as quotes.
}
#
# Check for "she-bang" line (#!/usr/bin/perl). Note that it *must* be the first line.
#
if($self->{'line_count'} == 1 and $line =~ /^#!/) {
return $self->_wrap($line, 'Directive');
}
#
# Check for line directives.
#
if($line =~ /^(#\s*line\s+\d+(?:\s+(?:"[^"]*"|\S+))?)(.*)$/) {
return $self->_wrap($1, 'Directive') . $self->_wrap($2, 'Comment', 'Normal');
}
#
# String formatting can continue for multiple lines.
#
if(not $self->{'unstable'} and ($self->{'in_string'} or $self->{'in_heredoc'})) {
$new_line = $self->_start('String');
}
} # End of unless($reentrant) (line-based stuff) block.
else {
if($self->{'reentrant'} > 20) {
my $sr = (caller(1))[3]; # Get the subroutine that called us (caller(0) returns us).
my $ln = (caller(0))[2]; # Get the line that _we_ were called from.
die "$0: deep recursion ( > 20 levels) caught in "
. __PACKAGE__ . "::_format_line() called from $sr at line $ln\n";
}
}
#
# "Optimization" to prevent doing more work on empty strings than we have to.
#
# Note: this _must_ be done _after_ the line-based construct
# checks (the unless($reentrant) stuff).
#
return '' if(not(defined $line) or $line eq '');
#
# Tokenize the line.
#
my @tokens = _tokenize($line);
#
# Main loop for processing the tokenized line.
#
foreach my $token (@tokens) {
#
# Skip empty tokens as a special case.
#
next if($token eq '');
$new_line .= $self->_process_token($token);
}
#
# End of line processing.
#
# EOL processing doesn't occur if we're reentrant because that means that
# we're not actually processing a line (rather a piece of a line).
#
if(not $self->{'reentrant'}) {
#
# Comments always end at the end of the line.
#
if($self->{'in_comment'}) {
$self->{'in_comment'} = FALSE;
$new_line .= $self->_end('Comment', 'Normal') unless($self->{'unstable'});
}
#
# Strings run to the end of line but the formats should never run *off* the end of line.
# Instablility of formatting makes it pointless to start and end a line-wide format.
#
if(not $self->{'unstable'} and ($self->{'in_string'} or $self->{'in_heredoc'})) {
$new_line .= $self->_end('String');
}
#
# Setting $self->{'in_heredoc'} is postponed until end of line because the here-doc doesn't
# actually start until the next line. Due to the possibility of "nested" here-doc's,
# we set $self->{'in_heredoc'} to the number of terminators we've gotten.
#
# For example, the code:
#
# print << "END1", "****\n", << "END2";
#
# Creates two terminators ('END1' and 'END2').
#
$self->{'in_heredoc'} = @{$self->{'here_terminator'}};
}
#
# Return the formatted line.
#
return $new_line;
} # End of _format_line()
#
# This _private_ function takes a line passed to it and breaks it into usefull pieces.
# I was using a single regex to do this but it didn't handle precedence properly.
#
sub _tokenize {
my @tokens = ();
local $_ = shift; # Line to tokenize.
#
# Loop through the line, breaking off tokens as we go. The tokens we look for
# (in order of precedence) are:
#
# Comments
# Quotes and quote-like constructs
# Here-Doc initiators
# Subroutine calls
# Variable identifiers
# Whitespace
# Special (backslashed, escaped) characters
# Keywords and builtin functions
# Operators
# Barewords
# Everything else (symbols)
#
LOOP: {
if(m/\G($quotes_re)/gc or # Quote Instigator
m/\G($heredoc_re)/gc or # Here-Doc Instigator
m/\G(__END__|__DATA__)/gc or # Code Terminators
m/\G($keyword_list_re)(?!\w|::)/gc or # Keywords
m/\G($builtin_list_re(?!\w|::)(\s*\()?)/gc or # Built-in Functions
m/\G((?:\\\&|\&)$varchars?\s*(?:$identifier_re|\{))/gc or # Subroutine: &ident
m/\G((?!$operator_list_re\s*\()$identifier_re\s*\()/gc or # Subroutine: ident(
m/\G(\\?$varchars(?:$identifier_re(?:\s*[\[\{])?|\s*\{))/gc or # Variable
m/\G(\\?(?:$varchars(?![@%]))?$builtin_vars_re(?:\s*[\[\{])?)/gc or # Built-in Variables
m/\G(\s+)/gc or # Whitespace
m/\G(\\.)/gc or # Character
m/\G($identifier_re(\s*(=>|:(?!:)))?)/gc or # Bareword / Label
m/\G($number_re)/gc or # Numbers
m/\G($operator_list_re)/gc or # Operator
m/\G(.)/gc # Symbol
) {
push @tokens, $1;
redo LOOP;
};
};
return @tokens;
}
#
# This _private_ function tests a token against any or all of the available Formats,
# and formats it accordingly. It also handles initiating and terminating quoted constructs.
#
sub _process_token {
my $self = (ref($_[0]) ? shift : $Default_Object);
my $token = shift;
#**********************************************************
# Preemptive tests.
#**********************************************************
#
# After parsing __END__ or __DATA__, we no longer format tokens
# (er, rather, we format them as DATA). Even ones on the same
# line as the __END__ or __DATA__.
#
# This block only handles tokens on the same line as the __END/DATA__.
# See _format_line() for the code that handles the lines following the __END/DATA__ line.
#
if($self->{'in_data'} and not $self->{'in_heredoc'}) {
return $self->_wrap($token, 'DATA');
}
#
# The only things we will allow between a class specifier and it's identifier are:
# A comment
# Whitespace
#
if($self->{'awaiting_variable'}) {
unless($token =~ /^$identifier_re/ or $self->{'in_comment'} or $token eq '#' or $token =~ /^\s+$/) {
$self->{'awaiting_variable'} = FALSE;
}
}
#**********************************************************
# Normal token tests.
#**********************************************************
#
# Test for special character.
#
if($token =~ /^(\\.)(.+)?$/) {
my $preamble = $1;
my $postamble = defined($2) ? $2 : '';
#
# We only do special characters when we're inside an
# interpolated string or a here-doc, or the character
# is super-special (meaning either a double back-slash,
# or a back-slash escaped quote-terminator).
#
unless(
(
$self->{'in_string'} and (
$self->{'quote_type'} =~ /Interpolated/
or $token eq "\\\\"
or $token =~ /\\\Q$self->{'quote_terminator'}\E/
)
)
or $self->{'in_heredoc'}
) {
$postamble = substr($preamble, 1, 1) . $postamble; # The character (plus other stuff)
$preamble = substr($preamble, 0, 1); # The backslash
++$self->{'reentrant'};
$preamble = $self->_format_line($preamble);
$postamble = $self->_format_line($postamble);
--$self->{'reentrant'};
return $preamble . $postamble;
}
$self->{'last_token'} = $preamble;
$self->{'last_token_type'} = 'Character';
if(defined $postamble) {
++$self->{'reentrant'};
$postamble = $self->_format_line($postamble);
--$self->{'reentrant'};
}
return $self->_wrap($preamble, 'Character') . $postamble;
}
#
# Test for comment.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and ($token eq '#' or $self->{'in_comment'})) {
#
# Start a new comment.
#
if($token eq '#' and not $self->{'in_comment'}) {
$self->{'in_comment'} = TRUE;
if($self->{'unstable'}) {
return $self->_wrap($token, 'Comment', 'Normal')
} else {
return $self->_start('Comment', 'Normal') . $self->_wrap($token, '')
}
return (
$self->{'unstable'}
?
$self->_wrap($token, 'Comment', 'Normal')
:
$self->_start('Comment', 'Normal') . $self->_wrap($token, '')
);
}
return (
$self->{'unstable'}
?
$self->_wrap($token, 'Comment', 'Normal')
:
$self->_wrap($token, '')
);
}
#
# Test for (DATA Instigators) special tokens that signal the end of executable code.
# We will format nothing after we encounter one of these.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and ($token eq '__END__' or $token eq '__DATA__')) {
$self->{'in_data'} = TRUE;
return $self->_wrap($token, 'CodeTerm');
}
#
# Quote-related tests.
#
#
# Check for nested quotes.
#
# If our quotes are bracketing and we encounter another Instigator inside
# the string, we require a matching terminator before we end the string.
#
# For example:
#
# qq{ Because of this -> { the string does not end here -> }, it ends here -> }
#
if($self->{'in_string'} and
$token !~ /\Q$self->{'quote_terminator'}\E/ and
$token =~ /\Q$self->{'quote_instigator'}\E/
) {
#
# Token matches the quote instigator but not the terminator so it must be
# a bracketing type of quote. We need to increase the count of nested
# quotes. We do not do anything else w/ the token, just let it be processed
# by subsequent code.
#
++$self->{'nested_quote'};
}
#
# Check for second part of Multipart quoted construct (if we're waiting for one).
#
# Comments (handled above) and whitespace are ignored between parts of a Multipart construct.
#
if($self->{'awaiting_multi'} and $token =~ /\S/) {
#
# Anything other than a comment or whitespace causes us to stop waiting
# for the second part. (It's technically an error.)
#
$self->{'awaiting_multi'} = FALSE;
if($token =~ /\Q$self->{'quote_instigator'}\E/) {
#
# We have found the second part!
#
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Quote';
$self->{'found_multi'} = TRUE;
$self->{'in_string'} = TRUE;
return
$self->_wrap($token, 'Quote')
. ($self->{'unstable'} ? '' : $self->_start('String'));
}
}
#
# Check for options to an optioned quoted construct.
#
if($self->{'awaiting_options'}) {
$self->{'awaiting_options'} = FALSE;
if($token =~ /^([cgimosexd]+|s.*)$/) {
my $postamble = '';
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Quote';
#
# Check for lone `s' option incorrectly tokenized as a s/// instigator
# and recursively re-process it if necessary.
#
if($token =~ /^(s)([^cgimoxed]*)$/) {
$token = $1;
$self->{'last_token'} = $token;
++$self->{'reentrant'};
$postamble = $self->_format_line($2);
--$self->{'reentrant'};
}
return $self->_wrap($token, 'Quote') . $postamble;
}
}
#
# Test for quote instigator (string-start).
#
# Note: The forward-slash and question mark characters (/ and ?) as quote instigators are
# pretty difficult to disambiguate and if it becomes a problem, I may just leave them
# out. Though I'd rather not.
#
# The strategy we use here is to only make them operators (division or ternary conditional,
# respectively) if they immediately follow a closing bracket-type-thingy ([\)\]\}]),
# quote, variable, literal number, bareword, or a builtin or user function other than
# print, split, grep, or map.
#
# Note that the function/subroutine situation is still ambiguous: some functions should
# cause them to start a quote and some should cause them to be operators, depending on
# the effective prototype of the function (eg: sin vs. time).
#
# There are also some other ambiguities, as well. Such as when they follow certain types
# of symbols or operators.
#
# See http://perlmonks.org/index.pl?node=On+Parsing+Perl for more information.
#
if((not $self->{'in_string'}) and (not $self->{'in_heredoc'}) and ($token =~ /^$quotes_re/ or
($token =~ m{^[/?]} and
$self->{'last_token'} !~ /[\)\]\}]$/ and # Closing bracket-type-thingy. Might add > later.
$self->{'last_token_type'} ne 'Quote' and
$self->{'last_token_type'} ne 'Variable' and
$self->{'last_token_type'} ne 'Number' and
$self->{'last_token_type'} ne 'Bareword' and
$self->{'last_token_type'} ne 'Subroutine' and
($self->{'last_token_type'} ne 'Builtin' or
$self->{'last_token'} eq 'print' or
$self->{'last_token'} eq 'split' or
$self->{'last_token'} eq 'grep' or
$self->{'last_token'} eq 'map')))) {
#
# Create a copy of $token so we can modify it with impunity.
# (Specifically for splitting up of '/='-like constructs (see below).)
#
my $quote = $token;
#
# In certain contexts (see above), the token '/=' or similar will be considered
# the start of a pattern-match quote. We have to split off the extra and process
# it as part of the string so we store it in $postamble and re-process it later
# (see the return at the bottom of this block).
#
my $postamble = '';
if($quote =~ m{^([/?])(.+)$}) {
#
# Store the split-off quote instigator (/) and the postamble.
#
$quote = $1;
$postamble = $2;
}
#
# The quote-instigator is the last character of the token.
#
$self->{'quote_instigator'} = substr $quote, -1;
#
# Define special terminators for bracketing characters.
# Otherwise, use the same character as the instigator.
#
$self->{'quote_terminator'} =
{ '{' => '}',
'(' => ')',
'[' => ']',
'<' => '>',
}->{$self->{'quote_instigator'}} || $self->{'quote_instigator'};
#
# The type will be matched later on like so:
#
# if($self->{'quote_type'} =~ /Interpolated/) { # Is it interpolated?
#
# Note: Some of the quoted constructs are interpolated or non-interpolated
# depending on the instigator/terminator character used. Specifically,
# if a single quote is used as the delimter for qx, m, qr, and s, they
# are *not* interpolated. Otherwise, they *are* interpolated.
#
$self->{'quote_type'} = (
($quote =~ /"|qq/ && 'Literal, Interpolated') or
($quote =~ /'|q[^qxwr]/ && 'Literal') or
($quote =~ /`|qx/ && 'Command' .
($self->{'quote_instigator'} eq q(') ? '' : ', Interpolated'))
or
($quote =~ /qw/ && 'Word list') or
($quote =~ /m|^[\/?]/ && 'Pattern, Matching, Optioned' .
($self->{'quote_instigator'} eq q(') ? '' : ', Interpolated'))
or
($quote =~ /qr/ && 'Pattern, Optioned' .
($self->{'quote_instigator'} eq q(') ? '' : ', Interpolated'))
or
($quote =~ /s/ && 'Pattern, Substitution, Optioned, Multipart' .
($self->{'quote_instigator'} eq q(') ? '' : ', Interpolated'))
or
($quote =~ /tr|y/ && 'Transliteration, Optioned, Multipart') or
'Error: Quote-Type Not Found'
);
$self->{'in_string'} = TRUE;
$self->{'last_token'} = $quote;
$self->{'last_token_type'} = 'Quote';
#
# Post-process the $postamble if necessary.
#
if($postamble ne '') {
++$self->{'reentrant'};
$postamble = $self->_format_line($postamble);
--$self->{'reentrant'};
}
return
$self->_wrap($quote, 'Quote')
. $self->_start('String')
. $postamble
. ($self->{'unstable'} ? $self->_end('String') : '');
} # End test for Quote Instigator
#
# Check for Quote Terminator. Here-doc terminators are line-based
# constructs, and thus are checked in _format_line().
#
if($self->{'in_string'} and
$token =~ /^(.*?)(?<!\\)(\Q$self->{'quote_terminator'}\E)(.*)$/
) {{ # Note double braces. That's so we can use last (just below) to exit the if.
#
# If our quotes are bracketing and we've encountered another Instigator inside
# the string, we require a matching terminator before we end the string.
#
# For example:
#
# qq{ Because of this -> { the string does not end here -> }, it ends here -> }
#
if($self->{'nested_quote'} > 0) {
--$self->{'nested_quote'};
last; # Exit enclosing if block (with double braces, not if nested_quote)
}
#
# This block terminates (possibly just the first part of) a quoted structure.
#
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Quote';
#
# Note on $preamble and $postamble:
#
# There might be extra "stuff" attached to the beginning or end of
# our quote terminator that should be formatted separately. This
# is due to the fact that the tokenizer doesn't know when it's tokenizing
# that it should be breaking things up based on quote teriminators.
#
# For example, the string '"$"' tokenizes as:
#
# '"' (quote-start), '$"' (built-in variable)
#
# It should actually be parsed:
#
# '"' (quote-start), '$' (error in Perl), '"' (quote-end)
#
# Another example; the string 's sjsjs' tokenizes as:
#
# 's s' (substitution-start), 'jsjs' (bareword)
#
# Instead of:
#
# 's s' (sub.-start), 'j' (string), 's' (sub.-end 1), 'j' (string), 's' (sub.-end)
#
my $preamble = $1;
my $terminator = $2;
my $new_string = ''; # May or may not be set; depends on if we find the second part of a multi-part.
my $postamble = $3;
++$self->{'reentrant'};
$preamble = $self->_format_line($preamble); # Must process preamble before doing multi-part logic.
--$self->{'reentrant'}; # Otherwise, we wouldn't know if it should be in_string.
#
# Handle multipart quotes.
#
if($self->{'found_multi'}) {
#
# If we've already found Multipart, we shouldn't look for it.
#
$self->{'found_multi'} = FALSE;
$self->{'in_string'} = FALSE;
$self->{'awaiting_options'} = TRUE if($self->{'quote_type'} =~ /Optioned/);
} elsif($self->{'quote_type'} =~ /Multipart/) {
#
# If we haven't already found the Multipart, we should check for it immediately.
#
if($self->{'quote_instigator'} eq $self->{'quote_terminator'}) {
#
# We found it.
#
$self->{'found_multi'} = TRUE;
$self->{'in_string'} = TRUE;
$new_string = $self->_start('String'); # Unstable logic done below (when this is used).
} else {
#
# We didn't find it so we start waiting.
#
$self->{'awaiting_multi'} = TRUE;
$self->{'in_string'} = FALSE;
}
} else {
#
# This quoted construct isn't Multiparted so we just end it.
#
$self->{'in_string'} = FALSE;
$self->{'awaiting_options'} = TRUE if($self->{'quote_type'} =~ /Optioned/);
}
#
# Do the formatting and re-processing.
#
my $formatted_token;
$formatted_token .= $preamble;
$formatted_token .= $self->_end('String') unless($self->{'unstable'});
$formatted_token .= $self->_wrap($terminator, 'Quote');
$formatted_token .= $new_string unless($self->{'unstable'});
#
# Reprocess $postamble now that multi-part logic has been done.
#
++$self->{'reentrant'};
$formatted_token .= $self->_format_line($postamble);
--$self->{'reentrant'};
return $formatted_token;
}} # End check for Quote Terminator. Note double braces.
#
# Test for Here-Doc (type of quote).
#
# Note: This maybe should be combined with the test
# for Quote Instigator or possibly Operator. Maybe.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and $token =~ /^$heredoc_re$/) {
#
# Here-Document instigators are ambiguous in some situations. The
# rule used here is that it's considered a Here-Document instigator
# unless it follows a Variable, Bareword, or Quote (string). If it
# does follow one of those, then it's probably a binary left shift
# operator and the token should be reprocessed.
#
# This rule doesn't cover every situation (functions with certain
# prototypes should also cause it to be considered a shift operator,
# and there's probably other situtations) but it should cover the
# most common ones.
#
if($self->{'last_token_type'} =~ /Quote|Bareword|Variable/) {
my ($preamble, $postamble) = $token =~ /^(<<)(.*)$/;
$preamble = $self->_wrap($preamble, 'Operator');
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Quote';
++$self->{'reentrant'};
$postamble = $self->_format_line($postamble);
--$self->{'reentrant'};
return $preamble . $postamble;
}
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Quote';
#
# Push only the word part of the here-doc terminator (not any optional quotes) onto the list.
# Note that this word part *can* be an empty string.
#
my ($term) = $token =~ /(\w+)/;
$term = '' unless(defined $term);
push @{$self->{'here_terminator'}}, $term;
$self->{'quote_type'} = 'Here-Document, Interpolated';
return $self->_wrap($token, 'Quote');
}
#
# End of quote-related tests.
#
#
# Test for keyword.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and $token =~ /^(?:$keyword_list_re)$/) {
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Keyword';
#
# Test for formats. Treat them like here-docs (they terminate w/ line =~ /^.$/).
#
if($token eq 'format') {
push @{$self->{'here_terminator'}}, '.';
}
return $self->_wrap($token, 'Keyword');
}
#
# Test for builtin functions.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and $token =~ /^($builtin_list_re)(\s*)(\(?)$/ and
$self->{'last_token'} ne 'sub' and $self->{'last_token'} ne '->') {
$self->{'last_token'} = $token;
if($3) {
$self->{'last_token_type'} = 'Symbol';
} else {
$self->{'last_token_type'} = 'Builtin';
}
return
$self->_wrap($1, 'Builtin', ($3 ? 'Function' : 'Operator')) .
$self->_wrap($2, 'Whitespace') .
$self->_wrap($3, 'Symbol');
}
#
# Test for subroutine.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and
($token =~ /^(\&$varchars?)(\s*)($identifier_re)?()((?(4)|\{))$/ or
$token =~ /^()()($identifier_re)(\s*)(\()$/ or
($token =~ /^()()($identifier_re)()()$/ and
($self->{'last_token'} eq 'sub' or $self->{'last_token'} eq '->')))) {
my $ampersand = $1 || '';
my $whitespace1 = $2 || '';
my $identifier = $3 || '';
my $whitespace2 = $4 || '';
my $parenthesis = $5 || '';
#
# Check for package imports with parameters (they accidentally get tokenized
# as subroutine calls.
#
if($self->{'last_token'} =~ /^(require|use|no)$/ and $ampersand eq '') {
$self->{'last_token'} = $token;
if($parenthesis) {
$self->{'last_token_type'} = 'Symbol';
} else {
$self->{'last_token_type'} = 'Subroutine';
}
return
$self->_wrap($identifier, 'Package')
. $self->_wrap($whitespace2, 'Whitespace')
. $self->_wrap($parenthesis, 'Symbol');
}
$self->{'last_token'} = $token;
if($parenthesis) {
$self->{'last_token_type'} = 'Symbol';
} else {
$self->{'last_token_type'} = 'Subroutine';
}
return (
(
$self->{'unstable'}
?
$self->_wrap($ampersand, 'Subroutine')
. $self->_wrap($whitespace1, 'Whitespace')
. $self->_wrap($identifier, 'Subroutine')
:
$self->_wrap($ampersand
. $self->_wrap($whitespace1, 'Whitespace')
. $identifier, 'Subroutine') # _wrap($amp . _wrap($white1, 'WS') . $ident, 'SR')
)
. $self->_wrap($whitespace2, 'Whitespace')
. $self->_wrap($parenthesis, 'Symbol')
);
} # End tests for subroutine.
#
# Test for variable.
#
# Note in the conditional for built-in variables (1st line):
# First we test for match, then, still in the conditional, we split it into the needed
# positional variables ($[1-6]) with the next match (3rd line). Once the token matches
# the first pattern (1st line), it should *always* match the second (2nd line) as well.
#
if(($token =~ /^$varchars?$builtin_vars_re$/ and
$token =~ /^($varchars)()(.+?)()([\[\{]?)$/) or # Split after match built-in variables.
$token =~ /^($varchars)(\s*)($identifier_re)(\s*)([\[\{]?)$/ or
$token =~ /^($varchars)(\s*)(\{)$/ or
$token =~ /^([\$\@\%\*])$/ or # Extra leading empty parens in regex to shift positional variables
($self->{'awaiting_variable'} and $token =~ /^()()($identifier_re)$/) ) {{ # Note double braces.
#
# The braces for this if() statement are doubled so that we can use the 'last'
# loop control statement to break out of the entire conditional block in the
# first conditional block below (the test for partial variables within Patterns).
#
my $class = '';
my $class_specifier = $1 || '';
my $whitespace1 = $2 || '';
my $identifier = (defined $3 ? $3 : ''); # Special case. ident. might be 0 ($0)
my $whitespace2 = $4 || '';
my $subscript = $5 || '';
my $postamble = '';
#
# Don't format variables inside of non-interpolated strings.
# Remember to do this _after_ using the positional variables!
#
last if($self->{'in_string'} and $self->{'quote_type'} !~ /Interpolated/);
#
# We don't format partial variables (ie, ones without identifiers) inside
# of Regex (Pattern) strings.
#
if($identifier eq '' and $self->{'in_string'} and $self->{'quote_type'} =~ /Pattern/) {
#
# This 'last' only works because of the doubled braces around the larger conditional
# block (if($token =~ ...) (see above). This trick is explained in the Perl syntax
# documentation (perlsyn). See `man perlsyn` under the Loop Control section for
# more information.
#
last;
}
#
# Hashes and typeglobs are not interpolated into strings
# or here-documents, so we need to strip any leading hash
# hash symbols (%) or typeglob symbols (*) and not consider
# the token a variable.
#
if(($self->{'in_string'} or $self->{'in_heredoc'}) and $class_specifier =~ /^([\%\*]+)/) {
my $preamble = $1;
#
# If the only thing there is the hash/typeglob character, just return.
#
if(length $token == length $preamble) {
return (
$self->{'unstable'}
?
$self->_wrap($token, 'String') # Reinstate string formatting if unstable.
:
$self->_wrap($token, '') # Format as '' to ensure substitutions.
);
}
#
# Reinstate string formatting if we're unstable.
#
$preamble = $self->_wrap($preamble, $self->{'unstable'} ? 'String' : '');
#
# Otherwise, strip off the leading symbol and reprocess the rest (via recursive call).
#
++$self->{'reentrant'};
my $result = $preamble . $self->_format_line(substr($token,1));
--$self->{'reentrant'};
return $result;
}
if($self->{'awaiting_variable'}) {
$self->{'awaiting_variable'} = FALSE;
# Adjust the class for a subscript or use the class determined before.
$class = (
$subscript
?
{'[' => 'Array', '{' => 'Hash'}->{$subscript}
:
$self->{'awaiting_class'}
);
++$self->{'reentrant'};
my $return_val =
$self->_wrap($whitespace1, 'Whitespace')
. $self->_wrap($class_specifier . $identifier, 'Variable', $class)
. $self->_wrap($whitespace2, 'Whitespace')
. $self->_format_line($subscript); # Reprocess it, in case we're in a string.
--$self->{'reentrant'};
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Variable';
return $return_val;
} elsif($class_specifier) {
# Adjust the class for a subscript or use the class specifier.
$class = (
$subscript ?
{'[' => 'Array', '{' => 'Hash'}->{$subscript}
:
{'$' => 'Scalar',
'@' => 'Array',
'%' => 'Hash',
'*' => 'Typeglob',
}->{substr($class_specifier,0,1)}
);
$class = 'INVALID CLASS' unless(defined $class);
#
# The special case of $identifier eq '{' (as in $token eq '${' for '${foo}')
# has to be handled. In case we're inside a string (we want symbols formatted
# consistantly, even if it's consistantly wrong), we need to recursively
# re-process the identifier.
#
# The other special case of $identifier eq '' means that we should start waiting
# for an identifier on a following line.
#
if($identifier eq '{') {
++$self->{'reentrant'};
$postamble = $self->_format_line($identifier);
--$self->{'reentrant'};
$identifier = '';
} elsif($identifier eq '') {
$self->{'awaiting_variable'} = TRUE;
$self->{'awaiting_class'} = $class;
}
++$self->{'reentrant'};
my $return_val =
$self->_wrap($whitespace1, 'Whitespace')
. $self->_wrap($class_specifier . $identifier, 'Variable', $class)
. $self->_wrap($whitespace2, 'Whitespace')
. $self->_format_line($subscript) # Reprocess in case we're in a string.
. $postamble;
--$self->{'reentrant'};
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Variable';
return $return_val;
}
#
# If we're not awaiting a variable identifier and there's no class specifier
# ($, @, or %), then it's probably actually a bareword or keyword or something.
#
# So we just let this if() statement fall through.
#
}} # End test for Variable. Note double braces.
#
# Test for whitespace.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and $token =~ /^\s+$/) {
return $self->_wrap($token, 'Whitespace');
}
#
# Test for operator.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and $token =~ /^(?:$operator_list_re)$/) {
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Operator';
return $self->_wrap($token, 'Operator');
}
#
# Test for number.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and $token =~ /^$number_re$/) {
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Number';
return $self->_wrap($token, 'Number');
}
#
# Test for bareword (or package name, which is a type of bareword).
#
if(not($self->{'in_string'} or $self->{'in_heredoc'}) and
$token =~ /^($identifier_re)((\s*)(=>|:(?!:)))?$/) {
#
# If $token =~ /BAREWORD\s*=>/, then BAREWORD should be formatted as a string.
#
# If $token =~ /BAREWORD\s*:/, then it's actually a label (elsif block).
#
if(defined $2 and substr($2, -1) ne ':') { # It's a string.
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'String';
++$self->{'reentrant'};
my $result = $self->_wrap($1, 'String') . $self->_format_line($2);
--$self->{'reentrant'};
return $result;
} elsif(defined $2) { # It's a label.
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'String';
return $self->_wrap($1, 'Label') . $self->_wrap($3, 'Whitespace') . $self->_wrap($4, 'Label');
}
if($self->{'last_token'} =~ /^(require|package|use|no)$/) {
#
# This bareword is actually a package name.
#
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Package';
return $self->_wrap($token, 'Package');
} elsif(substr($self->{'last_token'}, -1) eq '{' and $self->{'last_token_type'} eq 'Variable') {
#
# This bareword is the subscript to a hash and should be formatted as a string.
#
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'String';
return $self->_wrap($token, 'String');
} else {
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Bareword';
return $self->_wrap($token, 'Bareword');
}
}
#
# Test for symbol.
#
if(not($self->{'in_string'} or $self->{'in_heredoc'})) {
#
# The pound symbol (#) is special in that it starts a normal comment.
#
if($token eq '#') {
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Comment';
$self->{'in_comment'} = TRUE;
return (
$self->{'unstable'}
?
$self->_wrap($token, 'Comment', 'Normal')
:
$self->_start('Comment', 'Normal') . $self->_wrap($token, '')
);
}
$self->{'last_token'} = $token;
$self->{'last_token_type'} = 'Symbol';
return $self->_wrap($token, 'Symbol');
}
#
# No matches were made so we just return the token (reinstating
# string formatting if formatting is unstable).
#
return (
(($self->{'in_string'} or $self->{'in_heredoc'}) and $self->{'unstable'})
?
$self->_wrap($token, 'String') # If we're unstable, we need to reinstate string formatting.
:
$self->_wrap($token, '') # Format as '' to ensure substitutions; this causes no markup.
);
} # End _process_token()
TRUE; # Return true to indicate success.
=pod
=back
=head1 KNOWN ISSUES or LIMITATIONS
=over 4
=item *
Barewords used as keys to a hash are formatted as strings. This is Good. They should
not be, however, if they are not the only thing within the curly braces. That can be
fixed.
=item *
This version does not handle formats (see L<perlform(1)|perlform/1>) very well. It treats them as
Here-Documents and ignores the rules for comment lines, as well as the fact that picture
lines are not supposed to be interpolated. Thus, your picture lines will look strange
with the '@'s being formatted as array variables (albeit, invalid ones).
Ideally, it would also treat value lines as normal Perl code and format accordingly.
I think I'll get to the comment lines and non-interpolating picture lines first.
If/When I do get this fixed, I will most likely add a format type of 'Format' or something,
so that they can be formatted differently, if so desired.
=item *
This version does not handle Regular Expression significant characters. It simply treats
Regular Expressions as interpolated strings.
=item *
User-defined subroutines, called without parentheses, are formatted as barewords.
This is because there is no way to tell them apart from barewords without parsing
the code, and would require us to go as far as perl does when doing the C<-c> check
(ie, executing BEGIN and END blocks and the like). That's not going to happen.
=item *
If you are indexing (subscripting) an array or hash, the formatter tries to figure
out the "real" variable class by looking at how you index the variable. However, if
you do something funky (but legal in Perl) and put line-breaks or comments between
the variable class character ($) and your identifier, the formatter will get confused
and treat your variable as a scalar. Until it finds the index character. Then it
will format the scalar class character ($) as a scalar and your identifier as
the "correct" class.
=item *
If you put a line-break between your variable identifier and it's indexing character (see
above), which is also legal in Perl, the formatter will never find it and treat your
variable as a scalar.
=item *
If you put a line-break between a bareword hash-subscript and the hash variable, or between
a bareword and its associated C<=E<gt>> operator, the bareword will not be formatted correctly
(as a string). I<(Noticing a pattern here?)>
=back
=head1 BUGS
Bug reports are always welcome. Email me at b<davidcyl@cpan.org>.
=head1 AUTHOR
David C.Y. Liu b<davidcyl@cpan.org>
based on code by
Cory Johns B<darkness@yossman.net>
Copyright (c) 2004 David C.Y. Liu. This library is free software; you can
redistribute and/or modify it under the same conditions as Perl itself.
=head1 TO DO
I<Note:> This is Cory John's todo list, not mine. Currently none of these features are
planned for the near future.
=over 4
=item 1
Improve handling of regular expressions. Add support for regexp-special characters.
Recognize the /e option to the substitution operator (maybe).
=item 2
Improve handling of formats. Don't treat format definitions as interpolating. Handle
format-comments. Possibly format value lines as normal Perl code.
=item 3
Create in-memory deep-copy routine to replace C<eval(Data::Dumper)> deep-copy.
=item 4
Generalize state transitions (C<reset()> and, in the future, C<copy_state()>) to use
non-hard-coded keys and values for state variables. Probably will extrapolate them into an
overloadable hash, and use the aforementioned deep-copy to assign them.
=item 5
Create a method to save or copy states between objects (C<copy_state()>). Would be useful for
using this module in an editor.
=item 6
Add support for greater-than-one length special characters. Specifically, octal,
hexidecimal, and control character codes. For example, C<\644>, C<\x1a4> or C<\c[>.
=back
=head1 REVISIONS
=head2 05-03-2004 David C.Y. Liu (Version 1.01)
=over 4
=item *
Added 'our' to the keywords list.
=item *
Fixed bug that prevented interpolation inside qq() quotes.
=item *
Renamed to Syntax::Highlight::Perl::Improved.
=back
=head2 04-04-2001 Cory Johns
=over 4
=item *
Fixed problem with special characters not formatting inside of Here-Documents.
=item *
Fixed bug causing hash variables to format inside of Here-Documents.
=back
=head2 03-30-2001 Cory Johns
=over 4
=item *
Fixed bug where quote-terminators were checked for inside of Here-Documents.
=back
=head2 03-29-2001 Cory Johns
=over 4
=item *
Moved token processing tests from _format_line() into _process_token()
(where they should've been all along), generally making _format_line()
more logical. Contemplating extrapolating the tokenizing and token
loop into its own subroutine to avoid all the recursive calls.
=item *
Fixed bug that caused special characters to be recognized outside of
strings.
=item *
Added $VERSION variable.
=item *
Added support for different types of literal numbers: floating point,
exponential notation (eg: 1.3e10), hexidecimal, and underscore-separated.
=item *
Added the C<CodeTerm> and C<DATA> Formats.
=back
=head2 03-27-2001 Cory Johns
=over 4
=item *
Added was_pod() and updated the documentation for in_pod().
=back
=head2 03-20-2001 Cory Johns
=over 4
=item *
Added support for Perl formats (ie, `C<format = ...>').
=back
|