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 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771
|
/*******************************************************************************
* *
* macro.c -- Macro file processing, learn/replay, and built-in macro *
* subroutines *
* *
* Copyright (C) 1999 Mark Edel *
* *
* This is free software; you can redistribute it and/or modify it under the *
* terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 2 of the License, or (at your option) any later *
* version. In addition, you may distribute versions of this program linked to *
* Motif or Open Motif. See README for details. *
* *
* This software is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
* for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* software; if not, write to the Free Software Foundation, Inc., 59 Temple *
* Place, Suite 330, Boston, MA 02111-1307 USA *
* *
* Nirvana Text Editor *
* April, 1997 *
* *
* Written by Mark Edel *
* *
*******************************************************************************/
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif
#include "macro.h"
#include "textBuf.h"
#include "text.h"
#include "nedit.h"
#include "window.h"
#include "preferences.h"
#include "interpret.h"
#include "parse.h"
#include "search.h"
#include "server.h"
#include "shell.h"
#include "smartIndent.h"
#include "userCmds.h"
#include "selection.h"
#include "../util/rbTree.h"
#include "tags.h"
#include "calltips.h"
#include "../util/DialogF.h"
#include "../util/misc.h"
#include "../util/fileUtils.h"
#include "../util/utils.h"
#include "../util/getfiles.h"
#include "highlight.h"
#include "highlightData.h"
#include "rangeset.h"
#include "../util/nedit_malloc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#ifdef VMS
#include <limits.h>
#include "../util/VMSparam.h"
#include <types.h>
#include <stat.h>
#include <unixio.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#ifndef __MVS__
#include <sys/param.h>
#endif
#include <fcntl.h>
#endif /*VMS*/
#include <inttypes.h>
#include <X11/Intrinsic.h>
#include <X11/keysym.h>
#include <Xm/Xm.h>
#include <Xm/CutPaste.h>
#include <Xm/Form.h>
#include <Xm/RowColumn.h>
#include <Xm/LabelG.h>
#include <Xm/List.h>
#include <Xm/ToggleB.h>
#include <Xm/DialogS.h>
#include <Xm/MessageB.h>
#include <Xm/SelectioB.h>
#include <Xm/PushB.h>
#include <Xm/Text.h>
#include <Xm/Separator.h>
#ifdef HAVE_DEBUG_H
#include "../debug.h"
#endif
/* Maximum number of actions in a macro and args in
an action (to simplify the reader) */
#define MAX_MACRO_ACTIONS 1024
#define MAX_ACTION_ARGS 40
/* How long to wait (msec) before putting up Macro Command banner */
#define BANNER_WAIT_TIME 6000
/* The following definitions cause an exit from the macro with a message */
/* added if (1) to remove compiler warnings on solaris */
#define M_FAILURE(s) do { *errMsg = s; if (1) return False; } while (0)
#define M_STR_ALLOC_ASSERT(xDV) do { if (xDV.tag == STRING_TAG && !xDV.val.str.rep) { *errMsg = "Failed to allocate value: %s"; return(False); } } while (0)
#define M_ARRAY_INSERT_FAILURE() M_FAILURE("array element failed to insert: %s")
/* Data attached to window during shell command execution with
information for controling and communicating with the process */
typedef struct {
XtIntervalId bannerTimeoutID;
XtWorkProcId continueWorkProcID;
char bannerIsUp;
char closeOnCompletion;
Program *program;
RestartData *context;
Widget dialog;
} macroCmdInfo;
/* Widgets and global data for Repeat dialog */
typedef struct {
WindowInfo *forWindow;
char *lastCommand;
Widget shell, repeatText, lastCmdToggle;
Widget inSelToggle, toEndToggle;
} repeatDialog;
static void cancelLearn(void);
static void runMacro(WindowInfo *window, Program *prog);
static void finishMacroCmdExecution(WindowInfo *window);
static void repeatOKCB(Widget w, XtPointer clientData, XtPointer callData);
static void repeatApplyCB(Widget w, XtPointer clientData, XtPointer callData);
static int doRepeatDialogAction(repeatDialog *rd, XEvent *event);
static void repeatCancelCB(Widget w, XtPointer clientData, XtPointer callData);
static void repeatDestroyCB(Widget w, XtPointer clientData, XtPointer callData);
static void learnActionHook(Widget w, XtPointer clientData, String actionName,
XEvent *event, String *params, Cardinal *numParams);
static void lastActionHook(Widget w, XtPointer clientData, String actionName,
XEvent *event, String *params, Cardinal *numParams);
static char *actionToString(Widget w, char *actionName, XEvent *event,
String *params, Cardinal numParams);
static int isMouseAction(const char *action);
static int isRedundantAction(const char *action);
static int isIgnoredAction(const char *action);
static int readCheckMacroString(Widget dialogParent, char *string,
WindowInfo *runWindow, const char *errIn, char **errPos);
static void bannerTimeoutProc(XtPointer clientData, XtIntervalId *id);
static Boolean continueWorkProc(XtPointer clientData);
static int escapeStringChars(char *fromString, char *toString);
static int escapedStringLength(char *string);
static int lengthMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int minMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int maxMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int focusWindowMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int getRangeMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int getCharacterMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int replaceRangeMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int replaceSelectionMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int getSelectionMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int validNumberMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int replaceInStringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int replaceSubstringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int readFileMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int writeFileMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int appendFileMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int writeOrAppendFile(int append, WindowInfo *window,
DataValue *argList, int nArgs, DataValue *result, char **errMsg);
static int substringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int toupperMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int tolowerMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int stringToClipboardMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int clipboardToStringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int searchMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int searchStringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int setCursorPosMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int beepMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int selectMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int selectRectangleMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int tPrintMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int getenvMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int shellCmdMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int dialogMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static void dialogBtnCB(Widget w, XtPointer clientData, XtPointer callData);
static void dialogCloseCB(Widget w, XtPointer clientData, XtPointer callData);
#ifdef LESSTIF_VERSION
static void dialogEscCB(Widget w, XtPointer clientData, XEvent *event,
Boolean *cont);
#endif /* LESSTIF_VERSION */
static int stringDialogMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static void stringDialogBtnCB(Widget w, XtPointer clientData,
XtPointer callData);
static void stringDialogCloseCB(Widget w, XtPointer clientData,
XtPointer callData);
#ifdef LESSTIF_VERSION
static void stringDialogEscCB(Widget w, XtPointer clientData, XEvent *event,
Boolean *cont);
#endif /* LESSTIF_VERSION */
static int calltipMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int killCalltipMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
/* T Balinski */
static int listDialogMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static void listDialogBtnCB(Widget w, XtPointer clientData,
XtPointer callData);
static void listDialogCloseCB(Widget w, XtPointer clientData,
XtPointer callData);
/* T Balinski End */
#ifdef LESSTIF_VERSION
static void listDialogEscCB(Widget w, XtPointer clientData, XEvent *event,
Boolean *cont);
#endif /* LESSTIF_VERSION */
static int stringCompareMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int splitMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
/* DISASBLED for 5.4
static int setBacklightStringMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg);
*/
static int cursorMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int lineMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int columnMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int fileNameMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int filePathMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int lengthMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int selectionStartMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int selectionEndMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int selectionLeftMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int selectionRightMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int statisticsLineMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int incSearchLineMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int showLineNumbersMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int autoIndentMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int wrapTextMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int highlightSyntaxMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int makeBackupCopyMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int incBackupMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int showMatchingMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int matchSyntaxBasedMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int overTypeModeMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int readOnlyMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int lockedMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int fileFormatMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int fontNameMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int fontNameItalicMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int fontNameBoldMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int fontNameBoldItalicMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int subscriptSepMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int minFontWidthMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int maxFontWidthMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int wrapMarginMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int topLineMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int numDisplayLinesMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int displayWidthMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int activePaneMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int nPanesMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int emptyArrayMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int serverNameMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int tabDistMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int emTabDistMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int useTabsMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int modifiedMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int languageModeMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int calltipIDMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int readSearchArgs(DataValue *argList, int nArgs, int*searchDirection,
int *searchType, int *wrap, char **errMsg);
static int wrongNArgsErr(char **errMsg);
static int tooFewArgsErr(char **errMsg);
static int strCaseCmp(char *str1, char *str2);
static int readIntArg(DataValue dv, int *result, char **errMsg);
static int readStringArg(DataValue dv, char **result, char *stringStorage,
char **errMsg);
/* DISABLED FOR 5.4
static int backlightStringMV(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg);
*/
static int rangesetListMV(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg);
static int versionMV(WindowInfo* window, DataValue* argList, int nArgs,
DataValue* result, char** errMsg);
static int rangesetCreateMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int rangesetDestroyMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int rangesetGetByNameMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int rangesetAddMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int rangesetSubtractMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int rangesetInvertMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int rangesetInfoMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int rangesetRangeMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int rangesetIncludesPosMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg);
static int rangesetSetColorMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg);
static int rangesetSetNameMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg);
static int rangesetSetModeMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg);
static int fillPatternResult(DataValue *result, char **errMsg, WindowInfo *window,
char *patternName, Boolean preallocatedPatternName, Boolean includeName,
char *styleName, int bufferPos);
static int getPatternByNameMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int getPatternAtPosMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int fillStyleResult(DataValue *result, char **errMsg,
WindowInfo *window, char *styleName, Boolean preallocatedStyleName,
Boolean includeName, int patCode, int bufferPos);
static int getStyleByNameMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int getStyleAtPosMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg);
static int filenameDialogMS(WindowInfo* window, DataValue* argList, int nArgs,
DataValue* result, char** errMsg);
/* Built-in subroutines and variables for the macro language */
static BuiltInSubr MacroSubrs[] = {lengthMS, getRangeMS, tPrintMS,
dialogMS, stringDialogMS, replaceRangeMS, replaceSelectionMS,
setCursorPosMS, getCharacterMS, minMS, maxMS, searchMS,
searchStringMS, substringMS, replaceSubstringMS, readFileMS,
writeFileMS, appendFileMS, beepMS, getSelectionMS, validNumberMS,
replaceInStringMS, selectMS, selectRectangleMS, focusWindowMS,
shellCmdMS, stringToClipboardMS, clipboardToStringMS, toupperMS,
tolowerMS, listDialogMS, getenvMS,
stringCompareMS, splitMS, calltipMS, killCalltipMS,
/* DISABLED for 5.4 setBacklightStringMS,*/
rangesetCreateMS, rangesetDestroyMS,
rangesetAddMS, rangesetSubtractMS, rangesetInvertMS,
rangesetInfoMS, rangesetRangeMS, rangesetIncludesPosMS,
rangesetSetColorMS, rangesetSetNameMS, rangesetSetModeMS,
rangesetGetByNameMS,
getPatternByNameMS, getPatternAtPosMS,
getStyleByNameMS, getStyleAtPosMS, filenameDialogMS
};
#define N_MACRO_SUBRS (sizeof MacroSubrs/sizeof *MacroSubrs)
static const char *MacroSubrNames[N_MACRO_SUBRS] = {"length", "get_range", "t_print",
"dialog", "string_dialog", "replace_range", "replace_selection",
"set_cursor_pos", "get_character", "min", "max", "search",
"search_string", "substring", "replace_substring", "read_file",
"write_file", "append_file", "beep", "get_selection", "valid_number",
"replace_in_string", "select", "select_rectangle", "focus_window",
"shell_command", "string_to_clipboard", "clipboard_to_string",
"toupper", "tolower", "list_dialog", "getenv",
"string_compare", "split", "calltip", "kill_calltip",
/* DISABLED for 5.4 "set_backlight_string", */
"rangeset_create", "rangeset_destroy",
"rangeset_add", "rangeset_subtract", "rangeset_invert",
"rangeset_info", "rangeset_range", "rangeset_includes",
"rangeset_set_color", "rangeset_set_name", "rangeset_set_mode",
"rangeset_get_by_name",
"get_pattern_by_name", "get_pattern_at_pos",
"get_style_by_name", "get_style_at_pos", "filename_dialog"
};
static BuiltInSubr SpecialVars[] = {cursorMV, lineMV, columnMV,
fileNameMV, filePathMV, lengthMV, selectionStartMV, selectionEndMV,
selectionLeftMV, selectionRightMV, wrapMarginMV, tabDistMV,
emTabDistMV, useTabsMV, languageModeMV, modifiedMV,
statisticsLineMV, incSearchLineMV, showLineNumbersMV,
autoIndentMV, wrapTextMV, highlightSyntaxMV,
makeBackupCopyMV, incBackupMV, showMatchingMV, matchSyntaxBasedMV,
overTypeModeMV, readOnlyMV, lockedMV, fileFormatMV,
fontNameMV, fontNameItalicMV,
fontNameBoldMV, fontNameBoldItalicMV, subscriptSepMV,
minFontWidthMV, maxFontWidthMV, topLineMV, numDisplayLinesMV,
displayWidthMV, activePaneMV, nPanesMV, emptyArrayMV,
serverNameMV, calltipIDMV,
/* DISABLED for 5.4 backlightStringMV, */
rangesetListMV, versionMV
};
#define N_SPECIAL_VARS (sizeof SpecialVars/sizeof *SpecialVars)
static const char *SpecialVarNames[N_SPECIAL_VARS] = {"$cursor", "$line", "$column",
"$file_name", "$file_path", "$text_length", "$selection_start",
"$selection_end", "$selection_left", "$selection_right",
"$wrap_margin", "$tab_dist", "$em_tab_dist", "$use_tabs",
"$language_mode", "$modified",
"$statistics_line", "$incremental_search_line", "$show_line_numbers",
"$auto_indent", "$wrap_text", "$highlight_syntax",
"$make_backup_copy", "$incremental_backup", "$show_matching", "$match_syntax_based",
"$overtype_mode", "$read_only", "$locked", "$file_format",
"$font_name", "$font_name_italic",
"$font_name_bold", "$font_name_bold_italic", "$sub_sep",
"$min_font_width", "$max_font_width", "$top_line", "$n_display_lines",
"$display_width", "$active_pane", "$n_panes", "$empty_array",
"$server_name", "$calltip_ID",
/* DISABLED for 5.4 "$backlight_string", */
"$rangeset_list", "$VERSION"
};
/* Global symbols for returning values from built-in functions */
#define N_RETURN_GLOBALS 5
enum retGlobalSyms {STRING_DIALOG_BUTTON, SEARCH_END, READ_STATUS,
SHELL_CMD_STATUS, LIST_DIALOG_BUTTON};
static const char *ReturnGlobalNames[N_RETURN_GLOBALS] = {"$string_dialog_button",
"$search_end", "$read_status", "$shell_cmd_status",
"$list_dialog_button"};
static Symbol *ReturnGlobals[N_RETURN_GLOBALS];
/* List of actions not useful when learning a macro sequence (also see below) */
static char* IgnoredActions[] = {"focusIn", "focusOut"};
/* List of actions intended to be attached to mouse buttons, which the user
must be warned can't be recorded in a learn/replay sequence */
static const char* MouseActions[] = {"grab_focus", "extend_adjust", "extend_start",
"extend_end", "secondary_or_drag_adjust", "secondary_adjust",
"secondary_or_drag_start", "secondary_start", "move_destination",
"move_to", "move_to_or_end_drag", "copy_to", "copy_to_or_end_drag",
"exchange", "process_bdrag", "mouse_pan"};
/* List of actions to not record because they
generate further actions, more suitable for recording */
static const char* RedundantActions[] = {"open_dialog", "save_as_dialog",
"revert_to_saved_dialog", "include_file_dialog", "load_macro_file_dialog",
"load_tags_file_dialog", "find_dialog", "replace_dialog",
"goto_line_number_dialog", "mark_dialog", "goto_mark_dialog",
"control_code_dialog", "filter_selection_dialog", "execute_command_dialog",
"repeat_dialog", "start_incremental_find"};
/* The last command executed (used by the Repeat command) */
static char *LastCommand = NULL;
/* The current macro to execute on Replay command */
static char *ReplayMacro = NULL;
/* Buffer where macro commands are recorded in Learn mode */
static textBuffer *MacroRecordBuf = NULL;
/* Action Hook id for recording actions for Learn mode */
static XtActionHookId MacroRecordActionHook = 0;
/* Window where macro recording is taking place */
static WindowInfo *MacroRecordWindow = NULL;
/* Arrays for translating escape characters in escapeStringChars */
static char ReplaceChars[] = "\\\"ntbrfav";
static char EscapeChars[] = "\\\"\n\t\b\r\f\a\v";
/*
** Install built-in macro subroutines and special variables for accessing
** editor information
*/
void RegisterMacroSubroutines(void)
{
static DataValue subrPtr = {NO_TAG, {0}}, noValue = {NO_TAG, {0}};
unsigned i;
/* Install symbols for built-in routines and variables, with pointers
to the appropriate c routines to do the work */
for (i=0; i<N_MACRO_SUBRS; i++) {
subrPtr.val.subr = MacroSubrs[i];
InstallSymbol(MacroSubrNames[i], C_FUNCTION_SYM, subrPtr);
}
for (i=0; i<N_SPECIAL_VARS; i++) {
subrPtr.val.subr = SpecialVars[i];
InstallSymbol(SpecialVarNames[i], PROC_VALUE_SYM, subrPtr);
}
/* Define global variables used for return values, remember their
locations so they can be set without a LookupSymbol call */
for (i=0; i<N_RETURN_GLOBALS; i++)
ReturnGlobals[i] = InstallSymbol(ReturnGlobalNames[i], GLOBAL_SYM,
noValue);
}
#define MAX_LEARN_MSG_LEN ((2 * MAX_ACCEL_LEN) + 60)
void BeginLearn(WindowInfo *window)
{
WindowInfo *win;
XmString s;
XmString xmFinish;
XmString xmCancel;
char *cFinish;
char *cCancel;
char message[MAX_LEARN_MSG_LEN];
/* If we're already in learn mode, return */
if (MacroRecordActionHook != 0)
return;
/* dim the inappropriate menus and items, and undim finish and cancel */
for (win=WindowList; win!=NULL; win=win->next) {
if (!IsTopDocument(win))
continue;
XtSetSensitive(win->learnItem, False);
}
SetSensitive(window, window->finishLearnItem, True);
XtVaSetValues(window->cancelMacroItem, XmNlabelString,
s=XmStringCreateSimple("Cancel Learn"), NULL);
XmStringFree(s);
SetSensitive(window, window->cancelMacroItem, True);
/* Mark the window where learn mode is happening */
MacroRecordWindow = window;
/* Allocate a text buffer for accumulating the macro strings */
MacroRecordBuf = BufCreate();
/* Add the action hook for recording the actions */
MacroRecordActionHook =
XtAppAddActionHook(XtWidgetToApplicationContext(window->shell),
learnActionHook, window);
/* Extract accelerator texts from menu PushButtons */
XtVaGetValues(window->finishLearnItem, XmNacceleratorText, &xmFinish, NULL);
XtVaGetValues(window->cancelMacroItem, XmNacceleratorText, &xmCancel, NULL);
/* Translate Motif strings to char* */
cFinish = GetXmStringText(xmFinish);
cCancel = GetXmStringText(xmCancel);
/* Free Motif Strings */
XmStringFree(xmFinish);
XmStringFree(xmCancel);
/* Create message */
if (cFinish[0] == '\0') {
if (cCancel[0] == '\0') {
strncpy(message, "Learn Mode -- Use menu to finish or cancel",
MAX_LEARN_MSG_LEN);
message[MAX_LEARN_MSG_LEN - 1] = '\0';
}
else {
sprintf(message,
"Learn Mode -- Use menu to finish, press %s to cancel",
cCancel);
}
}
else {
if (cCancel[0] == '\0') {
sprintf(message,
"Learn Mode -- Press %s to finish, use menu to cancel",
cFinish);
}
else {
sprintf(message,
"Learn Mode -- Press %s to finish, %s to cancel",
cFinish,
cCancel);
}
}
/* Free C-strings */
NEditFree(cFinish);
NEditFree(cCancel);
/* Put up the learn-mode banner */
SetModeMessage(window, message);
}
void AddLastCommandActionHook(XtAppContext context)
{
XtAppAddActionHook(context, lastActionHook, NULL);
}
void FinishLearn(void)
{
WindowInfo *win;
/* If we're not in learn mode, return */
if (MacroRecordActionHook == 0)
return;
/* Remove the action hook */
XtRemoveActionHook(MacroRecordActionHook);
MacroRecordActionHook = 0;
/* Free the old learn/replay sequence */
NEditFree(ReplayMacro);
/* Store the finished action for the replay menu item */
ReplayMacro = BufGetAll(MacroRecordBuf);
/* Free the buffer used to accumulate the macro sequence */
BufFree(MacroRecordBuf);
/* Undim the menu items dimmed during learn */
for (win=WindowList; win!=NULL; win=win->next) {
if (!IsTopDocument(win))
continue;
XtSetSensitive(win->learnItem, True);
}
if (IsTopDocument(MacroRecordWindow)) {
XtSetSensitive(MacroRecordWindow->finishLearnItem, False);
XtSetSensitive(MacroRecordWindow->cancelMacroItem, False);
}
/* Undim the replay and paste-macro buttons */
for (win=WindowList; win!=NULL; win=win->next) {
if (!IsTopDocument(win))
continue;
XtSetSensitive(win->replayItem, True);
}
DimPasteReplayBtns(True);
/* Clear learn-mode banner */
ClearModeMessage(MacroRecordWindow);
}
/*
** Cancel Learn mode, or macro execution (they're bound to the same menu item)
*/
void CancelMacroOrLearn(WindowInfo *window)
{
if (MacroRecordActionHook != 0)
cancelLearn();
else if (window->macroCmdData != NULL)
AbortMacroCommand(window);
}
static void cancelLearn(void)
{
WindowInfo *win;
/* If we're not in learn mode, return */
if (MacroRecordActionHook == 0)
return;
/* Remove the action hook */
XtRemoveActionHook(MacroRecordActionHook);
MacroRecordActionHook = 0;
/* Free the macro under construction */
BufFree(MacroRecordBuf);
/* Undim the menu items dimmed during learn */
for (win=WindowList; win!=NULL; win=win->next) {
if (!IsTopDocument(win))
continue;
XtSetSensitive(win->learnItem, True);
}
if (IsTopDocument(MacroRecordWindow)) {
XtSetSensitive(MacroRecordWindow->finishLearnItem, False);
XtSetSensitive(MacroRecordWindow->cancelMacroItem, False);
}
/* Clear learn-mode banner */
ClearModeMessage(MacroRecordWindow);
}
/*
** Execute the learn/replay sequence stored in "window"
*/
void Replay(WindowInfo *window)
{
Program *prog;
char *errMsg, *stoppedAt;
/* Verify that a replay macro exists and it's not empty and that */
/* we're not already running a macro */
if (ReplayMacro != NULL &&
ReplayMacro[0] != 0 &&
window->macroCmdData == NULL) {
/* Parse the replay macro (it's stored in text form) and compile it into
an executable program "prog" */
prog = ParseMacro(ReplayMacro, &errMsg, &stoppedAt);
if (prog == NULL) {
fprintf(stderr,
"NEdit internal error, learn/replay macro syntax error: %s\n",
errMsg);
return;
}
/* run the executable program */
runMacro(window, prog);
}
}
/*
** Read the initial NEdit macro file if one exists.
*/
void ReadMacroInitFile(WindowInfo *window)
{
const char* autoloadName = GetRCFileName(AUTOLOAD_NM);
static int initFileLoaded = False;
/* GetRCFileName() might return NULL if an error occurs during
creation of the preference file directory. */
if (autoloadName != NULL && !initFileLoaded)
{
ReadMacroFile(window, autoloadName, False);
initFileLoaded = True;
}
}
/*
** Read an NEdit macro file. Extends the syntax of the macro parser with
** define keyword, and allows intermixing of defines with immediate actions.
*/
int ReadMacroFile(WindowInfo *window, const char *fileName, int warnNotExist)
{
int result;
char *fileString;
/* read-in macro file and force a terminating \n, to prevent syntax
** errors with statements on the last line
*/
fileString = ReadAnyTextFile(fileName, True);
if (fileString == NULL){
if (errno != ENOENT || warnNotExist)
{
DialogF(DF_ERR, window->shell, 1, "Read Macro",
"Error reading macro file %s: %s", "OK", fileName,
#ifdef VMS
strerror(errno, vaxc$errno));
#else
strerror(errno));
#endif
}
return False;
}
/* Parse fileString */
result = readCheckMacroString(window->shell, fileString, window, fileName,
NULL);
NEditFree(fileString);
return result;
}
/*
** Parse and execute a macro string including macro definitions. Report
** parsing errors in a dialog posted over window->shell.
*/
int ReadMacroString(WindowInfo *window, char *string, const char *errIn)
{
return readCheckMacroString(window->shell, string, window, errIn, NULL);
}
/*
** Check a macro string containing definitions for errors. Returns True
** if macro compiled successfully. Returns False and puts up
** a dialog explaining if macro did not compile successfully.
*/
int CheckMacroString(Widget dialogParent, char *string, const char *errIn,
char **errPos)
{
return readCheckMacroString(dialogParent, string, NULL, errIn, errPos);
}
/*
** Parse and optionally execute a macro string including macro definitions.
** Report parsing errors in a dialog posted over dialogParent, using the
** string errIn to identify the entity being parsed (filename, macro string,
** etc.). If runWindow is specified, runs the macro against the window. If
** runWindow is passed as NULL, does parse only. If errPos is non-null,
** returns a pointer to the error location in the string.
*/
static int readCheckMacroString(Widget dialogParent, char *string,
WindowInfo *runWindow, const char *errIn, char **errPos)
{
char *stoppedAt, *inPtr, *namePtr, *errMsg;
char subrName[MAX_SYM_LEN];
Program *prog;
Symbol *sym;
DataValue subrPtr;
Stack* progStack = (Stack*) NEditMalloc(sizeof(Stack));
progStack->top = NULL;
progStack->size = 0;
inPtr = string;
while (*inPtr != '\0') {
/* skip over white space and comments */
while (*inPtr==' ' || *inPtr=='\t' || *inPtr=='\n'|| *inPtr=='#') {
if (*inPtr == '#')
while (*inPtr != '\n' && *inPtr != '\0') inPtr++;
else
inPtr++;
}
if (*inPtr == '\0')
break;
/* look for define keyword, and compile and store defined routines */
if (!strncmp(inPtr, "define", 6) && (inPtr[6]==' ' || inPtr[6]=='\t')) {
inPtr += 6;
inPtr += strspn(inPtr, " \t\n");
namePtr = subrName;
while ((namePtr < &subrName[MAX_SYM_LEN - 1])
&& (isalnum((unsigned char)*inPtr) || *inPtr == '_')) {
*namePtr++ = *inPtr++;
}
*namePtr = '\0';
if (isalnum((unsigned char)*inPtr) || *inPtr == '_') {
return ParseError(dialogParent, string, inPtr, errIn,
"subroutine name too long");
}
inPtr += strspn(inPtr, " \t\n");
if (*inPtr != '{') {
if (errPos != NULL) *errPos = stoppedAt;
return ParseError(dialogParent, string, inPtr,
errIn, "expected '{'");
}
prog = ParseMacro(inPtr, &errMsg, &stoppedAt);
if (prog == NULL) {
if (errPos != NULL) *errPos = stoppedAt;
return ParseError(dialogParent, string, stoppedAt,
errIn, errMsg);
}
if (runWindow != NULL) {
sym = LookupSymbol(subrName);
if (sym == NULL) {
subrPtr.val.prog = prog;
subrPtr.tag = NO_TAG;
sym = InstallSymbol(subrName, MACRO_FUNCTION_SYM, subrPtr);
} else {
if (sym->type == MACRO_FUNCTION_SYM)
FreeProgram(sym->value.val.prog);
else
sym->type = MACRO_FUNCTION_SYM;
sym->value.val.prog = prog;
}
}
inPtr = stoppedAt;
/* Parse and execute immediate (outside of any define) macro commands
and WAIT for them to finish executing before proceeding. Note that
the code below is not perfect. If you interleave code blocks with
definitions in a file which is loaded from another macro file, it
will probably run the code blocks in reverse order! */
} else {
prog = ParseMacro(inPtr, &errMsg, &stoppedAt);
if (prog == NULL) {
if (errPos != NULL) {
*errPos = stoppedAt;
}
return ParseError(dialogParent, string, stoppedAt,
errIn, errMsg);
}
if (runWindow != NULL) {
XEvent nextEvent;
if (runWindow->macroCmdData == NULL) {
runMacro(runWindow, prog);
while (runWindow->macroCmdData != NULL) {
XtAppNextEvent(XtWidgetToApplicationContext(
runWindow->shell), &nextEvent);
ServerDispatchEvent(&nextEvent);
}
} else {
/* If we come here this means that the string was parsed
from within another macro via load_macro_file(). In
this case, plain code segments outside of define
blocks are rolled into one Program each and put on
the stack. At the end, the stack is unrolled, so the
plain Programs would be executed in the wrong order.
So we don't hand the Programs over to the interpreter
just yet (via RunMacroAsSubrCall()), but put it on a
stack of our own, reversing order once again. */
Push(progStack, (void*) prog);
}
}
inPtr = stoppedAt;
}
}
/* Unroll reversal stack for macros loaded from macros. */
while (NULL != (prog = (Program*) Pop(progStack))) {
RunMacroAsSubrCall(prog);
}
/* This stack is empty, so just free it without checking the members. */
NEditFree(progStack);
return True;
}
/*
** Run a pre-compiled macro, changing the interface state to reflect that
** a macro is running, and handling preemption, resumption, and cancellation.
** frees prog when macro execution is complete;
*/
static void runMacro(WindowInfo *window, Program *prog)
{
DataValue result;
char *errMsg;
int stat;
macroCmdInfo *cmdData;
XmString s;
/* If a macro is already running, just call the program as a subroutine,
instead of starting a new one, so we don't have to keep a separate
context, and the macros will serialize themselves automatically */
if (window->macroCmdData != NULL) {
RunMacroAsSubrCall(prog);
return;
}
/* put up a watch cursor over the waiting window */
BeginWait(window->shell);
/* enable the cancel menu item */
XtVaSetValues(window->cancelMacroItem, XmNlabelString,
s=XmStringCreateSimple("Cancel Macro"), NULL);
XmStringFree(s);
SetSensitive(window, window->cancelMacroItem, True);
/* Create a data structure for passing macro execution information around
amongst the callback routines which will process i/o and completion */
cmdData = (macroCmdInfo *)NEditMalloc(sizeof(macroCmdInfo));
window->macroCmdData = cmdData;
cmdData->bannerIsUp = False;
cmdData->closeOnCompletion = False;
cmdData->program = prog;
cmdData->context = NULL;
cmdData->continueWorkProcID = 0;
cmdData->dialog = NULL;
/* Set up timer proc for putting up banner when macro takes too long */
cmdData->bannerTimeoutID = XtAppAddTimeOut(
XtWidgetToApplicationContext(window->shell), BANNER_WAIT_TIME,
bannerTimeoutProc, window);
/* Begin macro execution */
stat = ExecuteMacro(window, prog, 0, NULL, &result, &cmdData->context,
&errMsg);
if (stat == MACRO_ERROR)
{
finishMacroCmdExecution(window);
DialogF(DF_ERR, window->shell, 1, "Macro Error",
"Error executing macro: %s", "OK", errMsg);
return;
}
if (stat == MACRO_DONE) {
finishMacroCmdExecution(window);
return;
}
if (stat == MACRO_TIME_LIMIT) {
ResumeMacroExecution(window);
return;
}
/* (stat == MACRO_PREEMPT) Macro was preempted */
}
/*
** Continue with macro execution after preemption. Called by the routines
** whose actions cause preemption when they have completed their lengthy tasks.
** Re-establishes macro execution work proc. Window must be the window in
** which the macro is executing (the window to which macroCmdData is attached),
** and not the window to which operations are focused.
*/
void ResumeMacroExecution(WindowInfo *window)
{
macroCmdInfo *cmdData = (macroCmdInfo *)window->macroCmdData;
if (cmdData != NULL)
cmdData->continueWorkProcID = XtAppAddWorkProc(
XtWidgetToApplicationContext(window->shell),
continueWorkProc, window);
}
/*
** Cancel the macro command in progress (user cancellation via GUI)
*/
void AbortMacroCommand(WindowInfo *window)
{
if (window->macroCmdData == NULL)
return;
/* If there's both a macro and a shell command executing, the shell command
must have been called from the macro. When called from a macro, shell
commands don't put up cancellation controls of their own, but rely
instead on the macro cancellation mechanism (here) */
#ifndef VMS
if (window->shellCmdData != NULL)
AbortShellCommand(window);
#endif
/* Free the continuation */
FreeRestartData(((macroCmdInfo *)window->macroCmdData)->context);
/* Kill the macro command */
finishMacroCmdExecution(window);
}
/*
** Call this before closing a window, to clean up macro references to the
** window, stop any macro which might be running from it, free associated
** memory, and check that a macro is not attempting to close the window from
** which it is run. If this is being called from a macro, and the window
** this routine is examining is the window from which the macro was run, this
** routine will return False, and the caller must NOT CLOSE THE WINDOW.
** Instead, empty it and make it Untitled, and let the macro completion
** process close the window when the macro is finished executing.
*/
int MacroWindowCloseActions(WindowInfo *window)
{
macroCmdInfo *mcd, *cmdData = window->macroCmdData;
WindowInfo *w;
if (MacroRecordActionHook != 0 && MacroRecordWindow == window) {
FinishLearn();
}
/* If no macro is executing in the window, allow the close, but check
if macros executing in other windows have it as focus. If so, set
their focus back to the window from which they were originally run */
if (cmdData == NULL) {
for (w=WindowList; w!=NULL; w=w->next) {
mcd = (macroCmdInfo *)w->macroCmdData;
if (w == MacroRunWindow() && MacroFocusWindow() == window)
SetMacroFocusWindow(MacroRunWindow());
else if (mcd != NULL && mcd->context->focusWindow == window)
mcd->context->focusWindow = mcd->context->runWindow;
}
return True;
}
/* If the macro currently running (and therefore calling us, because
execution must otherwise return to the main loop to execute any
commands), is running in this window, tell the caller not to close,
and schedule window close on completion of macro */
if (window == MacroRunWindow()) {
cmdData->closeOnCompletion = True;
return False;
}
/* Free the continuation */
FreeRestartData(cmdData->context);
/* Kill the macro command */
finishMacroCmdExecution(window);
return True;
}
/*
** Clean up after the execution of a macro command: free memory, and restore
** the user interface state.
*/
static void finishMacroCmdExecution(WindowInfo *window)
{
macroCmdInfo *cmdData = window->macroCmdData;
int closeOnCompletion = cmdData->closeOnCompletion;
XmString s;
XClientMessageEvent event;
/* Cancel pending timeout and work proc */
if (cmdData->bannerTimeoutID != 0)
XtRemoveTimeOut(cmdData->bannerTimeoutID);
if (cmdData->continueWorkProcID != 0)
XtRemoveWorkProc(cmdData->continueWorkProcID);
/* Clean up waiting-for-macro-command-to-complete mode */
EndWait(window->shell);
XtVaSetValues(window->cancelMacroItem, XmNlabelString,
s=XmStringCreateSimple("Cancel Learn"), NULL);
XmStringFree(s);
SetSensitive(window, window->cancelMacroItem, False);
if (cmdData->bannerIsUp)
ClearModeMessage(window);
/* If a dialog was up, get rid of it */
if (cmdData->dialog != NULL)
XtDestroyWidget(XtParent(cmdData->dialog));
/* Free execution information */
FreeProgram(cmdData->program);
NEditFree(cmdData);
window->macroCmdData = NULL;
/* If macro closed its own window, window was made empty and untitled,
but close was deferred until completion. This is completion, so if
the window is still empty, do the close */
if (closeOnCompletion && !window->filenameSet && !window->fileChanged) {
CloseWindow(window);
window = NULL;
}
/* If no other macros are executing, do garbage collection */
SafeGC();
/* In processing the .neditmacro file (and possibly elsewhere), there
is an event loop which waits for macro completion. Send an event
to wake up that loop, otherwise execution will stall until the user
does something to the window. */
if (!closeOnCompletion) {
event.format = 8;
event.type = ClientMessage;
XSendEvent(XtDisplay(window->shell), XtWindow(window->shell), False,
NoEventMask, (XEvent *)&event);
}
}
/*
** Do garbage collection of strings if there are no macros currently
** executing. NEdit's macro language GC strategy is to call this routine
** whenever a macro completes. If other macros are still running (preempted
** or waiting for a shell command or dialog), this does nothing and therefore
** defers GC to the completion of the last macro out.
*/
void SafeGC(void)
{
WindowInfo *win;
for (win=WindowList; win!=NULL; win=win->next)
if (win->macroCmdData != NULL || InSmartIndentMacros(win))
return;
GarbageCollectStrings();
}
/*
** Executes macro string "macro" using the lastFocus pane in "window".
** Reports errors via a dialog posted over "window", integrating the name
** "errInName" into the message to help identify the source of the error.
*/
void DoMacro(WindowInfo *window, const char *macro, const char *errInName)
{
Program *prog;
char *errMsg, *stoppedAt, *tMacro;
int macroLen;
/* Add a terminating newline (which command line users are likely to omit
since they are typically invoking a single routine) */
macroLen = strlen(macro);
tMacro = (char*)NEditMalloc(strlen(macro)+2);
strncpy(tMacro, macro, macroLen);
tMacro[macroLen] = '\n';
tMacro[macroLen+1] = '\0';
/* Parse the macro and report errors if it fails */
prog = ParseMacro(tMacro, &errMsg, &stoppedAt);
if (prog == NULL) {
ParseError(window->shell, tMacro, stoppedAt, errInName, errMsg);
NEditFree(tMacro);
return;
}
NEditFree(tMacro);
/* run the executable program (prog is freed upon completion) */
runMacro(window, prog);
}
/*
** Get the current Learn/Replay macro in text form. Returned string is a
** pointer to the stored macro and should not be freed by the caller (and
** will cease to exist when the next replay macro is installed)
*/
char *GetReplayMacro(void)
{
return ReplayMacro;
}
/*
** Present the user a dialog for "Repeat" command
*/
void RepeatDialog(WindowInfo *window)
{
Widget form, selBox, radioBox, timesForm;
repeatDialog *rd;
Arg selBoxArgs[1];
char *lastCmdLabel, *parenChar;
XmString s1;
int cmdNameLen;
if (LastCommand == NULL)
{
DialogF(DF_WARN, window->shell, 1, "Repeat Macro",
"No previous commands or learn/\nreplay sequences to repeat",
"OK");
return;
}
/* Remeber the last command, since the user is allowed to work in the
window while the dialog is up */
rd = (repeatDialog *)NEditMalloc(sizeof(repeatDialog));
rd->lastCommand = NEditStrdup(LastCommand);
/* make a label for the Last command item of the dialog, which includes
the last executed action name */
parenChar = strchr(LastCommand, '(');
if (parenChar == NULL)
return;
cmdNameLen = parenChar-LastCommand;
lastCmdLabel = (char*)NEditMalloc(16 + cmdNameLen);
strcpy(lastCmdLabel, "Last Command (");
strncpy(&lastCmdLabel[14], LastCommand, cmdNameLen);
strcpy(&lastCmdLabel[14 + cmdNameLen], ")");
XtSetArg(selBoxArgs[0], XmNautoUnmanage, False);
selBox = CreatePromptDialog(window->shell, "repeat", selBoxArgs, 1);
rd->shell = XtParent(selBox);
XtAddCallback(rd->shell, XmNdestroyCallback, repeatDestroyCB, rd);
XtAddCallback(selBox, XmNokCallback, repeatOKCB, rd);
XtAddCallback(selBox, XmNapplyCallback, repeatApplyCB, rd);
XtAddCallback(selBox, XmNcancelCallback, repeatCancelCB, rd);
XtUnmanageChild(XmSelectionBoxGetChild(selBox, XmDIALOG_TEXT));
XtUnmanageChild(XmSelectionBoxGetChild(selBox, XmDIALOG_SELECTION_LABEL));
XtUnmanageChild(XmSelectionBoxGetChild(selBox, XmDIALOG_HELP_BUTTON));
XtUnmanageChild(XmSelectionBoxGetChild(selBox, XmDIALOG_APPLY_BUTTON));
XtVaSetValues(XtParent(selBox), XmNtitle, "Repeat Macro", NULL);
AddMotifCloseCallback(XtParent(selBox), repeatCancelCB, rd);
form = XtVaCreateManagedWidget("form", xmFormWidgetClass, selBox, NULL);
radioBox = XtVaCreateManagedWidget("cmdSrc", xmRowColumnWidgetClass, form,
XmNradioBehavior, True,
XmNorientation, XmHORIZONTAL,
XmNpacking, XmPACK_TIGHT,
XmNtopAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_FORM, NULL);
rd->lastCmdToggle = XtVaCreateManagedWidget("lastCmdToggle",
xmToggleButtonWidgetClass, radioBox, XmNset, True,
XmNlabelString, s1=XmStringCreateSimple(lastCmdLabel),
XmNmnemonic, 'C', NULL);
XmStringFree(s1);
NEditFree(lastCmdLabel);
XtVaCreateManagedWidget("learnReplayToggle",
xmToggleButtonWidgetClass, radioBox, XmNset, False,
XmNlabelString,
s1=XmStringCreateSimple("Learn/Replay"),
XmNmnemonic, 'L',
XmNsensitive, ReplayMacro != NULL, NULL);
XmStringFree(s1);
timesForm = XtVaCreateManagedWidget("form", xmFormWidgetClass, form,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, radioBox,
XmNtopOffset, 10,
XmNleftAttachment, XmATTACH_FORM, NULL);
radioBox = XtVaCreateManagedWidget("method", xmRowColumnWidgetClass,
timesForm,
XmNradioBehavior, True,
XmNorientation, XmHORIZONTAL,
XmNpacking, XmPACK_TIGHT,
XmNtopAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_FORM, NULL);
rd->inSelToggle = XtVaCreateManagedWidget("inSelToggle",
xmToggleButtonWidgetClass, radioBox, XmNset, False,
XmNlabelString, s1=XmStringCreateSimple("In Selection"),
XmNmnemonic, 'I', NULL);
XmStringFree(s1);
rd->toEndToggle = XtVaCreateManagedWidget("toEndToggle",
xmToggleButtonWidgetClass, radioBox, XmNset, False,
XmNlabelString, s1=XmStringCreateSimple("To End"),
XmNmnemonic, 'T', NULL);
XmStringFree(s1);
XtVaCreateManagedWidget("nTimesToggle",
xmToggleButtonWidgetClass, radioBox, XmNset, True,
XmNlabelString, s1=XmStringCreateSimple("N Times"),
XmNmnemonic, 'N',
XmNset, True, NULL);
XmStringFree(s1);
rd->repeatText = XtVaCreateManagedWidget("repeatText", xmTextWidgetClass,
timesForm,
XmNcolumns, 5,
XmNtopAttachment, XmATTACH_FORM,
XmNbottomAttachment, XmATTACH_FORM,
XmNleftAttachment, XmATTACH_WIDGET,
XmNleftWidget, radioBox, NULL);
RemapDeleteKey(rd->repeatText);
/* Handle mnemonic selection of buttons and focus to dialog */
AddDialogMnemonicHandler(form, FALSE);
/* Set initial focus */
#if XmVersion >= 1002
XtVaSetValues(form, XmNinitialFocus, timesForm, NULL);
XtVaSetValues(timesForm, XmNinitialFocus, rd->repeatText, NULL);
#endif
/* put up dialog */
rd->forWindow = window;
ManageDialogCenteredOnPointer(selBox);
}
static void repeatOKCB(Widget w, XtPointer clientData, XtPointer callData)
{
repeatDialog *rd = (repeatDialog *)clientData;
if (doRepeatDialogAction(rd, ((XmAnyCallbackStruct *)callData)->event))
XtDestroyWidget(rd->shell);
}
/* Note that the apply button is not managed in the repeat dialog. The dialog
itself is capable of non-modal operation, but to be complete, it needs
to dynamically update last command, dimming of learn/replay, possibly a
stop button for the macro, and possibly in-selection with selection */
static void repeatApplyCB(Widget w, XtPointer clientData, XtPointer callData)
{
doRepeatDialogAction((repeatDialog *)clientData,
((XmAnyCallbackStruct *)callData)->event);
}
static int doRepeatDialogAction(repeatDialog *rd, XEvent *event)
{
int nTimes;
char nTimesStr[TYPE_INT_STR_SIZE(int)];
char *params[2];
/* Find out from the dialog how to repeat the command */
if (XmToggleButtonGetState(rd->inSelToggle))
{
if (!rd->forWindow->buffer->primary.selected)
{
DialogF(DF_WARN, rd->shell, 1, "Repeat Macro",
"No selection in window to repeat within", "OK");
XmProcessTraversal(rd->inSelToggle, XmTRAVERSE_CURRENT);
return False;
}
params[0] = "in_selection";
} else if (XmToggleButtonGetState(rd->toEndToggle))
{
params[0] = "to_end";
} else
{
if (GetIntTextWarn(rd->repeatText, &nTimes, "number of times", True)
!= TEXT_READ_OK)
{
XmProcessTraversal(rd->repeatText, XmTRAVERSE_CURRENT);
return False;
}
sprintf(nTimesStr, "%d", nTimes);
params[0] = nTimesStr;
}
/* Figure out which command user wants to repeat */
if (XmToggleButtonGetState(rd->lastCmdToggle))
params[1] = NEditStrdup(rd->lastCommand);
else {
if (ReplayMacro == NULL)
return False;
params[1] = NEditStrdup(ReplayMacro);
}
/* call the action routine repeat_macro to do the work */
XtCallActionProc(rd->forWindow->lastFocus, "repeat_macro", event, params,2);
NEditFree(params[1]);
return True;
}
static void repeatCancelCB(Widget w, XtPointer clientData, XtPointer callData)
{
repeatDialog *rd = (repeatDialog *)clientData;
XtDestroyWidget(rd->shell);
}
static void repeatDestroyCB(Widget w, XtPointer clientData, XtPointer callData)
{
repeatDialog *rd = (repeatDialog *)clientData;
NEditFree(rd->lastCommand);
NEditFree(rd);
}
/*
** Dispatches a macro to which repeats macro command in "command", either
** an integer number of times ("how" == positive integer), or within a
** selected range ("how" == REPEAT_IN_SEL), or to the end of the window
** ("how == REPEAT_TO_END).
**
** Note that as with most macro routines, this returns BEFORE the macro is
** finished executing
*/
void RepeatMacro(WindowInfo *window, const char *command, int how)
{
Program *prog;
char *errMsg, *stoppedAt, *loopMacro, *loopedCmd;
if (command == NULL)
return;
/* Wrap a for loop and counter/tests around the command */
if (how == REPEAT_TO_END)
loopMacro = "lastCursor=-1\nstartPos=$cursor\n\
while($cursor>=startPos&&$cursor!=lastCursor){\nlastCursor=$cursor\n%s\n}\n";
else if (how == REPEAT_IN_SEL)
loopMacro = "selStart = $selection_start\nif (selStart == -1)\nreturn\n\
selEnd = $selection_end\nset_cursor_pos(selStart)\nselect(0,0)\n\
boundText = get_range(selEnd, selEnd+10)\n\
while($cursor >= selStart && $cursor < selEnd && \\\n\
get_range(selEnd, selEnd+10) == boundText) {\n\
startLength = $text_length\n%s\n\
selEnd += $text_length - startLength\n}\n";
else
loopMacro = "for(i=0;i<%d;i++){\n%s\n}\n";
loopedCmd = (char*)NEditMalloc(strlen(command) + strlen(loopMacro) + 25);
if (how == REPEAT_TO_END || how == REPEAT_IN_SEL)
sprintf(loopedCmd, loopMacro, command);
else
sprintf(loopedCmd, loopMacro, how, command);
/* Parse the resulting macro into an executable program "prog" */
prog = ParseMacro(loopedCmd, &errMsg, &stoppedAt);
if (prog == NULL) {
fprintf(stderr, "NEdit internal error, repeat macro syntax wrong: %s\n",
errMsg);
return;
}
NEditFree(loopedCmd);
/* run the executable program */
runMacro(window, prog);
}
/*
** Macro recording action hook for Learn/Replay, added temporarily during
** learn.
*/
static void learnActionHook(Widget w, XtPointer clientData, String actionName,
XEvent *event, String *params, Cardinal *numParams)
{
WindowInfo *window;
int i;
char *actionString;
/* Select only actions in text panes in the window for which this
action hook is recording macros (from clientData). */
for (window=WindowList; window!=NULL; window=window->next) {
if (window->textArea == w)
break;
for (i=0; i<window->nPanes; i++) {
if (window->textPanes[i] == w)
break;
}
if (i < window->nPanes)
break;
}
if (window == NULL || window != (WindowInfo *)clientData)
return;
/* beep on un-recordable operations which require a mouse position, to
remind the user that the action was not recorded */
if (isMouseAction(actionName)) {
XBell(XtDisplay(w), 0);
return;
}
/* Record the action and its parameters */
actionString = actionToString(w, actionName, event, params, *numParams);
if (actionString != NULL) {
BufInsert(MacroRecordBuf, MacroRecordBuf->length, actionString);
NEditFree(actionString);
}
}
/*
** Permanent action hook for remembering last action for possible replay
*/
static void lastActionHook(Widget w, XtPointer clientData, String actionName,
XEvent *event, String *params, Cardinal *numParams)
{
WindowInfo *window;
int i;
char *actionString;
/* Find the window to which this action belongs */
for (window=WindowList; window!=NULL; window=window->next) {
if (window->textArea == w)
break;
for (i=0; i<window->nPanes; i++) {
if (window->textPanes[i] == w)
break;
}
if (i < window->nPanes)
break;
}
if (window == NULL)
return;
/* The last action is recorded for the benefit of repeating the last
action. Don't record repeat_macro and wipe out the real action */
if (!strcmp(actionName, "repeat_macro"))
return;
/* Record the action and its parameters */
actionString = actionToString(w, actionName, event, params, *numParams);
if (actionString != NULL) {
NEditFree(LastCommand);
LastCommand = actionString;
}
}
/*
** Create a macro string to represent an invocation of an action routine.
** Returns NULL for non-operational or un-recordable actions.
*/
static char *actionToString(Widget w, char *actionName, XEvent *event,
String *params, Cardinal numParams)
{
char chars[20], *charList[1], *outStr, *outPtr;
KeySym keysym;
int i, nChars, nParams, length, nameLength;
#ifndef NO_XMIM
int status;
#endif
if (isIgnoredAction(actionName) || isRedundantAction(actionName) ||
isMouseAction(actionName))
return NULL;
/* Convert self_insert actions, to insert_string */
if (!strcmp(actionName, "self_insert") ||
!strcmp(actionName, "self-insert")) {
actionName = "insert_string";
#ifdef NO_XMIM
nChars = XLookupString((XKeyEvent *)event, chars, 19, &keysym, NULL);
if (nChars == 0)
return NULL;
#else
nChars = XmImMbLookupString(w, (XKeyEvent *)event,
chars, 19, &keysym, &status);
if (nChars == 0 || status == XLookupNone ||
status == XLookupKeySym || status == XBufferOverflow)
return NULL;
#endif
chars[nChars] = '\0';
charList[0] = chars;
params = charList;
nParams = 1;
} else
nParams = numParams;
/* Figure out the length of string required */
nameLength = strlen(actionName);
length = nameLength + 3;
for (i=0; i<nParams; i++)
length += escapedStringLength(params[i]) + 4;
/* Allocate the string and copy the information to it */
outPtr = outStr = (char*)NEditMalloc(length + 1);
strcpy(outPtr, actionName);
outPtr += nameLength;
*outPtr++ = '(';
for (i=0; i<nParams; i++) {
*outPtr++ = '\"';
outPtr += escapeStringChars(params[i], outPtr);
*outPtr++ = '\"'; *outPtr++ = ','; *outPtr++ = ' ';
}
if (nParams != 0)
outPtr -= 2;
*outPtr++ = ')'; *outPtr++ = '\n'; *outPtr++ = '\0';
return outStr;
}
static int isMouseAction(const char *action)
{
int i;
for (i=0; i<(int)XtNumber(MouseActions); i++)
if (!strcmp(action, MouseActions[i]))
return True;
return False;
}
static int isRedundantAction(const char *action)
{
int i;
for (i=0; i<(int)XtNumber(RedundantActions); i++)
if (!strcmp(action, RedundantActions[i]))
return True;
return False;
}
static int isIgnoredAction(const char *action)
{
int i;
for (i=0; i<(int)XtNumber(IgnoredActions); i++)
if (!strcmp(action, IgnoredActions[i]))
return True;
return False;
}
/*
** Timer proc for putting up the "Macro Command in Progress" banner if
** the process is taking too long.
*/
#define MAX_TIMEOUT_MSG_LEN (MAX_ACCEL_LEN + 60)
static void bannerTimeoutProc(XtPointer clientData, XtIntervalId *id)
{
WindowInfo *window = (WindowInfo *)clientData;
macroCmdInfo *cmdData = window->macroCmdData;
XmString xmCancel;
char *cCancel = "\0";
char message[MAX_TIMEOUT_MSG_LEN];
cmdData->bannerIsUp = True;
/* Extract accelerator text from menu PushButtons */
XtVaGetValues(window->cancelMacroItem, XmNacceleratorText, &xmCancel, NULL);
if (!XmStringEmpty(xmCancel))
{
/* Translate Motif string to char* */
cCancel = GetXmStringText(xmCancel);
/* Free Motif String */
XmStringFree(xmCancel);
}
/* Create message */
if (cCancel[0] == '\0') {
strncpy(message, "Macro Command in Progress", MAX_TIMEOUT_MSG_LEN);
message[MAX_TIMEOUT_MSG_LEN - 1] = '\0';
}
else {
sprintf(message,
"Macro Command in Progress -- Press %s to Cancel",
cCancel);
}
/* Free C-string */
NEditFree(cCancel);
SetModeMessage(window, message);
cmdData->bannerTimeoutID = 0;
}
/*
** Work proc for continuing execution of a preempted macro.
**
** Xt WorkProcs are designed to run first-in first-out, which makes them
** very bad at sharing time between competing tasks. For this reason, it's
** usually bad to use work procs anywhere where their execution is likely to
** overlap. Using a work proc instead of a timer proc (which I usually
** prefer) here means macros will probably share time badly, but we're more
** interested in making the macros cancelable, and in continuing other work
** than having users run a bunch of them at once together.
*/
static Boolean continueWorkProc(XtPointer clientData)
{
WindowInfo *window = (WindowInfo *)clientData;
macroCmdInfo *cmdData = window->macroCmdData;
char *errMsg;
int stat;
DataValue result;
stat = ContinueMacro(cmdData->context, &result, &errMsg);
if (stat == MACRO_ERROR)
{
finishMacroCmdExecution(window);
DialogF(DF_ERR, window->shell, 1, "Macro Error",
"Error executing macro: %s", "OK", errMsg);
return True;
} else if (stat == MACRO_DONE)
{
finishMacroCmdExecution(window);
return True;
} else if (stat == MACRO_PREEMPT)
{
cmdData->continueWorkProcID = 0;
return True;
}
/* Macro exceeded time slice, re-schedule it */
if (stat != MACRO_TIME_LIMIT)
return True; /* shouldn't happen */
return False;
}
/*
** Copy fromString to toString replacing special characters in strings, such
** that they can be read back by the macro parser's string reader. i.e. double
** quotes are replaced by \", backslashes are replaced with \\, C-std control
** characters like \n are replaced with their backslash counterparts. This
** routine should be kept reasonably in sync with yylex in parse.y. Companion
** routine escapedStringLength predicts the length needed to write the string
** when it is expanded with the additional characters. Returns the number
** of characters to which the string expanded.
*/
static int escapeStringChars(char *fromString, char *toString)
{
char *e, *c, *outPtr = toString;
/* substitute escape sequences */
for (c=fromString; *c!='\0'; c++) {
for (e=EscapeChars; *e!='\0'; e++) {
if (*c == *e) {
*outPtr++ = '\\';
*outPtr++ = ReplaceChars[e-EscapeChars];
break;
}
}
if (*e == '\0')
*outPtr++ = *c;
}
*outPtr = '\0';
return outPtr - toString;
}
/*
** Predict the length of a string needed to hold a copy of "string" with
** special characters replaced with escape sequences by escapeStringChars.
*/
static int escapedStringLength(char *string)
{
char *c, *e;
int length = 0;
/* calculate length and allocate returned string */
for (c=string; *c!='\0'; c++) {
for (e=EscapeChars; *e!='\0'; e++) {
if (*c == *e) {
length++;
break;
}
}
length++;
}
return length;
}
/*
** Built-in macro subroutine for getting the length of a string
*/
static int lengthMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char *string, stringStorage[TYPE_INT_STR_SIZE(int)];
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage, errMsg))
return False;
result->tag = INT_TAG;
result->val.n = strlen(string);
return True;
}
/*
** Built-in macro subroutines for min and max
*/
static int minMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int minVal, value, i;
if (nArgs == 1)
return tooFewArgsErr(errMsg);
if (!readIntArg(argList[0], &minVal, errMsg))
return False;
for (i=0; i<nArgs; i++) {
if (!readIntArg(argList[i], &value, errMsg))
return False;
minVal = value < minVal ? value : minVal;
}
result->tag = INT_TAG;
result->val.n = minVal;
return True;
}
static int maxMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int maxVal, value, i;
if (nArgs == 1)
return tooFewArgsErr(errMsg);
if (!readIntArg(argList[0], &maxVal, errMsg))
return False;
for (i=0; i<nArgs; i++) {
if (!readIntArg(argList[i], &value, errMsg))
return False;
maxVal = value > maxVal ? value : maxVal;
}
result->tag = INT_TAG;
result->val.n = maxVal;
return True;
}
static int focusWindowMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[TYPE_INT_STR_SIZE(int)], *string;
WindowInfo *w;
char fullname[MAXPATHLEN];
char normalizedString[MAXPATHLEN];
/* Read the argument representing the window to focus to, and translate
it into a pointer to a real WindowInfo */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage, errMsg)) {
return False;
} else if (!strcmp(string, "last")) {
w = WindowList;
} else if (!strcmp(string, "next")) {
w = window->next;
} else if (strlen(string) >= MAXPATHLEN) {
*errMsg = "Pathname too long in focus_window()";
return False;
} else {
/* just use the plain name as supplied */
for (w=WindowList; w != NULL; w = w->next) {
sprintf(fullname, "%s%s", w->path, w->filename);
if (!strcmp(string, fullname)) {
break;
}
}
/* didn't work? try normalizing the string passed in */
if (w == NULL) {
strncpy(normalizedString, string, MAXPATHLEN);
normalizedString[MAXPATHLEN-1] = '\0';
if (1 == NormalizePathname(normalizedString)) {
/* Something is broken with the input pathname. */
*errMsg = "Pathname too long in focus_window()";
return False;
}
for (w=WindowList; w != NULL; w = w->next) {
sprintf(fullname, "%s%s", w->path, w->filename);
if (!strcmp(normalizedString, fullname))
break;
}
}
}
/* If no matching window was found, return empty string and do nothing */
if (w == NULL) {
result->tag = STRING_TAG;
result->val.str.rep = PERM_ALLOC_STR("");
result->val.str.len = 0;
return True;
}
/* Change the focused window to the requested one */
SetMacroFocusWindow(w);
/* turn on syntax highlight that might have been deferred */
if (w->highlightSyntax && w->highlightData==NULL)
StartHighlighting(w, False);
/* Return the name of the window */
result->tag = STRING_TAG;
AllocNString(&result->val.str, strlen(w->path)+strlen(w->filename)+1);
sprintf(result->val.str.rep, "%s%s", w->path, w->filename);
return True;
}
/*
** Built-in macro subroutine for getting text from the current window's text
** buffer
*/
static int getRangeMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int from, to;
textBuffer *buf = window->buffer;
char *rangeText;
/* Validate arguments and convert to int */
if (nArgs != 2)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &from, errMsg))
return False;
if (!readIntArg(argList[1], &to, errMsg))
return False;
if (from < 0) from = 0;
if (from > buf->length) from = buf->length;
if (to < 0) to = 0;
if (to > buf->length) to = buf->length;
if (from > to) {int temp = from; from = to; to = temp;}
/* Copy text from buffer (this extra copy could be avoided if textBuf.c
provided a routine for writing into a pre-allocated string) */
result->tag = STRING_TAG;
AllocNString(&result->val.str, to - from + 1);
rangeText = BufGetRange(buf, from, to);
BufUnsubstituteNullChars(rangeText, buf);
strcpy(result->val.str.rep, rangeText);
/* Note: after the un-substitution, it is possible that strlen() != len,
but that's because strlen() can't deal with 0-characters. */
NEditFree(rangeText);
return True;
}
/*
** Built-in macro subroutine for getting a single character at the position
** given, from the current window
*/
static int getCharacterMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int pos;
textBuffer *buf = window->buffer;
/* Validate argument and convert it to int */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &pos, errMsg))
return False;
if (pos < 0) pos = 0;
if (pos > buf->length) pos = buf->length;
/* Return the character in a pre-allocated string) */
result->tag = STRING_TAG;
AllocNString(&result->val.str, 2);
result->val.str.rep[0] = BufGetCharacter(buf, pos);
BufUnsubstituteNullChars(result->val.str.rep, buf);
/* Note: after the un-substitution, it is possible that strlen() != len,
but that's because strlen() can't deal with 0-characters. */
return True;
}
/*
** Built-in macro subroutine for replacing text in the current window's text
** buffer
*/
static int replaceRangeMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int from, to;
char stringStorage[TYPE_INT_STR_SIZE(int)], *string;
textBuffer *buf = window->buffer;
/* Validate arguments and convert to int */
if (nArgs != 3)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &from, errMsg))
return False;
if (!readIntArg(argList[1], &to, errMsg))
return False;
if (!readStringArg(argList[2], &string, stringStorage, errMsg))
return False;
if (from < 0) from = 0;
if (from > buf->length) from = buf->length;
if (to < 0) to = 0;
if (to > buf->length) to = buf->length;
if (from > to) {int temp = from; from = to; to = temp;}
/* Don't allow modifications if the window is read-only */
if (IS_ANY_LOCKED(window->lockReasons)) {
XBell(XtDisplay(window->shell), 0);
result->tag = NO_TAG;
return True;
}
/* There are no null characters in the string (because macro strings
still have null termination), but if the string contains the
character used by the buffer for null substitution, it could
theoretically become a null. In the highly unlikely event that
all of the possible substitution characters in the buffer are used
up, stop the macro and tell the user of the failure */
if (!BufSubstituteNullChars(string, strlen(string), window->buffer)) {
*errMsg = "Too much binary data in file";
return False;
}
/* Do the replace */
BufReplace(buf, from, to, string);
result->tag = NO_TAG;
return True;
}
/*
** Built-in macro subroutine for replacing the primary-selection selected
** text in the current window's text buffer
*/
static int replaceSelectionMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[TYPE_INT_STR_SIZE(int)], *string;
/* Validate argument and convert to string */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage, errMsg))
return False;
/* Don't allow modifications if the window is read-only */
if (IS_ANY_LOCKED(window->lockReasons)) {
XBell(XtDisplay(window->shell), 0);
result->tag = NO_TAG;
return True;
}
/* There are no null characters in the string (because macro strings
still have null termination), but if the string contains the
character used by the buffer for null substitution, it could
theoretically become a null. In the highly unlikely event that
all of the possible substitution characters in the buffer are used
up, stop the macro and tell the user of the failure */
if (!BufSubstituteNullChars(string, strlen(string), window->buffer)) {
*errMsg = "Too much binary data in file";
return False;
}
/* Do the replace */
BufReplaceSelected(window->buffer, string);
result->tag = NO_TAG;
return True;
}
/*
** Built-in macro subroutine for getting the text currently selected by
** the primary selection in the current window's text buffer, or in any
** part of screen if "any" argument is given
*/
static int getSelectionMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char *selText;
/* Read argument list to check for "any" keyword, and get the appropriate
selection */
if (nArgs != 0 && nArgs != 1)
return wrongNArgsErr(errMsg);
if (nArgs == 1) {
if (argList[0].tag != STRING_TAG || strcmp(argList[0].val.str.rep, "any")) {
*errMsg = "Unrecognized argument to %s";
return False;
}
selText = GetAnySelection(window);
if (selText == NULL)
selText = NEditStrdup("");
} else {
selText = BufGetSelectionText(window->buffer);
BufUnsubstituteNullChars(selText, window->buffer);
}
/* Return the text as an allocated string */
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, selText);
NEditFree(selText);
return True;
}
/*
** Built-in macro subroutine for determining if implicit conversion of
** a string to number will succeed or fail
*/
static int validNumberMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char *string, stringStorage[TYPE_INT_STR_SIZE(int)];
if (nArgs != 1) {
return wrongNArgsErr(errMsg);
}
if (!readStringArg(argList[0], &string, stringStorage, errMsg)) {
return False;
}
result->tag = INT_TAG;
result->val.n = StringToNum(string, NULL);
return True;
}
/*
** Built-in macro subroutine for replacing a substring within another string
*/
static int replaceSubstringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int from, to, length, replaceLen, outLen;
char stringStorage[2][TYPE_INT_STR_SIZE(int)], *string, *replStr;
/* Validate arguments and convert to int */
if (nArgs != 4)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage[1], errMsg))
return False;
if (!readIntArg(argList[1], &from, errMsg))
return False;
if (!readIntArg(argList[2], &to, errMsg))
return False;
if (!readStringArg(argList[3], &replStr, stringStorage[1], errMsg))
return False;
length = strlen(string);
if (from < 0) from = 0;
if (from > length) from = length;
if (to < 0) to = 0;
if (to > length) to = length;
if (from > to) {int temp = from; from = to; to = temp;}
/* Allocate a new string and do the replacement */
replaceLen = strlen(replStr);
outLen = length - (to - from) + replaceLen;
result->tag = STRING_TAG;
AllocNString(&result->val.str, outLen+1);
strncpy(result->val.str.rep, string, from);
strncpy(&result->val.str.rep[from], replStr, replaceLen);
strncpy(&result->val.str.rep[from + replaceLen], &string[to], length - to);
return True;
}
/*
** Built-in macro subroutine for getting a substring of a string.
** Called as substring(string, from [, to])
*/
static int substringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int from, to, length;
char stringStorage[TYPE_INT_STR_SIZE(int)], *string;
/* Validate arguments and convert to int */
if (nArgs != 2 && nArgs != 3)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage, errMsg))
return False;
if (!readIntArg(argList[1], &from, errMsg))
return False;
length = to = strlen(string);
if (nArgs == 3)
if (!readIntArg(argList[2], &to, errMsg))
return False;
if (from < 0) from += length;
if (from < 0) from = 0;
if (from > length) from = length;
if (to < 0) to += length;
if (to < 0) to = 0;
if (to > length) to = length;
if (from > to) to = from;
/* Allocate a new string and copy the sub-string into it */
result->tag = STRING_TAG;
AllocNStringNCpy(&result->val.str, &string[from], to - from);
return True;
}
static int toupperMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int i, length;
char stringStorage[TYPE_INT_STR_SIZE(int)], *string;
/* Validate arguments and convert to int */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage, errMsg))
return False;
length = strlen(string);
/* Allocate a new string and copy an uppercased version of the string it */
result->tag = STRING_TAG;
AllocNString(&result->val.str, length + 1);
for (i=0; i<length; i++)
result->val.str.rep[i] = toupper((unsigned char)string[i]);
return True;
}
static int tolowerMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int i, length;
char stringStorage[TYPE_INT_STR_SIZE(int)], *string;
/* Validate arguments and convert to int */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage, errMsg))
return False;
length = strlen(string);
/* Allocate a new string and copy an lowercased version of the string it */
result->tag = STRING_TAG;
AllocNString(&result->val.str, length + 1);
for (i=0; i<length; i++)
result->val.str.rep[i] = tolower((unsigned char)string[i]);
return True;
}
static int stringToClipboardMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
long itemID = 0;
XmString s;
int stat;
char stringStorage[TYPE_INT_STR_SIZE(int)], *string;
/* Get the string argument */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage, errMsg))
return False;
/* Use the XmClipboard routines to copy the text to the clipboard.
If errors occur, just give up. */
result->tag = NO_TAG;
stat = SpinClipboardStartCopy(TheDisplay, XtWindow(window->textArea),
s=XmStringCreateSimple("NEdit"), XtLastTimestampProcessed(TheDisplay),
window->textArea, NULL, &itemID);
XmStringFree(s);
if (stat != ClipboardSuccess)
return True;
if (SpinClipboardCopy(TheDisplay, XtWindow(window->textArea), itemID, "STRING",
string, strlen(string), 0, NULL) != ClipboardSuccess) {
SpinClipboardEndCopy(TheDisplay, XtWindow(window->textArea), itemID);
return True;
}
SpinClipboardEndCopy(TheDisplay, XtWindow(window->textArea), itemID);
return True;
}
static int clipboardToStringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
unsigned long length, retLength;
long id = 0;
/* Should have no arguments */
if (nArgs != 0)
return wrongNArgsErr(errMsg);
/* Ask if there's a string in the clipboard, and get its length */
if (SpinClipboardInquireLength(TheDisplay, XtWindow(window->shell), "STRING",
&length) != ClipboardSuccess) {
result->tag = STRING_TAG;
result->val.str.rep = PERM_ALLOC_STR("");
result->val.str.len = 0;
/*
* Possibly, the clipboard can remain in a locked state after
* a failure, so we try to remove the lock, just to be sure.
*/
SpinClipboardUnlock(TheDisplay, XtWindow(window->shell));
return True;
}
/* Allocate a new string to hold the data */
result->tag = STRING_TAG;
AllocNString(&result->val.str, (int)length + 1);
/* Copy the clipboard contents to the string */
if (SpinClipboardRetrieve(TheDisplay, XtWindow(window->shell), "STRING",
result->val.str.rep, length, &retLength, &id) != ClipboardSuccess) {
retLength = 0;
/*
* Possibly, the clipboard can remain in a locked state after
* a failure, so we try to remove the lock, just to be sure.
*/
SpinClipboardUnlock(TheDisplay, XtWindow(window->shell));
}
result->val.str.rep[retLength] = '\0';
result->val.str.len = retLength;
return True;
}
/*
** Built-in macro subroutine for reading the contents of a text file into
** a string. On success, returns 1 in $readStatus, and the contents of the
** file as a string in the subroutine return value. On failure, returns
** the empty string "" and an 0 $readStatus.
*/
static int readFileMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[TYPE_INT_STR_SIZE(int)], *name;
struct stat statbuf;
FILE *fp;
int readLen;
/* Validate arguments and convert to int */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &name, stringStorage, errMsg))
return False;
/* Read the whole file into an allocated string */
if ((fp = fopen(name, "r")) == NULL)
goto errorNoClose;
if (fstat(fileno(fp), &statbuf) != 0)
goto error;
result->tag = STRING_TAG;
AllocNString(&result->val.str, statbuf.st_size+1);
readLen = fread(result->val.str.rep, sizeof(char), statbuf.st_size+1, fp);
if (ferror(fp))
goto error;
if(!feof(fp)){
/* Couldn't trust file size. Use slower but more general method */
int chunkSize = 1024;
char *buffer;
buffer = (char*)NEditMalloc(readLen * sizeof(char));
memcpy(buffer, result->val.str.rep, readLen * sizeof(char));
while (!feof(fp)){
buffer = NEditRealloc(buffer, (readLen+chunkSize)*sizeof(char));
readLen += fread(&buffer[readLen], sizeof(char), chunkSize, fp);
if (ferror(fp)){
NEditFree(buffer);
goto error;
}
}
AllocNString(&result->val.str, readLen + 1);
memcpy(result->val.str.rep, buffer, readLen * sizeof(char));
NEditFree(buffer);
}
fclose(fp);
/* Return the results */
ReturnGlobals[READ_STATUS]->value.tag = INT_TAG;
ReturnGlobals[READ_STATUS]->value.val.n = True;
return True;
error:
fclose(fp);
errorNoClose:
ReturnGlobals[READ_STATUS]->value.tag = INT_TAG;
ReturnGlobals[READ_STATUS]->value.val.n = False;
result->tag = STRING_TAG;
result->val.str.rep = PERM_ALLOC_STR("");
result->val.str.len = 0;
return True;
}
/*
** Built-in macro subroutines for writing or appending a string (parameter $1)
** to a file named in parameter $2. Returns 1 on successful write, or 0 if
** unsuccessful.
*/
static int writeFileMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
return writeOrAppendFile(False, window, argList, nArgs, result, errMsg);
}
static int appendFileMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
return writeOrAppendFile(True, window, argList, nArgs, result, errMsg);
}
static int writeOrAppendFile(int append, WindowInfo *window,
DataValue *argList, int nArgs, DataValue *result, char **errMsg)
{
char stringStorage[2][TYPE_INT_STR_SIZE(int)], *name, *string;
FILE *fp;
/* Validate argument */
if (nArgs != 2)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage[1], errMsg))
return False;
if (!readStringArg(argList[1], &name, stringStorage[0], errMsg))
return False;
/* open the file */
if ((fp = fopen(name, append ? "a" : "w")) == NULL) {
result->tag = INT_TAG;
result->val.n = False;
return True;
}
/* write the string to the file */
fwrite(string, sizeof(char), strlen(string), fp);
if (ferror(fp)) {
fclose(fp);
result->tag = INT_TAG;
result->val.n = False;
return True;
}
fclose(fp);
/* return the status */
result->tag = INT_TAG;
result->val.n = True;
return True;
}
/*
** Built-in macro subroutine for searching silently in a window without
** dialogs, beeps, or changes to the selection. Arguments are: $1: string to
** search for, $2: starting position. Optional arguments may include the
** strings: "wrap" to make the search wrap around the beginning or end of the
** string, "backward" or "forward" to change the search direction ("forward" is
** the default), "literal", "case" or "regex" to change the search type
** (default is "literal").
**
** Returns the starting position of the match, or -1 if nothing matched.
** also returns the ending position of the match in $searchEndPos
*/
static int searchMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
DataValue newArgList[9];
/* Use the search string routine, by adding the buffer contents as
the string argument */
if (nArgs > 8)
return wrongNArgsErr(errMsg);
/* we remove constness from BufAsString() result since we know
searchStringMS will not modify the result */
newArgList[0].tag = STRING_TAG;
newArgList[0].val.str.rep = (char *)BufAsString(window->buffer);
newArgList[0].val.str.len = window->buffer->length;
/* copy other arguments to the new argument list */
memcpy(&newArgList[1], argList, nArgs * sizeof(DataValue));
return searchStringMS(window, newArgList, nArgs+1, result, errMsg);
}
/*
** Built-in macro subroutine for searching a string. Arguments are $1:
** string to search in, $2: string to search for, $3: starting position.
** Optional arguments may include the strings: "wrap" to make the search
** wrap around the beginning or end of the string, "backward" or "forward"
** to change the search direction ("forward" is the default), "literal",
** "case" or "regex" to change the search type (default is "literal").
**
** Returns the starting position of the match, or -1 if nothing matched.
** also returns the ending position of the match in $searchEndPos
*/
static int searchStringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int beginPos, wrap, direction, found = False, foundStart, foundEnd, type;
int skipSearch = False, len;
char stringStorage[2][TYPE_INT_STR_SIZE(int)], *string, *searchStr;
/* Validate arguments and convert to proper types */
if (nArgs < 3)
return tooFewArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage[0], errMsg))
return False;
if (!readStringArg(argList[1], &searchStr, stringStorage[1], errMsg))
return False;
if (!readIntArg(argList[2], &beginPos, errMsg))
return False;
if (!readSearchArgs(&argList[3], nArgs-3, &direction, &type, &wrap, errMsg))
return False;
len = argList[0].val.str.len;
if (beginPos > len) {
if (direction == SEARCH_FORWARD) {
if (wrap) {
beginPos = 0; /* Wrap immediately */
} else {
found = False;
skipSearch = True;
}
} else {
beginPos = len;
}
} else if (beginPos < 0) {
if (direction == SEARCH_BACKWARD) {
if (wrap) {
beginPos = len; /* Wrap immediately */
} else {
found = False;
skipSearch = True;
}
} else {
beginPos = 0;
}
}
if (!skipSearch)
found = SearchString(string, searchStr, direction, type, wrap, beginPos,
&foundStart, &foundEnd, NULL, NULL, GetWindowDelimiters(window));
/* Return the results */
ReturnGlobals[SEARCH_END]->value.tag = INT_TAG;
ReturnGlobals[SEARCH_END]->value.val.n = found ? foundEnd : 0;
result->tag = INT_TAG;
result->val.n = found ? foundStart : -1;
return True;
}
/*
** Built-in macro subroutine for replacing all occurences of a search string in
** a string with a replacement string. Arguments are $1: string to search in,
** $2: string to search for, $3: replacement string. Also takes an optional
** search type: one of "literal", "case" or "regex" (default is "literal"), and
** an optional "copy" argument.
**
** Returns a new string with all of the replacements done. If no replacements
** were performed and "copy" was specified, returns a copy of the original
** string. Otherwise returns an empty string ("").
*/
static int replaceInStringMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[3][TYPE_INT_STR_SIZE(int)], *string, *searchStr, *replaceStr;
char *argStr, *replacedStr;
int searchType = SEARCH_LITERAL, copyStart, copyEnd;
int replacedLen, replaceEnd, force=False, i;
/* Validate arguments and convert to proper types */
if (nArgs < 3 || nArgs > 5)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &string, stringStorage[0], errMsg))
return False;
if (!readStringArg(argList[1], &searchStr, stringStorage[1], errMsg))
return False;
if (!readStringArg(argList[2], &replaceStr, stringStorage[2], errMsg))
return False;
for (i = 3; i < nArgs; i++) {
/* Read the optional search type and force arguments */
if (!readStringArg(argList[i], &argStr, stringStorage[2], errMsg))
return False;
if (!StringToSearchType(argStr, &searchType)) {
/* It's not a search type. is it "copy"? */
if (!strcmp(argStr, "copy")) {
force = True;
} else {
*errMsg = "unrecognized argument to %s";
return False;
}
}
}
/* Do the replace */
replacedStr = ReplaceAllInString(string, searchStr, replaceStr, searchType,
©Start, ©End, &replacedLen, GetWindowDelimiters(window));
/* Return the results */
result->tag = STRING_TAG;
if (replacedStr == NULL) {
if (force) {
/* Just copy the original DataValue */
if (argList[0].tag == STRING_TAG) {
result->val.str.rep = argList[0].val.str.rep;
result->val.str.len = argList[0].val.str.len;
}
else {
AllocNStringCpy(&result->val.str, string);
}
}
else {
result->val.str.rep = PERM_ALLOC_STR("");
result->val.str.len = 0;
}
}
else {
size_t remainder = strlen(&string[copyEnd]);
replaceEnd = copyStart + replacedLen;
AllocNString(&result->val.str, replaceEnd + remainder + 1);
strncpy(result->val.str.rep, string, copyStart);
strcpy(&result->val.str.rep[copyStart], replacedStr);
strcpy(&result->val.str.rep[replaceEnd], &string[copyEnd]);
NEditFree(replacedStr);
}
return True;
}
static int readSearchArgs(DataValue *argList, int nArgs, int *searchDirection,
int *searchType, int *wrap, char **errMsg)
{
int i;
char *argStr, stringStorage[TYPE_INT_STR_SIZE(int)];
*wrap = False;
*searchDirection = SEARCH_FORWARD;
*searchType = SEARCH_LITERAL;
for (i=0; i<nArgs; i++) {
if (!readStringArg(argList[i], &argStr, stringStorage, errMsg))
return False;
else if (!strcmp(argStr, "wrap"))
*wrap = True;
else if (!strcmp(argStr, "nowrap"))
*wrap = False;
else if (!strcmp(argStr, "backward"))
*searchDirection = SEARCH_BACKWARD;
else if (!strcmp(argStr, "forward"))
*searchDirection = SEARCH_FORWARD;
else if (!StringToSearchType(argStr, searchType)) {
*errMsg = "Unrecognized argument to %s";
return False;
}
}
return True;
}
static int setCursorPosMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int pos;
/* Get argument and convert to int */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &pos, errMsg))
return False;
/* Set the position */
TextSetCursorPos(window->lastFocus, pos);
result->tag = NO_TAG;
return True;
}
static int selectMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int start, end, startTmp;
/* Get arguments and convert to int */
if (nArgs != 2)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &start, errMsg))
return False;
if (!readIntArg(argList[1], &end, errMsg))
return False;
/* Verify integrity of arguments */
if (start > end) {
startTmp = start;
start = end;
end = startTmp;
}
if (start < 0) start = 0;
if (start > window->buffer->length) start = window->buffer->length;
if (end < 0) end = 0;
if (end > window->buffer->length) end = window->buffer->length;
/* Make the selection */
BufSelect(window->buffer, start, end);
result->tag = NO_TAG;
return True;
}
static int selectRectangleMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int start, end, left, right;
/* Get arguments and convert to int */
if (nArgs != 4)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &start, errMsg))
return False;
if (!readIntArg(argList[1], &end, errMsg))
return False;
if (!readIntArg(argList[2], &left, errMsg))
return False;
if (!readIntArg(argList[3], &right, errMsg))
return False;
/* Make the selection */
BufRectSelect(window->buffer, start, end, left, right);
result->tag = NO_TAG;
return True;
}
/*
** Macro subroutine to ring the bell
*/
static int beepMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
if (nArgs != 0)
return wrongNArgsErr(errMsg);
XBell(XtDisplay(window->shell), 0);
result->tag = NO_TAG;
return True;
}
static int tPrintMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[TYPE_INT_STR_SIZE(int)], *string;
int i;
if (nArgs == 0)
return tooFewArgsErr(errMsg);
for (i=0; i<nArgs; i++) {
if (!readStringArg(argList[i], &string, stringStorage, errMsg))
return False;
printf("%s%s", string, i==nArgs-1 ? "" : " ");
}
fflush( stdout );
result->tag = NO_TAG;
return True;
}
/*
** Built-in macro subroutine for getting the value of an environment variable
*/
static int getenvMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[1][TYPE_INT_STR_SIZE(int)];
char *name;
char *value;
/* Get name of variable to get */
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &name, stringStorage[0], errMsg)) {
*errMsg = "argument to %s must be a string";
return False;
}
value = getenv(name);
if (value == NULL)
value = "";
/* Return the text as an allocated string */
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, value);
return True;
}
static int shellCmdMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[2][TYPE_INT_STR_SIZE(int)], *cmdString, *inputString;
if (nArgs != 2)
return wrongNArgsErr(errMsg);
if (!readStringArg(argList[0], &cmdString, stringStorage[0], errMsg))
return False;
if (!readStringArg(argList[1], &inputString, stringStorage[1], errMsg))
return False;
/* Shell command execution requires that the macro be suspended, so
this subroutine can't be run if macro execution can't be interrupted */
if (MacroRunWindow()->macroCmdData == NULL) {
*errMsg = "%s can't be called from non-suspendable context";
return False;
}
#ifdef VMS
*errMsg = "Shell commands not supported under VMS";
return False;
#else
ShellCmdToMacroString(window, cmdString, inputString);
result->tag = INT_TAG;
result->val.n = 0;
return True;
#endif /*VMS*/
}
/*
** Method used by ShellCmdToMacroString (called by shellCmdMS), for returning
** macro string and exit status after the execution of a shell command is
** complete. (Sorry about the poor modularity here, it's just not worth
** teaching other modules about macro return globals, since other than this,
** they're not used outside of macro.c)
*/
void ReturnShellCommandOutput(WindowInfo *window, const char *outText, int status)
{
DataValue retVal;
macroCmdInfo *cmdData = window->macroCmdData;
if (cmdData == NULL)
return;
retVal.tag = STRING_TAG;
AllocNStringCpy(&retVal.val.str, outText);
ModifyReturnedValue(cmdData->context, retVal);
ReturnGlobals[SHELL_CMD_STATUS]->value.tag = INT_TAG;
ReturnGlobals[SHELL_CMD_STATUS]->value.val.n = status;
}
static int dialogMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
macroCmdInfo *cmdData;
char stringStorage[TYPE_INT_STR_SIZE(int)];
char btnStorage[TYPE_INT_STR_SIZE(int)];
char *btnLabel;
char *message;
Arg al[20];
int ac;
Widget dialog, btn;
int i, nBtns;
XmString s1, s2;
/* Ignore the focused window passed as the function argument and put
the dialog up over the window which is executing the macro */
window = MacroRunWindow();
cmdData = window->macroCmdData;
/* Dialogs require macro to be suspended and interleaved with other macros.
This subroutine can't be run if macro execution can't be interrupted */
if (!cmdData) {
*errMsg = "%s can't be called from non-suspendable context";
return False;
}
/* Read and check the arguments. The first being the dialog message,
and the rest being the button labels */
if (nArgs == 0) {
*errMsg = "%s subroutine called with no arguments";
return False;
}
if (!readStringArg(argList[0], &message, stringStorage, errMsg)) {
return False;
}
/* check that all button labels can be read */
for (i=1; i<nArgs; i++) {
if (!readStringArg(argList[i], &btnLabel, btnStorage, errMsg)) {
return False;
}
}
/* pick up the first button */
if (nArgs == 1) {
btnLabel = "OK";
nBtns = 1;
}
else {
nBtns = nArgs - 1;
argList++;
readStringArg(argList[0], &btnLabel, btnStorage, errMsg);
}
/* Create the message box dialog widget and its dialog shell parent */
ac = 0;
XtSetArg(al[ac], XmNtitle, " "); ac++;
XtSetArg(al[ac], XmNmessageString, s1=MKSTRING(message)); ac++;
XtSetArg(al[ac], XmNokLabelString, s2=XmStringCreateSimple(btnLabel)); ac++;
dialog = CreateMessageDialog(window->shell, "macroDialog", al, ac);
if (1 == nArgs)
{
/* Only set margin width for the default OK button */
XtVaSetValues(XmMessageBoxGetChild(dialog, XmDIALOG_OK_BUTTON),
XmNmarginWidth, BUTTON_WIDTH_MARGIN,
NULL);
}
XmStringFree(s1);
XmStringFree(s2);
AddMotifCloseCallback(XtParent(dialog), dialogCloseCB, window);
XtAddCallback(dialog, XmNokCallback, dialogBtnCB, window);
XtVaSetValues(XmMessageBoxGetChild(dialog, XmDIALOG_OK_BUTTON),
XmNuserData, (XtPointer)1, NULL);
cmdData->dialog = dialog;
/* Unmanage default buttons, except for "OK" */
XtUnmanageChild(XmMessageBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON));
XtUnmanageChild(XmMessageBoxGetChild(dialog, XmDIALOG_HELP_BUTTON));
/* Make callback for the unmanaged cancel button (which can
still get executed via the esc key) activate close box action */
XtAddCallback(XmMessageBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON),
XmNactivateCallback, dialogCloseCB, window);
/* Add user specified buttons (1st is already done) */
for (i=1; i<nBtns; i++) {
readStringArg(argList[i], &btnLabel, btnStorage, errMsg);
btn = XtVaCreateManagedWidget("mdBtn", xmPushButtonWidgetClass, dialog,
XmNlabelString, s1=XmStringCreateSimple(btnLabel),
XmNuserData, (XtPointer)(intptr_t)(i+1), NULL);
XtAddCallback(btn, XmNactivateCallback, dialogBtnCB, window);
XmStringFree(s1);
}
#ifdef LESSTIF_VERSION
/* Workaround for Lesstif (e.g. v2.1 r0.93.18) that doesn't handle
the escape key for closing the dialog (probably because the
cancel button is not managed). */
XtAddEventHandler(dialog, KeyPressMask, False, dialogEscCB,
(XtPointer)window);
XtGrabKey(dialog, XKeysymToKeycode(XtDisplay(dialog), XK_Escape), 0,
True, GrabModeAsync, GrabModeAsync);
#endif /* LESSTIF_VERSION */
/* Put up the dialog */
ManageDialogCenteredOnPointer(dialog);
/* Stop macro execution until the dialog is complete */
PreemptMacro();
/* Return placeholder result. Value will be changed by button callback */
result->tag = INT_TAG;
result->val.n = 0;
return True;
}
static void dialogBtnCB(Widget w, XtPointer clientData, XtPointer callData)
{
WindowInfo *window = (WindowInfo *)clientData;
macroCmdInfo *cmdData = window->macroCmdData;
XtPointer userData;
DataValue retVal;
/* Return the index of the button which was pressed (stored in the userData
field of the button widget). The 1st button, being a gadget, is not
returned in w. */
if (cmdData == NULL)
return; /* shouldn't happen */
if (XtClass(w) == xmPushButtonWidgetClass) {
XtVaGetValues(w, XmNuserData, &userData, NULL);
retVal.val.n = (int)(intptr_t)userData;
} else
retVal.val.n = 1;
retVal.tag = INT_TAG;
ModifyReturnedValue(cmdData->context, retVal);
/* Pop down the dialog */
XtDestroyWidget(XtParent(cmdData->dialog));
cmdData->dialog = NULL;
/* Continue preempted macro execution */
ResumeMacroExecution(window);
}
static void dialogCloseCB(Widget w, XtPointer clientData, XtPointer callData)
{
WindowInfo *window = (WindowInfo *)clientData;
macroCmdInfo *cmdData = window->macroCmdData;
DataValue retVal;
/* Return 0 to show that the dialog was closed via the window close box */
retVal.val.n = 0;
retVal.tag = INT_TAG;
ModifyReturnedValue(cmdData->context, retVal);
/* Pop down the dialog */
XtDestroyWidget(XtParent(cmdData->dialog));
cmdData->dialog = NULL;
/* Continue preempted macro execution */
ResumeMacroExecution(window);
}
#ifdef LESSTIF_VERSION
static void dialogEscCB(Widget w, XtPointer clientData, XEvent *event,
Boolean *cont)
{
if (event->xkey.keycode != XKeysymToKeycode(XtDisplay(w), XK_Escape))
return;
if (clientData != NULL) {
dialogCloseCB(w, (WindowInfo *)clientData, NULL);
}
*cont = False;
}
#endif /* LESSTIF_VERSION */
static int stringDialogMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
macroCmdInfo *cmdData;
char stringStorage[TYPE_INT_STR_SIZE(int)];
char btnStorage[TYPE_INT_STR_SIZE(int)];
char *btnLabel;
char *message;
Widget dialog, btn;
int i, nBtns;
XmString s1, s2;
Arg al[20];
int ac;
/* Ignore the focused window passed as the function argument and put
the dialog up over the window which is executing the macro */
window = MacroRunWindow();
cmdData = window->macroCmdData;
/* Dialogs require macro to be suspended and interleaved with other macros.
This subroutine can't be run if macro execution can't be interrupted */
if (!cmdData) {
*errMsg = "%s can't be called from non-suspendable context";
return False;
}
/* Read and check the arguments. The first being the dialog message,
and the rest being the button labels */
if (nArgs == 0) {
*errMsg = "%s subroutine called with no arguments";
return False;
}
if (!readStringArg(argList[0], &message, stringStorage, errMsg)) {
return False;
}
/* check that all button labels can be read */
for (i=1; i<nArgs; i++) {
if (!readStringArg(argList[i], &btnLabel, stringStorage, errMsg)) {
return False;
}
}
if (nArgs == 1) {
btnLabel = "OK";
nBtns = 1;
}
else {
nBtns = nArgs - 1;
argList++;
readStringArg(argList[0], &btnLabel, btnStorage, errMsg);
}
/* Create the selection box dialog widget and its dialog shell parent */
ac = 0;
XtSetArg(al[ac], XmNtitle, " "); ac++;
XtSetArg(al[ac], XmNselectionLabelString, s1=MKSTRING(message)); ac++;
XtSetArg(al[ac], XmNokLabelString, s2=XmStringCreateSimple(btnLabel)); ac++;
dialog = CreatePromptDialog(window->shell, "macroStringDialog", al, ac);
if (1 == nArgs)
{
/* Only set margin width for the default OK button */
XtVaSetValues(XmSelectionBoxGetChild(dialog, XmDIALOG_OK_BUTTON),
XmNmarginWidth, BUTTON_WIDTH_MARGIN,
NULL);
}
XmStringFree(s1);
XmStringFree(s2);
AddMotifCloseCallback(XtParent(dialog), stringDialogCloseCB, window);
XtAddCallback(dialog, XmNokCallback, stringDialogBtnCB, window);
XtVaSetValues(XmSelectionBoxGetChild(dialog, XmDIALOG_OK_BUTTON),
XmNuserData, (XtPointer)1, NULL);
cmdData->dialog = dialog;
/* Unmanage unneded widgets */
XtUnmanageChild(XmSelectionBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON));
XtUnmanageChild(XmSelectionBoxGetChild(dialog, XmDIALOG_HELP_BUTTON));
/* Make callback for the unmanaged cancel button (which can
still get executed via the esc key) activate close box action */
XtAddCallback(XmSelectionBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON),
XmNactivateCallback, stringDialogCloseCB, window);
/* Add user specified buttons (1st is already done). Selection box
requires a place-holder widget to be added before buttons can be
added, that's what the separator below is for */
XtVaCreateWidget("x", xmSeparatorWidgetClass, dialog, NULL);
for (i=1; i<nBtns; i++) {
readStringArg(argList[i], &btnLabel, btnStorage, errMsg);
btn = XtVaCreateManagedWidget("mdBtn", xmPushButtonWidgetClass, dialog,
XmNlabelString, s1=XmStringCreateSimple(btnLabel),
XmNuserData, (XtPointer)(intptr_t)(i+1), NULL);
XtAddCallback(btn, XmNactivateCallback, stringDialogBtnCB, window);
XmStringFree(s1);
}
#ifdef LESSTIF_VERSION
/* Workaround for Lesstif (e.g. v2.1 r0.93.18) that doesn't handle
the escape key for closing the dialog (probably because the
cancel button is not managed). */
XtAddEventHandler(dialog, KeyPressMask, False, stringDialogEscCB,
(XtPointer)window);
XtGrabKey(dialog, XKeysymToKeycode(XtDisplay(dialog), XK_Escape), 0,
True, GrabModeAsync, GrabModeAsync);
#endif /* LESSTIF_VERSION */
/* Put up the dialog */
ManageDialogCenteredOnPointer(dialog);
/* Stop macro execution until the dialog is complete */
PreemptMacro();
/* Return placeholder result. Value will be changed by button callback */
result->tag = INT_TAG;
result->val.n = 0;
return True;
}
static void stringDialogBtnCB(Widget w, XtPointer clientData,
XtPointer callData)
{
WindowInfo *window = (WindowInfo *)clientData;
macroCmdInfo *cmdData = window->macroCmdData;
XtPointer userData;
DataValue retVal;
char *text;
int btnNum;
/* shouldn't happen, but would crash if it did */
if (cmdData == NULL)
return;
/* Return the string entered in the selection text area */
text = XmTextGetString(XmSelectionBoxGetChild(cmdData->dialog,
XmDIALOG_TEXT));
retVal.tag = STRING_TAG;
AllocNStringCpy(&retVal.val.str, text);
NEditFree(text);
ModifyReturnedValue(cmdData->context, retVal);
/* Find the index of the button which was pressed (stored in the userData
field of the button widget). The 1st button, being a gadget, is not
returned in w. */
if (XtClass(w) == xmPushButtonWidgetClass) {
XtVaGetValues(w, XmNuserData, &userData, NULL);
btnNum = (int)(intptr_t)userData;
} else
btnNum = 1;
/* Return the button number in the global variable $string_dialog_button */
ReturnGlobals[STRING_DIALOG_BUTTON]->value.tag = INT_TAG;
ReturnGlobals[STRING_DIALOG_BUTTON]->value.val.n = btnNum;
/* Pop down the dialog */
XtDestroyWidget(XtParent(cmdData->dialog));
cmdData->dialog = NULL;
/* Continue preempted macro execution */
ResumeMacroExecution(window);
}
static void stringDialogCloseCB(Widget w, XtPointer clientData,
XtPointer callData)
{
WindowInfo *window = (WindowInfo *)clientData;
macroCmdInfo *cmdData = window->macroCmdData;
DataValue retVal;
/* shouldn't happen, but would crash if it did */
if (cmdData == NULL)
return;
/* Return an empty string */
retVal.tag = STRING_TAG;
retVal.val.str.rep = PERM_ALLOC_STR("");
retVal.val.str.len = 0;
ModifyReturnedValue(cmdData->context, retVal);
/* Return button number 0 in the global variable $string_dialog_button */
ReturnGlobals[STRING_DIALOG_BUTTON]->value.tag = INT_TAG;
ReturnGlobals[STRING_DIALOG_BUTTON]->value.val.n = 0;
/* Pop down the dialog */
XtDestroyWidget(XtParent(cmdData->dialog));
cmdData->dialog = NULL;
/* Continue preempted macro execution */
ResumeMacroExecution(window);
}
#ifdef LESSTIF_VERSION
static void stringDialogEscCB(Widget w, XtPointer clientData, XEvent *event,
Boolean *cont)
{
if (event->xkey.keycode != XKeysymToKeycode(XtDisplay(w), XK_Escape))
return;
if (clientData != NULL) {
stringDialogCloseCB(w, (WindowInfo *)clientData, NULL);
}
*cont = False;
}
#endif /* LESSTIF_VERSION */
/*
** A subroutine to put up a calltip
** First arg is either text to be displayed or a key for tip/tag lookup.
** Optional second arg is the buffer position beneath which to display the
** upper-left corner of the tip. Default (or -1) puts it under the cursor.
** Additional optional arguments:
** "tipText": (default) Indicates first arg is text to be displayed in tip.
** "tipKey": Indicates first arg is key in calltips database. If key
** is not found in tip database then the tags database is also
** searched.
** "tagKey": Indicates first arg is key in tags database. (Skips
** search in calltips database.)
** "center": Horizontally center the calltip at the position
** "right": Put the right edge of the calltip at the position
** "center" and "right" cannot both be specified.
** "above": Place the calltip above the position
** "strict": Don't move the calltip to keep it on-screen and away
** from the cursor's line.
**
** Returns the new calltip's ID on success, 0 on failure.
**
** Does this need to go on IgnoredActions? I don't think so, since
** showing a calltip may be part of the action you want to learn.
*/
static int calltipMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[TYPE_INT_STR_SIZE(int)], *tipText, *txtArg;
Boolean anchored = False, lookup = True;
int mode = -1, i;
int anchorPos, hAlign = TIP_LEFT, vAlign = TIP_BELOW,
alignMode = TIP_SLOPPY;
/* Read and check the string */
if (nArgs < 1) {
*errMsg = "%s subroutine called with too few arguments";
return False;
}
if (nArgs > 6) {
*errMsg = "%s subroutine called with too many arguments";
return False;
}
/* Read the tip text or key */
if (!readStringArg(argList[0], &tipText, stringStorage, errMsg))
return False;
/* Read the anchor position (-1 for unanchored) */
if (nArgs > 1) {
if (!readIntArg(argList[1], &anchorPos, errMsg))
return False;
} else {
anchorPos = -1;
}
if (anchorPos >= 0) anchored = True;
/* Any further args are directives for relative positioning */
for (i = 2; i < nArgs; ++i) {
if (!readStringArg(argList[i], &txtArg, stringStorage, errMsg)){
return False;
}
switch( txtArg[0] ) {
case 'c':
if (strcmp(txtArg, "center"))
goto bad_arg;
hAlign = TIP_CENTER;
break;
case 'r':
if (strcmp(txtArg, "right"))
goto bad_arg;
hAlign = TIP_RIGHT;
break;
case 'a':
if (strcmp(txtArg, "above"))
goto bad_arg;
vAlign = TIP_ABOVE;
break;
case 's':
if (strcmp(txtArg, "strict"))
goto bad_arg;
alignMode = TIP_STRICT;
break;
case 't':
if (!strcmp(txtArg, "tipText"))
mode = -1;
else if (!strcmp(txtArg, "tipKey"))
mode = TIP;
else if (!strcmp(txtArg, "tagKey"))
mode = TIP_FROM_TAG;
else
goto bad_arg;
break;
default:
goto bad_arg;
}
}
result->tag = INT_TAG;
if (mode < 0) lookup = False;
/* Look up (maybe) a calltip and display it */
result->val.n = ShowTipString( window, tipText, anchored, anchorPos, lookup,
mode, hAlign, vAlign, alignMode );
return True;
bad_arg:
/* This is how the (more informative) global var. version would work,
assuming there was a global buffer called msg. */
/* sprintf(msg, "unrecognized argument to %%s: \"%s\"", txtArg);
*errMsg = msg; */
*errMsg = "unrecognized argument to %s";
return False;
}
/*
** A subroutine to kill the current calltip
*/
static int killCalltipMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int calltipID = 0;
if (nArgs > 1) {
*errMsg = "%s subroutine called with too many arguments";
return False;
}
if (nArgs > 0) {
if (!readIntArg(argList[0], &calltipID, errMsg))
return False;
}
KillCalltip( window, calltipID );
result->tag = NO_TAG;
return True;
}
/*
* A subroutine to get the ID of the current calltip, or 0 if there is none.
*/
static int calltipIDMV(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = GetCalltipID(window, 0);
return True;
}
/*
** filename_dialog([title[, mode[, defaultPath[, filter[, defaultName]]]]])
**
** Presents a FileSelectionDialog to the user prompting for a new file.
**
** Options are:
** title - will be the title of the dialog, defaults to "Choose file".
** mode - if set to "exist" (default), the "New File Name" TextField
** of the FSB will be unmanaged. If "new", the TextField will
** be managed.
** defaultPath - is the default path to use. Default (or "") will use the
** active document's directory.
** filter - the file glob which determines which files to display.
** Is set to "*" if filter is "" and by default.
** defaultName - is the default filename that is filled in automatically.
**
** Returns "" if the user cancelled the dialog, otherwise returns the path to
** the file that was selected
**
** Note that defaultName doesn't work on all *tifs. :-(
*/
static int filenameDialogMS(WindowInfo* window, DataValue* argList, int nArgs,
DataValue* result, char** errMsg)
{
char stringStorage[5][TYPE_INT_STR_SIZE(int)];
char filename[MAXPATHLEN + 1];
char* title = "Choose Filename";
char* mode = "exist";
char* defaultPath = "";
char* filter = "";
char* defaultName = "";
char* orgDefaultPath;
char* orgFilter;
int gfnResult;
/* Ignore the focused window passed as the function argument and put
the dialog up over the window which is executing the macro */
window = MacroRunWindow();
/* Dialogs require macro to be suspended and interleaved with other macros.
This subroutine can't be run if macro execution can't be interrupted */
if (NULL == window->macroCmdData) {
M_FAILURE("%s can't be called from non-suspendable context");
}
/* Get the argument list. */
if (nArgs > 0 && !readStringArg(argList[0], &title, stringStorage[0],
errMsg)) {
return False;
}
if (nArgs > 1 && !readStringArg(argList[1], &mode, stringStorage[1],
errMsg)) {
return False;
}
if (0 != strcmp(mode, "exist") && 0 != strcmp(mode, "new")) {
M_FAILURE("Invalid value for mode in %s");
}
if (nArgs > 2 && !readStringArg(argList[2], &defaultPath, stringStorage[2],
errMsg)) {
return False;
}
if (nArgs > 3 && !readStringArg(argList[3], &filter, stringStorage[3],
errMsg)) {
return False;
}
if (nArgs > 4 && !readStringArg(argList[4], &defaultName, stringStorage[4],
errMsg)) {
return False;
}
if (nArgs > 5) {
M_FAILURE("%s called with too many arguments. Expects at most 5 arguments.");
}
/* Set default directory (saving original for later) */
orgDefaultPath = GetFileDialogDefaultDirectory();
if ('\0' != defaultPath[0]) {
SetFileDialogDefaultDirectory(defaultPath);
} else {
SetFileDialogDefaultDirectory(window->path);
}
/* Set filter (saving original for later) */
orgFilter = GetFileDialogDefaultPattern();
if ('\0' != filter[0]) {
SetFileDialogDefaultPattern(filter);
}
/* Fork to one of the worker methods from util/getfiles.c.
(This should obviously be refactored.) */
if (0 == strcmp(mode, "exist")) {
gfnResult = GetExistingFilename(window->shell, title, filename);
} else {
gfnResult = GetNewFilename(window->shell, title, filename, defaultName);
} /* Invalid values are weeded out above. */
/* Reset original values and free temps */
SetFileDialogDefaultDirectory(orgDefaultPath);
SetFileDialogDefaultPattern(orgFilter);
NEditFree(orgDefaultPath);
NEditFree(orgFilter);
result->tag = STRING_TAG;
if (GFN_OK == gfnResult) {
/* Got a string, copy it to the result */
if (!AllocNStringNCpy(&result->val.str, filename, MAXPATHLEN)) {
M_FAILURE("failed to allocate return value: %s");
}
} else {
/* User cancelled. Return "" */
result->val.str.rep = PERM_ALLOC_STR("");
result->val.str.len = 0;
}
return True;
}
/* T Balinski */
static int listDialogMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
macroCmdInfo *cmdData;
char stringStorage[TYPE_INT_STR_SIZE(int)];
char textStorage[TYPE_INT_STR_SIZE(int)];
char btnStorage[TYPE_INT_STR_SIZE(int)];
char *btnLabel;
char *message, *text;
Widget dialog, btn;
int i, nBtns;
XmString s1, s2;
long nlines = 0;
char *p, *old_p, **text_lines, *tmp;
int tmp_len;
int n, is_last;
XmString *test_strings;
int tabDist;
Arg al[20];
int ac;
/* Ignore the focused window passed as the function argument and put
the dialog up over the window which is executing the macro */
window = MacroRunWindow();
cmdData = window->macroCmdData;
/* Dialogs require macro to be suspended and interleaved with other macros.
This subroutine can't be run if macro execution can't be interrupted */
if (!cmdData) {
*errMsg = "%s can't be called from non-suspendable context";
return False;
}
/* Read and check the arguments. The first being the dialog message,
and the rest being the button labels */
if (nArgs < 2) {
*errMsg = "%s subroutine called with no message, string or arguments";
return False;
}
if (!readStringArg(argList[0], &message, stringStorage, errMsg))
return False;
if (!readStringArg(argList[1], &text, textStorage, errMsg))
return False;
if (!text || text[0] == '\0') {
*errMsg = "%s subroutine called with empty list data";
return False;
}
/* check that all button labels can be read */
for (i=2; i<nArgs; i++)
if (!readStringArg(argList[i], &btnLabel, btnStorage, errMsg))
return False;
/* pick up the first button */
if (nArgs == 2) {
btnLabel = "OK";
nBtns = 1;
}
else {
nBtns = nArgs - 2;
argList += 2;
readStringArg(argList[0], &btnLabel, btnStorage, errMsg);
}
/* count the lines in the text - add one for unterminated last line */
nlines = 1;
for (p = text; *p; p++)
if (*p == '\n')
nlines++;
/* now set up arrays of pointers to lines */
/* test_strings to hold the display strings (tab expanded) */
/* text_lines to hold the original text lines (without the '\n's) */
test_strings = (XmString *) NEditMalloc(sizeof(XmString) * nlines);
text_lines = (char **)NEditMalloc(sizeof(char *) * (nlines + 1));
for (n = 0; n < nlines; n++) {
test_strings[n] = (XmString)0;
text_lines[n] = (char *)0;
}
text_lines[n] = (char *)0; /* make sure this is a null-terminated table */
/* pick up the tabDist value */
tabDist = window->buffer->tabDist;
/* load the table */
n = 0;
is_last = 0;
p = old_p = text;
tmp_len = 0; /* current allocated size of temporary buffer tmp */
tmp = (char*)NEditMalloc(1); /* temporary buffer into which to expand tabs */
do {
is_last = (*p == '\0');
if (*p == '\n' || is_last) {
*p = '\0';
if (strlen(old_p) > 0) { /* only include non-empty lines */
char *s, *t;
int l;
/* save the actual text line in text_lines[n] */
text_lines[n] = (char *)NEditMalloc(strlen(old_p) + 1);
strcpy(text_lines[n], old_p);
/* work out the tabs expanded length */
for (s = old_p, l = 0; *s; s++)
l += (*s == '\t') ? tabDist - (l % tabDist) : 1;
/* verify tmp is big enough then tab-expand old_p into tmp */
if (l > tmp_len)
tmp = (char*)NEditRealloc(tmp, (tmp_len = l) + 1);
for (s = old_p, t = tmp, l = 0; *s; s++) {
if (*s == '\t') {
for (i = tabDist - (l % tabDist); i--; l++)
*t++ = ' ';
}
else {
*t++ = *s;
l++;
}
}
*t = '\0';
/* that's it: tmp is the tab-expanded version of old_p */
test_strings[n] = MKSTRING(tmp);
n++;
}
old_p = p + 1;
if (!is_last)
*p = '\n'; /* put back our newline */
}
p++;
} while (!is_last);
NEditFree(tmp); /* don't need this anymore */
nlines = n;
if (nlines == 0) {
test_strings[0] = MKSTRING("");
nlines = 1;
}
/* Create the selection box dialog widget and its dialog shell parent */
ac = 0;
XtSetArg(al[ac], XmNtitle, " "); ac++;
XtSetArg(al[ac], XmNlistLabelString, s1=MKSTRING(message)); ac++;
XtSetArg(al[ac], XmNlistItems, test_strings); ac++;
XtSetArg(al[ac], XmNlistItemCount, nlines); ac++;
XtSetArg(al[ac], XmNlistVisibleItemCount, (nlines > 10) ? 10 : nlines); ac++;
XtSetArg(al[ac], XmNokLabelString, s2=XmStringCreateSimple(btnLabel)); ac++;
dialog = CreateSelectionDialog(window->shell, "macroListDialog", al, ac);
if (2 == nArgs)
{
/* Only set margin width for the default OK button */
XtVaSetValues(XmSelectionBoxGetChild(dialog, XmDIALOG_OK_BUTTON),
XmNmarginWidth, BUTTON_WIDTH_MARGIN,
NULL);
}
AddMotifCloseCallback(XtParent(dialog), listDialogCloseCB, window);
XtAddCallback(dialog, XmNokCallback, listDialogBtnCB, window);
XtVaSetValues(XmSelectionBoxGetChild(dialog, XmDIALOG_OK_BUTTON),
XmNuserData, (XtPointer)1, NULL);
XmStringFree(s1);
XmStringFree(s2);
cmdData->dialog = dialog;
/* forget lines stored in list */
while (n--)
XmStringFree(test_strings[n]);
NEditFree(test_strings);
/* modify the list */
XtVaSetValues(XmSelectionBoxGetChild(dialog, XmDIALOG_LIST),
XmNselectionPolicy, XmSINGLE_SELECT,
XmNuserData, (XtPointer)text_lines, NULL);
/* Unmanage unneeded widgets */
XtUnmanageChild(XmSelectionBoxGetChild(dialog, XmDIALOG_APPLY_BUTTON));
XtUnmanageChild(XmSelectionBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON));
XtUnmanageChild(XmSelectionBoxGetChild(dialog, XmDIALOG_HELP_BUTTON));
XtUnmanageChild(XmSelectionBoxGetChild(dialog, XmDIALOG_TEXT));
XtUnmanageChild(XmSelectionBoxGetChild(dialog, XmDIALOG_SELECTION_LABEL));
/* Make callback for the unmanaged cancel button (which can
still get executed via the esc key) activate close box action */
XtAddCallback(XmSelectionBoxGetChild(dialog, XmDIALOG_CANCEL_BUTTON),
XmNactivateCallback, listDialogCloseCB, window);
/* Add user specified buttons (1st is already done). Selection box
requires a place-holder widget to be added before buttons can be
added, that's what the separator below is for */
XtVaCreateWidget("x", xmSeparatorWidgetClass, dialog, NULL);
for (i=1; i<nBtns; i++) {
readStringArg(argList[i], &btnLabel, btnStorage, errMsg);
btn = XtVaCreateManagedWidget("mdBtn", xmPushButtonWidgetClass, dialog,
XmNlabelString, s1=XmStringCreateSimple(btnLabel),
XmNuserData, (XtPointer)(intptr_t)(i+1), NULL);
XtAddCallback(btn, XmNactivateCallback, listDialogBtnCB, window);
XmStringFree(s1);
}
#ifdef LESSTIF_VERSION
/* Workaround for Lesstif (e.g. v2.1 r0.93.18) that doesn't handle
the escape key for closing the dialog. */
XtAddEventHandler(dialog, KeyPressMask, False, listDialogEscCB,
(XtPointer)window);
XtGrabKey(dialog, XKeysymToKeycode(XtDisplay(dialog), XK_Escape), 0,
True, GrabModeAsync, GrabModeAsync);
#endif /* LESSTIF_VERSION */
/* Put up the dialog */
ManageDialogCenteredOnPointer(dialog);
/* Stop macro execution until the dialog is complete */
PreemptMacro();
/* Return placeholder result. Value will be changed by button callback */
result->tag = INT_TAG;
result->val.n = 0;
return True;
}
static void listDialogBtnCB(Widget w, XtPointer clientData,
XtPointer callData)
{
WindowInfo *window = (WindowInfo *)clientData;
macroCmdInfo *cmdData = window->macroCmdData;
XtPointer userData;
DataValue retVal;
char *text;
char **text_lines;
int btnNum;
int n_sel, *seltable, sel_index = 0;
Widget theList;
size_t length;
/* shouldn't happen, but would crash if it did */
if (cmdData == NULL)
return;
theList = XmSelectionBoxGetChild(cmdData->dialog, XmDIALOG_LIST);
/* Return the string selected in the selection list area */
XtVaGetValues(theList, XmNuserData, &text_lines, NULL);
if (!XmListGetSelectedPos(theList, &seltable, &n_sel)) {
n_sel = 0;
}
else {
sel_index = seltable[0] - 1;
NEditFree(seltable);
}
if (!n_sel) {
text = NEditStrdup("");
length = 0;
}
else {
length = strlen((char *)text_lines[sel_index]);
text = NEditStrdup(text_lines[sel_index]);
}
/* don't need text_lines anymore: free it */
for (sel_index = 0; text_lines[sel_index]; sel_index++)
NEditFree(text_lines[sel_index]);
NEditFree(text_lines);
retVal.tag = STRING_TAG;
retVal.val.str.rep = text;
retVal.val.str.len = length;
ModifyReturnedValue(cmdData->context, retVal);
/* Find the index of the button which was pressed (stored in the userData
field of the button widget). The 1st button, being a gadget, is not
returned in w. */
if (XtClass(w) == xmPushButtonWidgetClass) {
XtVaGetValues(w, XmNuserData, &userData, NULL);
btnNum = (int)(intptr_t)userData;
} else
btnNum = 1;
/* Return the button number in the global variable $list_dialog_button */
ReturnGlobals[LIST_DIALOG_BUTTON]->value.tag = INT_TAG;
ReturnGlobals[LIST_DIALOG_BUTTON]->value.val.n = btnNum;
/* Pop down the dialog */
XtDestroyWidget(XtParent(cmdData->dialog));
cmdData->dialog = NULL;
/* Continue preempted macro execution */
ResumeMacroExecution(window);
}
static void listDialogCloseCB(Widget w, XtPointer clientData,
XtPointer callData)
{
WindowInfo *window = (WindowInfo *)clientData;
macroCmdInfo *cmdData = window->macroCmdData;
DataValue retVal;
char **text_lines;
int sel_index;
Widget theList;
/* shouldn't happen, but would crash if it did */
if (cmdData == NULL)
return;
/* don't need text_lines anymore: retrieve it then free it */
theList = XmSelectionBoxGetChild(cmdData->dialog, XmDIALOG_LIST);
XtVaGetValues(theList, XmNuserData, &text_lines, NULL);
for (sel_index = 0; text_lines[sel_index]; sel_index++)
NEditFree(text_lines[sel_index]);
NEditFree(text_lines);
/* Return an empty string */
retVal.tag = STRING_TAG;
retVal.val.str.rep = NEditStrdup("");
retVal.val.str.len = 0;
ModifyReturnedValue(cmdData->context, retVal);
/* Return button number 0 in the global variable $list_dialog_button */
ReturnGlobals[LIST_DIALOG_BUTTON]->value.tag = INT_TAG;
ReturnGlobals[LIST_DIALOG_BUTTON]->value.val.n = 0;
/* Pop down the dialog */
XtDestroyWidget(XtParent(cmdData->dialog));
cmdData->dialog = NULL;
/* Continue preempted macro execution */
ResumeMacroExecution(window);
}
/* T Balinski End */
#ifdef LESSTIF_VERSION
static void listDialogEscCB(Widget w, XtPointer clientData, XEvent *event,
Boolean *cont)
{
if (event->xkey.keycode != XKeysymToKeycode(XtDisplay(w), XK_Escape))
return;
if (clientData != NULL) {
listDialogCloseCB(w, (WindowInfo *)clientData, NULL);
}
*cont = False;
}
#endif /* LESSTIF_VERSION */
static int stringCompareMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[3][TYPE_INT_STR_SIZE(int)];
char *leftStr, *rightStr, *argStr;
int considerCase = True;
int i;
int compareResult;
if (nArgs < 2) {
return(wrongNArgsErr(errMsg));
}
if (!readStringArg(argList[0], &leftStr, stringStorage[0], errMsg))
return False;
if (!readStringArg(argList[1], &rightStr, stringStorage[1], errMsg))
return False;
for (i = 2; i < nArgs; ++i) {
if (!readStringArg(argList[i], &argStr, stringStorage[2], errMsg))
return False;
else if (!strcmp(argStr, "case"))
considerCase = True;
else if (!strcmp(argStr, "nocase"))
considerCase = False;
else {
*errMsg = "Unrecognized argument to %s";
return False;
}
}
if (considerCase) {
compareResult = strcmp(leftStr, rightStr);
compareResult = (compareResult > 0) ? 1 : ((compareResult < 0) ? -1 : 0);
}
else {
compareResult = strCaseCmp(leftStr, rightStr);
}
result->tag = INT_TAG;
result->val.n = compareResult;
return True;
}
/*
** This function is intended to split strings into an array of substrings
** Importatnt note: It should always return at least one entry with key 0
** split("", ",") result[0] = ""
** split("1,2", ",") result[0] = "1" result[1] = "2"
** split("1,2,", ",") result[0] = "1" result[1] = "2" result[2] = ""
**
** This behavior is specifically important when used to break up
** array sub-scripts
*/
static int splitMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[3][TYPE_INT_STR_SIZE(int)];
char *sourceStr, *splitStr, *typeSplitStr;
int searchType, beginPos, foundStart, foundEnd, strLength, lastEnd;
int found, elementEnd, indexNum;
char indexStr[TYPE_INT_STR_SIZE(int)], *allocIndexStr;
DataValue element;
int elementLen;
if (nArgs < 2) {
return(wrongNArgsErr(errMsg));
}
if (!readStringArg(argList[0], &sourceStr, stringStorage[0], errMsg)) {
*errMsg = "first argument must be a string: %s";
return(False);
}
if (!readStringArg(argList[1], &splitStr, stringStorage[1], errMsg)) {
splitStr = NULL;
}
else {
if (splitStr[0] == 0) {
splitStr = NULL;
}
}
if (splitStr == NULL) {
*errMsg = "second argument must be a non-empty string: %s";
return(False);
}
if (nArgs > 2 && readStringArg(argList[2], &typeSplitStr, stringStorage[2], errMsg)) {
if (!StringToSearchType(typeSplitStr, &searchType)) {
*errMsg = "unrecognized argument to %s";
return(False);
}
}
else {
searchType = SEARCH_LITERAL;
}
result->tag = ARRAY_TAG;
result->val.arrayPtr = ArrayNew();
beginPos = 0;
lastEnd = 0;
indexNum = 0;
strLength = strlen(sourceStr);
found = 1;
while (found && beginPos < strLength) {
sprintf(indexStr, "%d", indexNum);
allocIndexStr = AllocString(strlen(indexStr) + 1);
if (!allocIndexStr) {
*errMsg = "array element failed to allocate key: %s";
return(False);
}
strcpy(allocIndexStr, indexStr);
found = SearchString(sourceStr, splitStr, SEARCH_FORWARD, searchType,
False, beginPos, &foundStart, &foundEnd,
NULL, NULL, GetWindowDelimiters(window));
elementEnd = found ? foundStart : strLength;
elementLen = elementEnd - lastEnd;
element.tag = STRING_TAG;
if (!AllocNStringNCpy(&element.val.str, &sourceStr[lastEnd], elementLen)) {
*errMsg = "failed to allocate element value: %s";
return(False);
}
if (!ArrayInsert(result, allocIndexStr, &element)) {
M_ARRAY_INSERT_FAILURE();
}
if (found) {
if (foundStart == foundEnd) {
beginPos = foundEnd + 1; /* Avoid endless loop for 0-width match */
} else {
beginPos = foundEnd;
}
} else {
beginPos = strLength; /* Break the loop */
}
lastEnd = foundEnd;
++indexNum;
}
if (found) {
sprintf(indexStr, "%d", indexNum);
allocIndexStr = AllocString(strlen(indexStr) + 1);
if (!allocIndexStr) {
*errMsg = "array element failed to allocate key: %s";
return(False);
}
strcpy(allocIndexStr, indexStr);
element.tag = STRING_TAG;
if (lastEnd == strLength) {
/* The pattern mathed the end of the string. Add an empty chunk. */
element.val.str.rep = PERM_ALLOC_STR("");
element.val.str.len = 0;
if (!ArrayInsert(result, allocIndexStr, &element)) {
M_ARRAY_INSERT_FAILURE();
}
} else {
/* We skipped the last character to prevent an endless loop.
Add it to the list. */
elementLen = strLength - lastEnd;
if (!AllocNStringNCpy(&element.val.str, &sourceStr[lastEnd], elementLen)) {
*errMsg = "failed to allocate element value: %s";
return(False);
}
if (!ArrayInsert(result, allocIndexStr, &element)) {
M_ARRAY_INSERT_FAILURE();
}
/* If the pattern can match zero-length strings, we may have to
add a final empty chunk.
For instance: split("abc\n", "$", "regex")
-> matches before \n and at end of string
-> expected output: "abc", "\n", ""
The '\n' gets added in the lines above, but we still have to
verify whether the pattern also matches the end of the string,
and add an empty chunk in case it does. */
found = SearchString(sourceStr, splitStr, SEARCH_FORWARD,
searchType, False, strLength, &foundStart, &foundEnd,
NULL, NULL, GetWindowDelimiters(window));
if (found) {
++indexNum;
sprintf(indexStr, "%d", indexNum);
allocIndexStr = AllocString(strlen(indexStr) + 1);
if (!allocIndexStr) {
*errMsg = "array element failed to allocate key: %s";
return(False);
}
strcpy(allocIndexStr, indexStr);
element.tag = STRING_TAG;
element.val.str.rep = PERM_ALLOC_STR("");
element.val.str.len = 0;
if (!ArrayInsert(result, allocIndexStr, &element)) {
M_ARRAY_INSERT_FAILURE();
}
}
}
}
return(True);
}
/*
** Set the backlighting string resource for the current window. If no parameter
** is passed or the value "default" is passed, it attempts to set the preference
** value of the resource. If the empty string is passed, the backlighting string
** will be cleared, turning off backlighting.
*/
/* DISABLED for 5.4
static int setBacklightStringMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg)
{
char *backlightString;
if (nArgs == 0) {
backlightString = GetPrefBacklightCharTypes();
}
else if (nArgs == 1) {
if (argList[0].tag != STRING_TAG) {
*errMsg = "%s not called with a string parameter";
return False;
}
backlightString = argList[0].val.str.rep;
}
else
return wrongNArgsErr(errMsg);
if (strcmp(backlightString, "default") == 0)
backlightString = GetPrefBacklightCharTypes();
if (backlightString && *backlightString == '\0') / * empty string param * /
backlightString = NULL; / * turns of backlighting * /
SetBacklightChars(window, backlightString);
return True;
} */
static int cursorMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = TextGetCursorPos(window->lastFocus);
return True;
}
static int lineMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int line, cursorPos, colNum;
result->tag = INT_TAG;
cursorPos = TextGetCursorPos(window->lastFocus);
if (!TextPosToLineAndCol(window->lastFocus, cursorPos, &line, &colNum))
line = BufCountLines(window->buffer, 0, cursorPos) + 1;
result->val.n = line;
return True;
}
static int columnMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
textBuffer *buf = window->buffer;
int cursorPos;
result->tag = INT_TAG;
cursorPos = TextGetCursorPos(window->lastFocus);
result->val.n = BufCountDispChars(buf, BufStartOfLine(buf, cursorPos),
cursorPos);
return True;
}
static int fileNameMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, window->filename);
return True;
}
static int filePathMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, window->path);
return True;
}
static int lengthMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->buffer->length;
return True;
}
static int selectionStartMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->buffer->primary.selected ?
window->buffer->primary.start : -1;
return True;
}
static int selectionEndMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->buffer->primary.selected ?
window->buffer->primary.end : -1;
return True;
}
static int selectionLeftMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
selection *sel = &window->buffer->primary;
result->tag = INT_TAG;
result->val.n = sel->selected && sel->rectangular ? sel->rectStart : -1;
return True;
}
static int selectionRightMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
selection *sel = &window->buffer->primary;
result->tag = INT_TAG;
result->val.n = sel->selected && sel->rectangular ? sel->rectEnd : -1;
return True;
}
static int wrapMarginMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int margin, nCols;
XtVaGetValues(window->textArea, textNcolumns, &nCols,
textNwrapMargin, &margin, NULL);
result->tag = INT_TAG;
result->val.n = margin == 0 ? nCols : margin;
return True;
}
static int statisticsLineMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->showStats ? 1 : 0;
return True;
}
static int incSearchLineMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->showISearchLine ? 1 : 0;
return True;
}
static int showLineNumbersMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->showLineNumbers ? 1 : 0;
return True;
}
static int autoIndentMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char *res = NULL;
switch (window->indentStyle) {
case NO_AUTO_INDENT:
res = PERM_ALLOC_STR("off");
break;
case AUTO_INDENT:
res = PERM_ALLOC_STR("on");
break;
case SMART_INDENT:
res = PERM_ALLOC_STR("smart");
break;
default:
*errMsg = "Invalid indent style value encountered in %s";
return False;
break;
}
result->tag = STRING_TAG;
result->val.str.rep = res;
result->val.str.len = strlen(res);
return True;
}
static int wrapTextMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char *res = NULL;
switch (window->wrapMode) {
case NO_WRAP:
res = PERM_ALLOC_STR("none");
break;
case NEWLINE_WRAP:
res = PERM_ALLOC_STR("auto");
break;
case CONTINUOUS_WRAP:
res = PERM_ALLOC_STR("continuous");
break;
default:
*errMsg = "Invalid wrap style value encountered in %s";
return False;
break;
}
result->tag = STRING_TAG;
result->val.str.rep = res;
result->val.str.len = strlen(res);
return True;
}
static int highlightSyntaxMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->highlightSyntax ? 1 : 0;
return True;
}
static int makeBackupCopyMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->saveOldVersion ? 1 : 0;
return True;
}
static int incBackupMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->autoSave ? 1 : 0;
return True;
}
static int showMatchingMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char *res = NULL;
switch (window->showMatchingStyle) {
case NO_FLASH:
res = PERM_ALLOC_STR(NO_FLASH_STRING);
break;
case FLASH_DELIMIT:
res = PERM_ALLOC_STR(FLASH_DELIMIT_STRING);
break;
case FLASH_RANGE:
res = PERM_ALLOC_STR(FLASH_RANGE_STRING);
break;
default:
*errMsg = "Invalid match flashing style value encountered in %s";
return False;
break;
}
result->tag = STRING_TAG;
result->val.str.rep = res;
result->val.str.len = strlen(res);
return True;
}
static int matchSyntaxBasedMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->matchSyntaxBased ? 1 : 0;
return True;
}
static int overTypeModeMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->overstrike ? 1 : 0;
return True;
}
static int readOnlyMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = (IS_ANY_LOCKED(window->lockReasons)) ? 1 : 0;
return True;
}
static int lockedMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = (IS_USER_LOCKED(window->lockReasons)) ? 1 : 0;
return True;
}
static int fileFormatMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char *res = NULL;
switch (window->fileFormat) {
case UNIX_FILE_FORMAT:
res = PERM_ALLOC_STR("unix");
break;
case DOS_FILE_FORMAT:
res = PERM_ALLOC_STR("dos");
break;
case MAC_FILE_FORMAT:
res = PERM_ALLOC_STR("macintosh");
break;
default:
*errMsg = "Invalid linefeed style value encountered in %s";
return False;
}
result->tag = STRING_TAG;
result->val.str.rep = res;
result->val.str.len = strlen(res);
return True;
}
static int fontNameMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, window->fontName);
return True;
}
static int fontNameItalicMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, window->italicFontName);
return True;
}
static int fontNameBoldMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, window->boldFontName);
return True;
}
static int fontNameBoldItalicMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, window->boldItalicFontName);
return True;
}
static int subscriptSepMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = STRING_TAG;
result->val.str.rep = PERM_ALLOC_STR(ARRAY_DIM_SEP);
result->val.str.len = strlen(result->val.str.rep);
return True;
}
static int minFontWidthMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = TextGetMinFontWidth(window->textArea, window->highlightSyntax);
return True;
}
static int maxFontWidthMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = TextGetMaxFontWidth(window->textArea, window->highlightSyntax);
return True;
}
static int topLineMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = TextFirstVisibleLine(window->lastFocus);
return True;
}
static int numDisplayLinesMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = TextNumVisibleLines(window->lastFocus);
return True;
}
static int displayWidthMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = TextVisibleWidth(window->lastFocus);
return True;
}
static int activePaneMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = WidgetToPaneIndex(window, window->lastFocus) + 1;
return True;
}
static int nPanesMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->nPanes + 1;
return True;
}
static int emptyArrayMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = ARRAY_TAG;
result->val.arrayPtr = NULL;
return True;
}
static int serverNameMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, GetPrefServerName());
return True;
}
static int tabDistMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->buffer->tabDist;
return True;
}
static int emTabDistMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int dist;
XtVaGetValues(window->textArea, textNemulateTabs, &dist, NULL);
result->tag = INT_TAG;
result->val.n = dist;
return True;
}
static int useTabsMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->buffer->useTabs;
return True;
}
static int modifiedMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
result->tag = INT_TAG;
result->val.n = window->fileChanged;
return True;
}
static int languageModeMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char *lmName = LanguageModeName(window->languageMode);
if (lmName == NULL)
lmName = "Plain";
result->tag = STRING_TAG;
AllocNStringCpy(&result->val.str, lmName);
return True;
}
/* DISABLED for 5.4
static int backlightStringMV(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg)
{
char *backlightString = window->backlightCharTypes;
result->tag = STRING_TAG;
if (!backlightString || !window->backlightChars)
backlightString = "";
AllocNStringCpy(&result->val.str, backlightString);
return True;
} */
/* -------------------------------------------------------------------------- */
/*
** Range set macro variables and functions
*/
static int rangesetListMV(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
RangesetTable *rangesetTable = window->buffer->rangesetTable;
unsigned char *rangesetList;
char *allocIndexStr;
char indexStr[TYPE_INT_STR_SIZE(int)] ;
int nRangesets, i;
DataValue element;
result->tag = ARRAY_TAG;
result->val.arrayPtr = ArrayNew();
if (rangesetTable == NULL) {
return True;
}
rangesetList = RangesetGetList(rangesetTable);
nRangesets = strlen((char*)rangesetList);
for(i = 0; i < nRangesets; i++) {
element.tag = INT_TAG;
element.val.n = rangesetList[i];
sprintf(indexStr, "%d", nRangesets - i - 1);
allocIndexStr = AllocString(strlen(indexStr) + 1);
if (allocIndexStr == NULL)
M_FAILURE("Failed to allocate array key in %s");
strcpy(allocIndexStr, indexStr);
if (!ArrayInsert(result, allocIndexStr, &element))
M_FAILURE("Failed to insert array element in %s");
}
return True;
}
/*
** Returns the version number of the current macro language implementation.
** For releases, this is the same number as NEdit's major.minor version
** number to keep things simple. For developer versions this could really
** be anything.
**
** Note that the current way to build $VERSION builds the same value for
** different point revisions. This is done because the macro interface
** does not change for the same version.
*/
static int versionMV(WindowInfo* window, DataValue* argList, int nArgs,
DataValue* result, char** errMsg)
{
static unsigned version = NEDIT_VERSION * 1000 + NEDIT_REVISION;
result->tag = INT_TAG;
result->val.n = version;
return True;
}
/*
** Built-in macro subroutine to create a new rangeset or rangesets.
** If called with one argument: $1 is the number of rangesets required and
** return value is an array indexed 0 to n, with the rangeset labels as values;
** (or an empty array if the requested number of rangesets are not available).
** If called with no arguments, returns a single rangeset label (not an array),
** or an empty string if there are no rangesets available.
*/
static int rangesetCreateMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int label;
int i, nRangesetsRequired;
DataValue element;
char indexStr[TYPE_INT_STR_SIZE(int)], *allocIndexStr;
RangesetTable *rangesetTable = window->buffer->rangesetTable;
if (nArgs > 1)
return wrongNArgsErr(errMsg);
if (rangesetTable == NULL) {
window->buffer->rangesetTable = rangesetTable =
RangesetTableAlloc(window->buffer);
}
if (nArgs == 0) {
label = RangesetCreate(rangesetTable);
result->tag = INT_TAG;
result->val.n = label;
return True;
}
else {
if (!readIntArg(argList[0], &nRangesetsRequired, errMsg))
return False;
result->tag = ARRAY_TAG;
result->val.arrayPtr = ArrayNew();
if (nRangesetsRequired > nRangesetsAvailable(rangesetTable))
return True;
for (i = 0; i < nRangesetsRequired; i++) {
element.tag = INT_TAG;
element.val.n = RangesetCreate(rangesetTable);
sprintf(indexStr, "%d", i);
allocIndexStr = AllocString(strlen(indexStr) + 1);
if (!allocIndexStr) {
*errMsg = "Array element failed to allocate key: %s";
return(False);
}
strcpy(allocIndexStr, indexStr);
ArrayInsert(result, allocIndexStr, &element);
}
return True;
}
}
/*
** Built-in macro subroutine for forgetting a range set.
*/
static int rangesetDestroyMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
RangesetTable *rangesetTable = window->buffer->rangesetTable;
DataValue *array;
DataValue element;
char keyString[TYPE_INT_STR_SIZE(int)];
int deleteLabels[N_RANGESETS];
int i, arraySize;
int label = 0;
if (nArgs != 1) {
return wrongNArgsErr(errMsg);
}
if (argList[0].tag == ARRAY_TAG) {
array = &argList[0];
arraySize = ArraySize(array);
if (arraySize > N_RANGESETS) {
M_FAILURE("Too many elements in array in %s");
}
for (i = 0; i < arraySize; i++) {
sprintf(keyString, "%d", i);
if (!ArrayGet(array, keyString, &element)) {
M_FAILURE("Invalid key in array in %s");
}
if (!readIntArg(element, &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("Invalid rangeset label in array in %s");
}
deleteLabels[i] = label;
}
for (i = 0; i < arraySize; i++) {
RangesetForget(rangesetTable, deleteLabels[i]);
}
} else {
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("Invalid rangeset label in %s");
}
if(rangesetTable != NULL) {
RangesetForget(rangesetTable, label);
}
}
/* set up result */
result->tag = NO_TAG;
return True;
}
/*
** Built-in macro subroutine for getting all range sets with a specfic name.
** Arguments are $1: range set name.
** return value is an array indexed 0 to n, with the rangeset labels as values;
*/
static int rangesetGetByNameMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[1][TYPE_INT_STR_SIZE(int)];
Rangeset *rangeset;
int label;
char *name, *rangeset_name;
RangesetTable *rangesetTable = window->buffer->rangesetTable;
unsigned char *rangesetList;
char *allocIndexStr;
char indexStr[TYPE_INT_STR_SIZE(int)] ;
int nRangesets, i, insertIndex = 0;
DataValue element;
if (nArgs != 1) {
return wrongNArgsErr(errMsg);
}
if (!readStringArg(argList[0], &name, stringStorage[0], errMsg)) {
M_FAILURE("First parameter is not a name string in %s");
}
result->tag = ARRAY_TAG;
result->val.arrayPtr = ArrayNew();
if (rangesetTable == NULL) {
return True;
}
rangesetList = RangesetGetList(rangesetTable);
nRangesets = strlen((char *)rangesetList);
for (i = 0; i < nRangesets; ++i) {
label = rangesetList[i];
rangeset = RangesetFetch(rangesetTable, label);
if (rangeset) {
rangeset_name = RangesetGetName(rangeset);
if (strcmp(name, rangeset_name ? rangeset_name : "") == 0) {
element.tag = INT_TAG;
element.val.n = label;
sprintf(indexStr, "%d", insertIndex);
allocIndexStr = AllocString(strlen(indexStr) + 1);
if (allocIndexStr == NULL)
M_FAILURE("Failed to allocate array key in %s");
strcpy(allocIndexStr, indexStr);
if (!ArrayInsert(result, allocIndexStr, &element))
M_FAILURE("Failed to insert array element in %s");
++insertIndex;
}
}
}
return True;
}
/*
** Built-in macro subroutine for adding to a range set. Arguments are $1: range
** set label (one integer), then either (a) $2: source range set label,
** (b) $2: int start-range, $3: int end-range, (c) nothing (use selection
** if any to specify range to add - must not be rectangular). Returns the
** index of the newly added range (cases b and c), or 0 (case a).
*/
static int rangesetAddMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
textBuffer *buffer = window->buffer;
RangesetTable *rangesetTable = buffer->rangesetTable;
Rangeset *targetRangeset, *sourceRangeset;
int start, end, isRect, rectStart, rectEnd, maxpos, index;
int label = 0;
if (nArgs < 1 || nArgs > 3)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
targetRangeset = RangesetFetch(rangesetTable, label);
if (targetRangeset == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
start = end = -1;
if (nArgs == 1) {
/* pick up current selection in this window */
if (!BufGetSelectionPos(buffer, &start, &end,
&isRect, &rectStart, &rectEnd) || isRect) {
M_FAILURE("Selection missing or rectangular in call to %s");
}
if (!RangesetAddBetween(targetRangeset, start, end)) {
M_FAILURE("Failure to add selection in %s");
}
}
if (nArgs == 2) {
/* add ranges taken from a second set */
if (!readIntArg(argList[1], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("Second parameter is an invalid rangeset label in %s");
}
sourceRangeset = RangesetFetch(rangesetTable, label);
if (sourceRangeset == NULL) {
M_FAILURE("Second rangeset does not exist in %s");
}
RangesetAdd(targetRangeset, sourceRangeset);
}
if (nArgs == 3) {
/* add a range bounded by the start and end positions in $2, $3 */
if (!readIntArg(argList[1], &start, errMsg)) {
return False;
}
if (!readIntArg(argList[2], &end, errMsg)) {
return False;
}
/* make sure range is in order and fits buffer size */
maxpos = buffer->length;
if (start < 0) start = 0;
if (start > maxpos) start = maxpos;
if (end < 0) end = 0;
if (end > maxpos) end = maxpos;
if (start > end) {int temp = start; start = end; end = temp;}
if ((start != end) && !RangesetAddBetween(targetRangeset, start, end)) {
M_FAILURE("Failed to add range in %s");
}
}
/* (to) which range did we just add? */
if (nArgs != 2 && start >= 0) {
start = (start + end) / 2; /* "middle" of added range */
index = 1 + RangesetFindRangeOfPos(targetRangeset, start, False);
}
else {
index = 0;
}
/* set up result */
result->tag = INT_TAG;
result->val.n = index;
return True;
}
/*
** Built-in macro subroutine for removing from a range set. Almost identical to
** rangesetAddMS() - only changes are from RangesetAdd()/RangesetAddBetween()
** to RangesetSubtract()/RangesetSubtractBetween(), the handling of an
** undefined destination range, and that it returns no value.
*/
static int rangesetSubtractMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
textBuffer *buffer = window->buffer;
RangesetTable *rangesetTable = buffer->rangesetTable;
Rangeset *targetRangeset, *sourceRangeset;
int start, end, isRect, rectStart, rectEnd, maxpos;
int label = 0;
if (nArgs < 1 || nArgs > 3) {
return wrongNArgsErr(errMsg);
}
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
targetRangeset = RangesetFetch(rangesetTable, label);
if (targetRangeset == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
if (nArgs == 1) {
/* remove current selection in this window */
if (!BufGetSelectionPos(buffer, &start, &end, &isRect, &rectStart, &rectEnd)
|| isRect) {
M_FAILURE("Selection missing or rectangular in call to %s");
}
RangesetRemoveBetween(targetRangeset, start, end);
}
if (nArgs == 2) {
/* remove ranges taken from a second set */
if (!readIntArg(argList[1], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("Second parameter is an invalid rangeset label in %s");
}
sourceRangeset = RangesetFetch(rangesetTable, label);
if (sourceRangeset == NULL) {
M_FAILURE("Second rangeset does not exist in %s");
}
RangesetRemove(targetRangeset, sourceRangeset);
}
if (nArgs == 3) {
/* remove a range bounded by the start and end positions in $2, $3 */
if (!readIntArg(argList[1], &start, errMsg))
return False;
if (!readIntArg(argList[2], &end, errMsg))
return False;
/* make sure range is in order and fits buffer size */
maxpos = buffer->length;
if (start < 0) start = 0;
if (start > maxpos) start = maxpos;
if (end < 0) end = 0;
if (end > maxpos) end = maxpos;
if (start > end) {int temp = start; start = end; end = temp;}
RangesetRemoveBetween(targetRangeset, start, end);
}
/* set up result */
result->tag = NO_TAG;
return True;
}
/*
** Built-in macro subroutine to invert a range set. Argument is $1: range set
** label (one alphabetic character). Returns nothing. Fails if range set
** undefined.
*/
static int rangesetInvertMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
RangesetTable *rangesetTable = window->buffer->rangesetTable;
Rangeset *rangeset;
int label = 0;
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
rangeset = RangesetFetch(rangesetTable, label);
if (rangeset == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
if (RangesetInverse(rangeset) < 0) {
M_FAILURE("Problem inverting rangeset in %s");
}
/* set up result */
result->tag = NO_TAG;
return True;
}
/*
** Built-in macro subroutine for finding out info about a rangeset. Takes one
** argument of a rangeset label. Returns an array with the following keys:
** defined, count, color, mode.
*/
static int rangesetInfoMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
RangesetTable *rangesetTable = window->buffer->rangesetTable;
Rangeset *rangeset = NULL;
int count, defined;
char *color, *name, *mode;
DataValue element;
int label = 0;
if (nArgs != 1)
return wrongNArgsErr(errMsg);
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable != NULL) {
rangeset = RangesetFetch(rangesetTable, label);
}
RangesetGetInfo(rangeset, &defined, &label, &count, &color, &name, &mode);
/* set up result */
result->tag = ARRAY_TAG;
result->val.arrayPtr = ArrayNew();
element.tag = INT_TAG;
element.val.n = defined;
if (!ArrayInsert(result, PERM_ALLOC_STR("defined"), &element))
M_FAILURE("Failed to insert array element \"defined\" in %s");
element.tag = INT_TAG;
element.val.n = count;
if (!ArrayInsert(result, PERM_ALLOC_STR("count"), &element))
M_FAILURE("Failed to insert array element \"count\" in %s");
element.tag = STRING_TAG;
if (!AllocNStringCpy(&element.val.str, color))
M_FAILURE("Failed to allocate array value \"color\" in %s");
if (!ArrayInsert(result, PERM_ALLOC_STR("color"), &element))
M_FAILURE("Failed to insert array element \"color\" in %s");
element.tag = STRING_TAG;
if (!AllocNStringCpy(&element.val.str, name))
M_FAILURE("Failed to allocate array value \"name\" in %s");
if (!ArrayInsert(result, PERM_ALLOC_STR("name"), &element)) {
M_FAILURE("Failed to insert array element \"name\" in %s");
}
element.tag = STRING_TAG;
if (!AllocNStringCpy(&element.val.str, mode))
M_FAILURE("Failed to allocate array value \"mode\" in %s");
if (!ArrayInsert(result, PERM_ALLOC_STR("mode"), &element))
M_FAILURE("Failed to insert array element \"mode\" in %s");
return True;
}
/*
** Built-in macro subroutine for finding the extent of a range in a set.
** If only one parameter is supplied, use the spanning range of all
** ranges, otherwise select the individual range specified. Returns
** an array with the keys "start" and "end" and values
*/
static int rangesetRangeMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
textBuffer *buffer = window->buffer;
RangesetTable *rangesetTable = buffer->rangesetTable;
Rangeset *rangeset;
int start, end, dummy, rangeIndex, ok;
DataValue element;
int label = 0;
if (nArgs < 1 || nArgs > 2) {
return wrongNArgsErr(errMsg);
}
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
ok = False;
rangeset = RangesetFetch(rangesetTable, label);
if (rangeset != NULL) {
if (nArgs == 1) {
rangeIndex = RangesetGetNRanges(rangeset) - 1;
ok = RangesetFindRangeNo(rangeset, 0, &start, &dummy);
ok &= RangesetFindRangeNo(rangeset, rangeIndex, &dummy, &end);
rangeIndex = -1;
}
else if (nArgs == 2) {
if (!readIntArg(argList[1], &rangeIndex, errMsg)) {
return False;
}
ok = RangesetFindRangeNo(rangeset, rangeIndex-1, &start, &end);
}
}
/* set up result */
result->tag = ARRAY_TAG;
result->val.arrayPtr = ArrayNew();
if (!ok)
return True;
element.tag = INT_TAG;
element.val.n = start;
if (!ArrayInsert(result, PERM_ALLOC_STR("start"), &element))
M_FAILURE("Failed to insert array element \"start\" in %s");
element.tag = INT_TAG;
element.val.n = end;
if (!ArrayInsert(result, PERM_ALLOC_STR("end"), &element))
M_FAILURE("Failed to insert array element \"end\" in %s");
return True;
}
/*
** Built-in macro subroutine for checking a position against a range. If only
** one parameter is supplied, the current cursor position is used. Returns
** false (zero) if not in a range, range index (1-based) if in a range;
** fails if parameters were bad.
*/
static int rangesetIncludesPosMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg)
{
textBuffer *buffer = window->buffer;
RangesetTable *rangesetTable = buffer->rangesetTable;
Rangeset *rangeset;
int pos, rangeIndex, maxpos;
int label = 0;
if (nArgs < 1 || nArgs > 2) {
return wrongNArgsErr(errMsg);
}
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
rangeset = RangesetFetch(rangesetTable, label);
if (rangeset == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
if (nArgs == 1) {
pos = TextGetCursorPos(window->lastFocus);
}
else if (nArgs == 2) {
if (!readIntArg(argList[1], &pos, errMsg))
return False;
}
maxpos = buffer->length;
if (pos < 0 || pos > maxpos) {
rangeIndex = 0;
}
else {
rangeIndex = RangesetFindRangeOfPos(rangeset, pos, False) + 1;
}
/* set up result */
result->tag = INT_TAG;
result->val.n = rangeIndex;
return True;
}
/*
** Set the color of a range set's ranges. it is ignored if the color cannot be
** found/applied. If no color is applied, any current color is removed. Returns
** true if the rangeset is valid.
*/
static int rangesetSetColorMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg)
{
char stringStorage[1][TYPE_INT_STR_SIZE(int)];
textBuffer *buffer = window->buffer;
RangesetTable *rangesetTable = buffer->rangesetTable;
Rangeset *rangeset;
char *color_name;
int label = 0;
if (nArgs != 2) {
return wrongNArgsErr(errMsg);
}
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
rangeset = RangesetFetch(rangesetTable, label);
if (rangeset == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
color_name = "";
if (rangeset != NULL) {
if (!readStringArg(argList[1], &color_name, stringStorage[0], errMsg)) {
M_FAILURE("Second parameter is not a color name string in %s");
}
}
RangesetAssignColorName(rangeset, color_name);
/* set up result */
result->tag = NO_TAG;
return True;
}
/*
** Set the name of a range set's ranges. Returns
** true if the rangeset is valid.
*/
static int rangesetSetNameMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg)
{
char stringStorage[1][TYPE_INT_STR_SIZE(int)];
textBuffer *buffer = window->buffer;
RangesetTable *rangesetTable = buffer->rangesetTable;
Rangeset *rangeset;
char *name;
int label = 0;
if (nArgs != 2) {
return wrongNArgsErr(errMsg);
}
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
rangeset = RangesetFetch(rangesetTable, label);
if (rangeset == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
name = "";
if (rangeset != NULL) {
if (!readStringArg(argList[1], &name, stringStorage[0], errMsg)) {
M_FAILURE("Second parameter is not a valid name string in %s");
}
}
RangesetAssignName(rangeset, name);
/* set up result */
result->tag = NO_TAG;
return True;
}
/*
** Change a range's modification response. Returns true if the rangeset is
** valid and the response type name is valid.
*/
static int rangesetSetModeMS(WindowInfo *window, DataValue *argList,
int nArgs, DataValue *result, char **errMsg)
{
char stringStorage[1][TYPE_INT_STR_SIZE(int)];
textBuffer *buffer = window->buffer;
RangesetTable *rangesetTable = buffer->rangesetTable;
Rangeset *rangeset;
char *update_fn_name;
int ok;
int label = 0;
if (nArgs < 1 || nArgs > 2) {
return wrongNArgsErr(errMsg);
}
if (!readIntArg(argList[0], &label, errMsg)
|| !RangesetLabelOK(label)) {
M_FAILURE("First parameter is an invalid rangeset label in %s");
}
if (rangesetTable == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
rangeset = RangesetFetch(rangesetTable, label);
if (rangeset == NULL) {
M_FAILURE("Rangeset does not exist in %s");
}
update_fn_name = "";
if (rangeset != NULL) {
if (nArgs == 2) {
if (!readStringArg(argList[1], &update_fn_name, stringStorage[0], errMsg)) {
M_FAILURE("Second parameter is not a string in %s");
}
}
}
ok = RangesetChangeModifyResponse(rangeset, update_fn_name);
if (!ok) {
M_FAILURE("Second parameter is not a valid mode in %s");
}
/* set up result */
result->tag = NO_TAG;
return True;
}
/* -------------------------------------------------------------------------- */
/*
** Routines to get details directly from the window.
*/
/*
** Sets up an array containing information about a style given its name or
** a buffer position (bufferPos >= 0) and its highlighting pattern code
** (patCode >= 0).
** From the name we obtain:
** ["color"] Foreground color name of style
** ["background"] Background color name of style if specified
** ["bold"] '1' if style is bold, '0' otherwise
** ["italic"] '1' if style is italic, '0' otherwise
** Given position and pattern code we obtain:
** ["rgb"] RGB representation of foreground color of style
** ["back_rgb"] RGB representation of background color of style
** ["extent"] Forward distance from position over which style applies
** We only supply the style name if the includeName parameter is set:
** ["style"] Name of style
**
*/
static int fillStyleResult(DataValue *result, char **errMsg,
WindowInfo *window, char *styleName, Boolean preallocatedStyleName,
Boolean includeName, int patCode, int bufferPos)
{
DataValue DV;
char colorValue[20];
int r, g, b;
/* initialize array */
result->tag = ARRAY_TAG;
result->val.arrayPtr = ArrayNew();
/* the following array entries will be strings */
DV.tag = STRING_TAG;
if (includeName) {
/* insert style name */
if (preallocatedStyleName) {
DV.val.str.rep = styleName;
DV.val.str.len = strlen(styleName);
}
else {
AllocNStringCpy(&DV.val.str, styleName);
}
M_STR_ALLOC_ASSERT(DV);
if (!ArrayInsert(result, PERM_ALLOC_STR("style"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
}
/* insert color name */
AllocNStringCpy(&DV.val.str, ColorOfNamedStyle(styleName));
M_STR_ALLOC_ASSERT(DV);
if (!ArrayInsert(result, PERM_ALLOC_STR("color"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
/* Prepare array element for color value
(only possible if we pass through the dynamic highlight pattern tables
in other words, only if we have a pattern code) */
if (patCode) {
HighlightColorValueOfCode(window, patCode, &r, &g, &b);
sprintf(colorValue, "#%02x%02x%02x", r/256, g/256, b/256);
AllocNStringCpy(&DV.val.str, colorValue);
M_STR_ALLOC_ASSERT(DV);
if (!ArrayInsert(result, PERM_ALLOC_STR("rgb"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
}
/* Prepare array element for background color name */
AllocNStringCpy(&DV.val.str, BgColorOfNamedStyle(styleName));
M_STR_ALLOC_ASSERT(DV);
if (!ArrayInsert(result, PERM_ALLOC_STR("background"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
/* Prepare array element for background color value
(only possible if we pass through the dynamic highlight pattern tables
in other words, only if we have a pattern code) */
if (patCode) {
GetHighlightBGColorOfCode(window, patCode, &r, &g, &b);
sprintf(colorValue, "#%02x%02x%02x", r/256, g/256, b/256);
AllocNStringCpy(&DV.val.str, colorValue);
M_STR_ALLOC_ASSERT(DV);
if (!ArrayInsert(result, PERM_ALLOC_STR("back_rgb"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
}
/* the following array entries will be integers */
DV.tag = INT_TAG;
/* Put boldness value in array */
DV.val.n = FontOfNamedStyleIsBold(styleName);
if (!ArrayInsert(result, PERM_ALLOC_STR("bold"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
/* Put italicity value in array */
DV.val.n = FontOfNamedStyleIsItalic(styleName);
if (!ArrayInsert(result, PERM_ALLOC_STR("italic"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
if (bufferPos >= 0) {
/* insert extent */
const char *styleNameNotUsed = NULL;
DV.val.n = StyleLengthOfCodeFromPos(window, bufferPos, &styleNameNotUsed);
if (!ArrayInsert(result, PERM_ALLOC_STR("extent"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
}
return True;
}
/*
** Returns an array containing information about the style of name $1
** ["color"] Foreground color name of style
** ["background"] Background color name of style if specified
** ["bold"] '1' if style is bold, '0' otherwise
** ["italic"] '1' if style is italic, '0' otherwise
**
*/
static int getStyleByNameMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[1][TYPE_INT_STR_SIZE(int)];
char *styleName;
/* Validate number of arguments */
if (nArgs != 1) {
return wrongNArgsErr(errMsg);
}
/* Prepare result */
result->tag = ARRAY_TAG;
result->val.arrayPtr = NULL;
if (!readStringArg(argList[0], &styleName, stringStorage[0], errMsg)) {
M_FAILURE("First parameter is not a string in %s");
}
if (!NamedStyleExists(styleName)) {
/* if the given name is invalid we just return an empty array. */
return True;
}
return fillStyleResult(result, errMsg, window,
styleName, (argList[0].tag == STRING_TAG), False, 0, -1);
}
/*
** Returns an array containing information about the style of position $1
** ["style"] Name of style
** ["color"] Foreground color name of style
** ["background"] Background color name of style if specified
** ["bold"] '1' if style is bold, '0' otherwise
** ["italic"] '1' if style is italic, '0' otherwise
** ["rgb"] RGB representation of foreground color of style
** ["back_rgb"] RGB representation of background color of style
** ["extent"] Forward distance from position over which style applies
**
*/
static int getStyleAtPosMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int patCode;
int bufferPos;
textBuffer *buf = window->buffer;
/* Validate number of arguments */
if (nArgs != 1) {
return wrongNArgsErr(errMsg);
}
/* Prepare result */
result->tag = ARRAY_TAG;
result->val.arrayPtr = NULL;
if (!readIntArg(argList[0], &bufferPos, errMsg)) {
return False;
}
/* Verify sane buffer position */
if ((bufferPos < 0) || (bufferPos >= buf->length)) {
/* If the position is not legal, we cannot guess anything about
the style, so we return an empty array. */
return True;
}
/* Determine pattern code */
patCode = HighlightCodeOfPos(window, bufferPos);
if (patCode == 0) {
/* if there is no pattern we just return an empty array. */
return True;
}
return fillStyleResult(result, errMsg, window,
HighlightStyleOfCode(window, patCode), False, True, patCode, bufferPos);
}
/*
** Sets up an array containing information about a pattern given its name or
** a buffer position (bufferPos >= 0).
** From the name we obtain:
** ["style"] Name of style
** ["extent"] Forward distance from position over which style applies
** We only supply the pattern name if the includeName parameter is set:
** ["pattern"] Name of pattern
**
*/
static int fillPatternResult(DataValue *result, char **errMsg,
WindowInfo *window, char *patternName, Boolean preallocatedPatternName,
Boolean includeName, char* styleName, int bufferPos)
{
DataValue DV;
/* initialize array */
result->tag = ARRAY_TAG;
result->val.arrayPtr = ArrayNew();
/* the following array entries will be strings */
DV.tag = STRING_TAG;
if (includeName) {
/* insert pattern name */
if (preallocatedPatternName) {
DV.val.str.rep = patternName;
DV.val.str.len = strlen(patternName);
}
else {
AllocNStringCpy(&DV.val.str, patternName);
}
M_STR_ALLOC_ASSERT(DV);
if (!ArrayInsert(result, PERM_ALLOC_STR("pattern"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
}
/* insert style name */
AllocNStringCpy(&DV.val.str, styleName);
M_STR_ALLOC_ASSERT(DV);
if (!ArrayInsert(result, PERM_ALLOC_STR("style"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
/* the following array entries will be integers */
DV.tag = INT_TAG;
if (bufferPos >= 0) {
/* insert extent */
int checkCode = 0;
DV.val.n = HighlightLengthOfCodeFromPos(window, bufferPos, &checkCode);
if (!ArrayInsert(result, PERM_ALLOC_STR("extent"), &DV)) {
M_ARRAY_INSERT_FAILURE();
}
}
return True;
}
/*
** Returns an array containing information about a highlighting pattern. The
** single parameter contains the pattern name for which this information is
** requested.
** The returned array looks like this:
** ["style"] Name of style
*/
static int getPatternByNameMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
char stringStorage[1][TYPE_INT_STR_SIZE(int)];
char *patternName = NULL;
highlightPattern *pattern;
/* Begin of building the result. */
result->tag = ARRAY_TAG;
result->val.arrayPtr = NULL;
/* Validate number of arguments */
if (nArgs != 1) {
return wrongNArgsErr(errMsg);
}
if (!readStringArg(argList[0], &patternName, stringStorage[0], errMsg)) {
M_FAILURE("First parameter is not a string in %s");
}
pattern = FindPatternOfWindow(window, patternName);
if (pattern == NULL) {
/* The pattern's name is unknown. */
return True;
}
return fillPatternResult(result, errMsg, window, patternName,
(argList[0].tag == STRING_TAG), False, pattern->style, -1);
}
/*
** Returns an array containing information about the highlighting pattern
** applied at a given position, passed as the only parameter.
** The returned array looks like this:
** ["pattern"] Name of pattern
** ["style"] Name of style
** ["extent"] Distance from position over which this pattern applies
*/
static int getPatternAtPosMS(WindowInfo *window, DataValue *argList, int nArgs,
DataValue *result, char **errMsg)
{
int bufferPos = -1;
textBuffer *buffer = window->buffer;
int patCode = 0;
/* Begin of building the result. */
result->tag = ARRAY_TAG;
result->val.arrayPtr = NULL;
/* Validate number of arguments */
if (nArgs != 1) {
return wrongNArgsErr(errMsg);
}
/* The most straightforward case: Get a pattern, style and extent
for a buffer position. */
if (!readIntArg(argList[0], &bufferPos, errMsg)) {
return False;
}
/* Verify sane buffer position
* You would expect that buffer->length would be among the sane
* positions, but we have n characters and n+1 buffer positions. */
if ((bufferPos < 0) || (bufferPos >= buffer->length)) {
/* If the position is not legal, we cannot guess anything about
the highlighting pattern, so we return an empty array. */
return True;
}
/* Determine the highlighting pattern used */
patCode = HighlightCodeOfPos(window, bufferPos);
if (patCode == 0) {
/* if there is no highlighting pattern we just return an empty array. */
return True;
}
return fillPatternResult(result, errMsg, window,
HighlightNameOfCode(window, patCode), False, True,
HighlightStyleOfCode(window, patCode), bufferPos);
}
static int wrongNArgsErr(char **errMsg)
{
*errMsg = "Wrong number of arguments to function %s";
return False;
}
static int tooFewArgsErr(char **errMsg)
{
*errMsg = "Too few arguments to function %s";
return False;
}
/*
** strCaseCmp compares its arguments and returns 0 if the two strings
** are equal IGNORING case differences. Otherwise returns 1 or -1
** depending on relative comparison.
*/
static int strCaseCmp(char *str1, char *str2)
{
char *c1, *c2;
for (c1 = str1, c2 = str2;
(*c1 != '\0' && *c2 != '\0')
&& toupper((unsigned char)*c1) == toupper((unsigned char)*c2);
++c1, ++c2)
{
}
if (((unsigned char)toupper((unsigned char)*c1))
> ((unsigned char)toupper((unsigned char)*c2)))
{
return(1);
} else if (((unsigned char)toupper((unsigned char)*c1))
< ((unsigned char)toupper((unsigned char)*c2)))
{
return(-1);
} else
{
return(0);
}
}
/*
** Get an integer value from a tagged DataValue structure. Return True
** if conversion succeeded, and store result in *result, otherwise
** return False with an error message in *errMsg.
*/
static int readIntArg(DataValue dv, int *result, char **errMsg)
{
char *c;
if (dv.tag == INT_TAG) {
*result = dv.val.n;
return True;
} else if (dv.tag == STRING_TAG) {
for (c=dv.val.str.rep; *c != '\0'; c++) {
if (!(isdigit((unsigned char)*c) || *c == ' ' || *c == '\t')) {
goto typeError;
}
}
sscanf(dv.val.str.rep, "%d", result);
return True;
}
typeError:
*errMsg = "%s called with non-integer argument";
return False;
}
/*
** Get an string value from a tagged DataValue structure. Return True
** if conversion succeeded, and store result in *result, otherwise
** return False with an error message in *errMsg. If an integer value
** is converted, write the string in the space provided by "stringStorage",
** which must be large enough to handle ints of the maximum size.
*/
static int readStringArg(DataValue dv, char **result, char *stringStorage,
char **errMsg)
{
if (dv.tag == STRING_TAG) {
*result = dv.val.str.rep;
return True;
} else if (dv.tag == INT_TAG) {
sprintf(stringStorage, "%d", dv.val.n);
*result = stringStorage;
return True;
}
*errMsg = "%s called with unknown object";
return False;
}
|