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
|
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright : (C) 2008 by Eran Ifrah
// file name : cl_editor.cpp
//
// -------------------------------------------------------------------------
// A
// _____ _ _ _ _
// / __ \ | | | | (_) |
// | / \/ ___ __| | ___| | _| |_ ___
// | | / _ \ / _ |/ _ \ | | | __/ _ )
// | \__/\ (_) | (_| | __/ |___| | || __/
// \____/\___/ \__,_|\___\_____/_|\__\___|
//
// F i l e
//
// This program 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.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include "file_logger.h"
#include "precompiled_header.h"
#include "cl_editor.h"
#include "code_completion_manager.h"
#include "macromanager.h"
#include <wx/log.h>
#include "event_notifier.h"
#include "code_completion_box.h"
#include "event_notifier.h"
#include "cl_editor_tip_window.h"
#include "new_quick_watch_dlg.h"
#include "buildtabsettingsdata.h"
#include "jobqueue.h"
#include "stringhighlighterjob.h"
#include "job.h"
#include "drawingutils.h"
#include "cc_box.h"
#include "stringsearcher.h"
#include "colourrequest.h"
#include "colourthread.h"
#include "parse_thread.h"
#include "ctags_manager.h"
#include "manager.h"
#include "menumanager.h"
#include "findreplacedlg.h"
#include "context_manager.h"
#include "editor_config.h"
#include "filedroptarget.h"
#include "fileutils.h"
#include "simpletable.h"
#include "debuggerpane.h"
#include "frame.h"
#include "pluginmanager.h"
#include "breakpointdlg.h"
#include "debuggersettings.h"
#include "globals.h"
#include "debuggerconfigtool.h"
#include "addincludefiledlg.h"
#include "quickfindbar.h"
#include "new_build_tab.h"
#include "localworkspace.h"
#include "findresultstab.h"
#include "bookmark_manager.h"
#include "clang_code_completion.h"
#include <wx/wupdlock.h>
#include "cl_command_event.h"
#include "codelite_events.h"
// fix bug in wxscintilla.h
#ifdef EVT_STC_CALLTIP_CLICK
#undef EVT_STC_CALLTIP_CLICK
#define EVT_STC_CALLTIP_CLICK(id, fn) \
DECLARE_EVENT_TABLE_ENTRY( \
wxEVT_STC_CALLTIP_CLICK, \
id, \
wxID_ANY, \
(wxObjectEventFunction)(wxEventFunction)wxStaticCastEvent(wxStyledTextEventFunction, &fn), \
(wxObject*)NULL),
#endif
#define NUMBER_MARGIN_ID 0
#define EDIT_TRACKER_MARGIN_ID 1
#define SYMBOLS_MARGIN_ID 2
#define SYMBOLS_MARGIN_SEP_ID 3
#define FOLD_MARGIN_ID 4
#define CL_LINE_MODIFIED_STYLE 200
#define CL_LINE_SAVED_STYLE 201
#define ANNOTATION_STYLE_WARNING 210
#define ANNOTATION_STYLE_ERROR 211
// debugger line marker xpms
extern const char* arrow_right_green_xpm[];
extern const char* stop_xpm[]; // Breakpoint
extern const char* BreakptDisabled[];
extern const char* BreakptCommandList[];
extern const char* BreakptCommandListDisabled[];
extern const char* BreakptIgnore[];
extern const char* ConditionalBreakpt[];
extern const char* ConditionalBreakptDisabled[];
const wxEventType wxCMD_EVENT_REMOVE_MATCH_INDICATOR = XRCID("remove_match_indicator");
const wxEventType wxCMD_EVENT_ENABLE_WORD_HIGHLIGHT = ::wxNewEventType();
BEGIN_EVENT_TABLE(LEditor, wxStyledTextCtrl)
EVT_STC_CHARADDED(wxID_ANY, LEditor::OnCharAdded)
EVT_STC_MARGINCLICK(wxID_ANY, LEditor::OnMarginClick)
EVT_STC_CALLTIP_CLICK(wxID_ANY, LEditor::OnCallTipClick)
EVT_STC_DWELLEND(wxID_ANY, LEditor::OnDwellEnd)
EVT_STC_START_DRAG(wxID_ANY, LEditor::OnDragStart)
EVT_STC_DO_DROP(wxID_ANY, LEditor::OnDragEnd)
EVT_STC_PAINTED(wxID_ANY, LEditor::OnScnPainted)
EVT_STC_UPDATEUI(wxID_ANY, LEditor::OnSciUpdateUI)
EVT_STC_SAVEPOINTREACHED(wxID_ANY, LEditor::OnSavePoint)
EVT_STC_SAVEPOINTLEFT(wxID_ANY, LEditor::OnSavePoint)
EVT_STC_MODIFIED(wxID_ANY, LEditor::OnChange)
EVT_CONTEXT_MENU(LEditor::OnContextMenu)
EVT_KEY_DOWN(LEditor::OnKeyDown)
EVT_KEY_UP(LEditor::OnKeyUp)
EVT_LEFT_DOWN(LEditor::OnLeftDown)
EVT_RIGHT_DOWN(LEditor::OnRightDown)
EVT_RIGHT_UP(LEditor::OnRightUp)
EVT_MOTION(LEditor::OnMotion)
EVT_LEFT_UP(LEditor::OnLeftUp)
EVT_LEAVE_WINDOW(LEditor::OnLeaveWindow)
EVT_KILL_FOCUS(LEditor::OnFocusLost)
EVT_SET_FOCUS(LEditor::OnFocus)
EVT_STC_DOUBLECLICK(wxID_ANY, LEditor::OnLeftDClick)
EVT_COMMAND(wxID_ANY, wxEVT_FRD_FIND_NEXT, LEditor::OnFindDialog)
EVT_COMMAND(wxID_ANY, wxEVT_FRD_REPLACE, LEditor::OnFindDialog)
EVT_COMMAND(wxID_ANY, wxEVT_FRD_REPLACEALL, LEditor::OnFindDialog)
EVT_COMMAND(wxID_ANY, wxEVT_FRD_BOOKMARKALL, LEditor::OnFindDialog)
EVT_COMMAND(wxID_ANY, wxEVT_FRD_CLOSE, LEditor::OnFindDialog)
EVT_COMMAND(wxID_ANY, wxEVT_FRD_CLEARBOOKMARKS, LEditor::OnFindDialog)
EVT_COMMAND(wxID_ANY, wxCMD_EVENT_REMOVE_MATCH_INDICATOR, LEditor::OnRemoveMatchInidicator)
EVT_COMMAND(wxID_ANY, wxCMD_EVENT_SET_EDITOR_ACTIVE, LEditor::OnSetActive)
END_EVENT_TABLE()
// Instantiate statics
FindReplaceDialog* LEditor::m_findReplaceDlg = NULL;
FindReplaceData LEditor::m_findReplaceData;
std::map<wxString, int> LEditor::ms_bookmarkShapes;
bool LEditor::m_ccShowPrivateMembers = true;
bool LEditor::m_ccShowItemsComments = true;
bool LEditor::m_ccInitialized = false;
LEditor::LEditor(wxWindow* parent)
: wxStyledTextCtrl(parent, wxID_ANY, wxDefaultPosition, wxSize(1, 1), wxNO_BORDER)
, m_rightClickMenu(NULL)
, m_popupIsOn(false)
, m_isDragging(false)
, m_modifyTime(0)
, m_isVisible(true)
, m_hyperLinkIndicatroStart(wxNOT_FOUND)
, m_hyperLinkIndicatroEnd(wxNOT_FOUND)
, m_hyperLinkType(wxID_NONE)
, m_hightlightMatchedBraces(true)
, m_autoAddMatchedCurlyBrace(false)
, m_autoAddNormalBraces(false)
, m_autoAdjustHScrollbarWidth(true)
, m_reloadingFile(false)
, m_functionTip(NULL)
, m_lastCharEntered(0)
, m_lastCharEnteredPos(0)
, m_isFocused(true)
, m_pluginInitializedRMenu(false)
, m_positionToEnsureVisible(wxNOT_FOUND)
, m_fullLineCopyCut(false)
, m_findBookmarksActive(false)
{
m_commandsProcessor.SetParent(this);
ms_bookmarkShapes[wxT("Small Rectangle")] = wxSTC_MARK_SMALLRECT;
ms_bookmarkShapes[wxT("Rounded Rectangle")] = wxSTC_MARK_ROUNDRECT;
ms_bookmarkShapes[wxT("Small Arrow")] = wxSTC_MARK_ARROW;
ms_bookmarkShapes[wxT("Circle")] = wxSTC_MARK_CIRCLE;
SetSyntaxHighlight();
CmdKeyClear(wxT('D'), wxSTC_SCMOD_CTRL); // clear Ctrl+D because we use it for something else
Connect(wxEVT_STC_DWELLSTART, wxStyledTextEventHandler(LEditor::OnDwellStart), NULL, this);
// Initialise the breakpt-marker array
FillBPtoMarkerArray();
// set EOL mode for the newly created file
int eol = GetEOLByOS();
int alternate_eol = GetEOLByContent();
if(alternate_eol != wxNOT_FOUND) {
eol = alternate_eol;
}
SetEOLMode(eol);
// Create the various tip windows
m_functionTip = new clEditorTipWindow(this);
m_disableSmartIndent = GetOptions()->GetDisableSmartIndent();
m_deltas = new EditorDeltasHolder;
EventNotifier::Get()->Connect(
wxCMD_EVENT_ENABLE_WORD_HIGHLIGHT, wxCommandEventHandler(LEditor::OnHighlightWordChecked), NULL, this);
EventNotifier::Get()->Connect(
wxEVT_CODEFORMATTER_INDENT_STARTING, wxCommandEventHandler(LEditor::OnFileFormatStarting), NULL, this);
EventNotifier::Get()->Connect(
wxEVT_CODEFORMATTER_INDENT_COMPLETED, wxCommandEventHandler(LEditor::OnFileFormatDone), NULL, this);
Bind(wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler(LEditor::OnChangeActiveBookmarkType),
this,
XRCID("BookmarkTypes[start]"),
XRCID("BookmarkTypes[end]"));
}
LEditor::~LEditor()
{
EventNotifier::Get()->Disconnect(
wxCMD_EVENT_ENABLE_WORD_HIGHLIGHT, wxCommandEventHandler(LEditor::OnHighlightWordChecked), NULL, this);
EventNotifier::Get()->Disconnect(
wxEVT_CODEFORMATTER_INDENT_STARTING, wxCommandEventHandler(LEditor::OnFileFormatStarting), NULL, this);
EventNotifier::Get()->Disconnect(
wxEVT_CODEFORMATTER_INDENT_COMPLETED, wxCommandEventHandler(LEditor::OnFileFormatDone), NULL, this);
Unbind(wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler(LEditor::OnChangeActiveBookmarkType),
this,
XRCID("BookmarkTypes[start]"),
XRCID("BookmarkTypes[end]"));
delete m_deltas;
if(this->HasCapture()) {
this->ReleaseMouse();
}
}
time_t LEditor::GetFileLastModifiedTime() const { return GetFileModificationTime(m_fileName.GetFullPath()); }
void LEditor::SetSyntaxHighlight(const wxString& lexerName)
{
ClearDocumentStyle();
m_context = ContextManager::Get()->NewContext(this, lexerName);
m_rightClickMenu = m_context->GetMenu();
m_rightClickMenu->AppendSeparator(); // separates plugins
SetProperties();
SetEOL();
m_context->SetActive();
m_context->ApplySettings();
UpdateColours();
}
void LEditor::SetSyntaxHighlight(bool bUpdateColors)
{
ClearDocumentStyle();
m_context = ContextManager::Get()->NewContextByFileName(this, m_fileName);
m_rightClickMenu = m_context->GetMenu();
m_rightClickMenu->AppendSeparator(); // separates plugins
SetProperties();
m_context->SetActive();
m_context->ApplySettings();
if(bUpdateColors) {
UpdateColours();
}
}
// Fills the struct array that marries breakpoint type to marker and mask
void LEditor::FillBPtoMarkerArray()
{
BPtoMarker bpm;
bpm.bp_type = BP_type_break;
bpm.marker = smt_breakpoint;
bpm.mask = mmt_breakpoint;
bpm.marker_disabled = smt_bp_disabled;
bpm.mask_disabled = mmt_bp_disabled;
m_BPstoMarkers.push_back(bpm);
BPtoMarker bpcmdm;
bpcmdm.bp_type = BP_type_cmdlistbreak;
bpcmdm.marker = smt_bp_cmdlist;
bpcmdm.mask = mmt_bp_cmdlist;
bpcmdm.marker_disabled = smt_bp_cmdlist_disabled;
bpcmdm.mask_disabled = mmt_bp_cmdlist_disabled;
m_BPstoMarkers.push_back(bpcmdm);
BPtoMarker bpcondm;
bpcondm.bp_type = BP_type_condbreak;
bpcondm.marker = smt_cond_bp;
bpcondm.mask = mmt_cond_bp;
bpcondm.marker_disabled = smt_cond_bp_disabled;
bpcondm.mask_disabled = mmt_cond_bp_disabled;
m_BPstoMarkers.push_back(bpcondm);
BPtoMarker bpignm;
bpignm.bp_type = BP_type_ignoredbreak;
bpignm.marker = bpignm.marker_disabled = smt_bp_ignored;
bpignm.mask = bpignm.mask_disabled = mmt_bp_ignored; // Enabled/disabled are the same
m_BPstoMarkers.push_back(bpignm);
bpm.bp_type = BP_type_tempbreak;
m_BPstoMarkers.push_back(bpm); // Temp is the same as non-temp
}
// Looks for a struct for this breakpoint-type
BPtoMarker LEditor::GetMarkerForBreakpt(enum BreakpointType bp_type)
{
std::vector<BPtoMarker>::iterator iter = m_BPstoMarkers.begin();
for(; iter != m_BPstoMarkers.end(); ++iter) {
if((*iter).bp_type == bp_type) {
return *iter;
}
}
wxLogMessage(wxT("Breakpoint type not in vector!?"));
return *iter;
}
void LEditor::SetCaretAt(long pos)
{
DoSetCaretAt(pos);
EnsureCaretVisible();
}
/// Setup some scintilla properties
void LEditor::SetProperties()
{
SetRectangularSelectionModifier(wxSTC_SCMOD_CTRL);
SetAdditionalSelectionTyping(true);
OptionsConfigPtr options = GetOptions();
CallTipUseStyle(1);
CallTipSetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK));
CallTipSetForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOTEXT));
m_hightlightMatchedBraces = options->GetHighlightMatchedBraces();
m_autoAddMatchedCurlyBrace = options->GetAutoAddMatchedCurlyBraces();
m_autoAddNormalBraces = options->GetAutoAddMatchedNormalBraces();
m_autoAdjustHScrollbarWidth = options->GetAutoAdjustHScrollBarWidth();
m_disableSmartIndent = options->GetDisableSmartIndent();
m_disableSemicolonShift = options->GetDisableSemicolonShift();
SetMultipleSelection(!options->HasOption(OptionsConfig::Opt_Disable_Multiselect));
SetMultiPaste(options->HasOption(OptionsConfig::Opt_Disable_Multipaste) ? 0 : 1);
if(!m_hightlightMatchedBraces) {
wxStyledTextCtrl::BraceHighlight(wxSTC_INVALID_POSITION, wxSTC_INVALID_POSITION);
SetHighlightGuide(0);
}
SetVirtualSpaceOptions(options->GetOptions() & OptionsConfig::Opt_AllowCaretAfterEndOfLine ? 2 : 1);
SetWrapMode(options->GetWordWrap() ? wxSTC_WRAP_WORD : wxSTC_WRAP_NONE);
SetViewWhiteSpace(options->GetShowWhitspaces());
SetMouseDwellTime(500);
SetProperty(wxT("fold"), wxT("1"));
SetProperty(wxT("fold.html"), wxT("1"));
SetProperty(wxT("fold.comment"), wxT("1"));
SetProperty(wxT("fold.at.else"), options->GetFoldAtElse() ? wxT("1") : wxT("0"));
SetProperty(wxT("fold.preprocessor"), options->GetFoldPreprocessor() ? wxT("1") : wxT("0"));
SetProperty(wxT("fold.compact"), options->GetFoldCompact() ? wxT("1") : wxT("0"));
// disable pre-processing (for now)
// TODO: make this configurable
SetProperty(wxT("lexer.cpp.track.preprocessor"), wxT("0"));
SetProperty(wxT("lexer.cpp.update.preprocessor"), wxT("0"));
// Fold and comments as well
SetProperty(wxT("fold.comment"), wxT("1"));
SetModEventMask(wxSTC_MOD_DELETETEXT | wxSTC_MOD_INSERTTEXT | wxSTC_PERFORMED_UNDO | wxSTC_PERFORMED_REDO |
wxSTC_MOD_BEFOREDELETE | wxSTC_MOD_CHANGESTYLE);
int caretSlop = 1;
int caretZone = 20;
int caretStrict = 0;
int caretEven = 0;
int caretJumps = 0;
SetXCaretPolicy(caretStrict | caretSlop | caretEven | caretJumps, caretZone);
caretSlop = 1;
caretZone = 1;
caretStrict = 4;
caretEven = 8;
caretJumps = 0;
SetYCaretPolicy(caretStrict | caretSlop | caretEven | caretJumps, caretZone);
SetCaretWidth(options->GetCaretWidth());
SetCaretPeriod(options->GetCaretBlinkPeriod());
SetMarginLeft(1);
// Mark current line
SetCaretLineVisible(options->GetHighlightCaretLine());
SetCaretLineBackground(options->GetCaretLineColour());
SetCaretLineBackAlpha(30);
// MarkerSetAlpha(smt_bookmark, 30);
SetFoldFlags(options->GetUnderlineFoldLine() ? 16 : 0);
SetEndAtLastLine(!options->GetScrollBeyondLastLine());
//------------------------------------------
// Margin settings
//------------------------------------------
// symbol margin
SetMarginType(SYMBOLS_MARGIN_ID, wxSTC_MARGIN_SYMBOL);
// Line numbers
SetMarginType(NUMBER_MARGIN_ID, wxSTC_MARGIN_NUMBER);
// line number margin displays every thing but folding, bookmarks and breakpoint
SetMarginMask(NUMBER_MARGIN_ID,
~(mmt_folds | mmt_all_bookmarks | mmt_indicator | mmt_compiler | mmt_all_breakpoints));
SetMarginType(EDIT_TRACKER_MARGIN_ID, 4); // Styled Text margin
SetMarginWidth(EDIT_TRACKER_MARGIN_ID, options->GetHideChangeMarkerMargin() ? 0 : 3);
SetMarginMask(EDIT_TRACKER_MARGIN_ID, 0);
// Separators
SetMarginType(SYMBOLS_MARGIN_SEP_ID, wxSTC_MARGIN_FORE);
SetMarginMask(SYMBOLS_MARGIN_SEP_ID, 0);
// Fold margin - allow only folder symbols to display
SetMarginMask(FOLD_MARGIN_ID, wxSTC_MASK_FOLDERS);
// Set margins' width
SetMarginWidth(SYMBOLS_MARGIN_ID, options->GetDisplayBookmarkMargin() ? 16 : 0); // Symbol margin
// If the symbols margin is hidden, hide its related separator margin
// as well
SetMarginWidth(SYMBOLS_MARGIN_SEP_ID,
options->GetDisplayBookmarkMargin() ? 1 : 0); // Symbol margin which acts as separator
// allow everything except for the folding symbols
SetMarginMask(SYMBOLS_MARGIN_ID, ~(wxSTC_MASK_FOLDERS));
// Line number margin
#ifdef __WXMSW__
int pixelWidth = 4 + 5 * TextWidth(wxSTC_STYLE_LINENUMBER, wxT("9"));
#else
int pixelWidth = 4 + 5 * 8;
#endif
// Show number margin according to settings.
SetMarginWidth(NUMBER_MARGIN_ID, options->GetDisplayLineNumbers() ? pixelWidth : 0);
// Show the fold margin
SetMarginWidth(FOLD_MARGIN_ID, options->GetDisplayFoldMargin() ? 16 : 0); // Fold margin
// Mark fold margin & symbols margins as sensetive
SetMarginSensitive(FOLD_MARGIN_ID, true);
SetMarginSensitive(SYMBOLS_MARGIN_ID, true);
// Right margin
SetEdgeMode(options->GetEdgeMode());
SetEdgeColumn(options->GetEdgeColumn());
SetEdgeColour(options->GetEdgeColour());
//---------------------------------------------------
// Fold settings
//---------------------------------------------------
// Define the folding style to be square
if(options->GetFoldStyle() == wxT("Flatten Tree Square Headers")) {
DefineMarker(
wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_VLINE, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_LCORNER, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUSCONNECTED, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDEROPENMID,
wxSTC_MARK_BOXMINUSCONNECTED,
wxColor(0xff, 0xff, 0xff),
wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_TCORNER, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
} else if(options->GetFoldStyle() == wxT("Flatten Tree Circular Headers")) {
DefineMarker(
wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_CIRCLEMINUS, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_CIRCLEPLUS, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_VLINE, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_LCORNERCURVE, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDEREND,
wxSTC_MARK_CIRCLEPLUSCONNECTED,
wxColor(0xff, 0xff, 0xff),
wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDEROPENMID,
wxSTC_MARK_CIRCLEMINUSCONNECTED,
wxColor(0xff, 0xff, 0xff),
wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_TCORNER, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
} else if(options->GetFoldStyle() == wxT("Simple")) {
DefineMarker(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_MINUS, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_PLUS, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_BACKGROUND, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_BACKGROUND, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_PLUS, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_MINUS, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_BACKGROUND, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
} else { // use wxT("Arrows") as the default
DefineMarker(
wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_ARROWDOWN, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_ARROW, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_BACKGROUND, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_BACKGROUND, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_ARROW, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_ARROWDOWN, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
DefineMarker(
wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_BACKGROUND, wxColor(0xff, 0xff, 0xff), wxColor(0x80, 0x80, 0x80));
}
// Bookmark
int marker = wxSTC_MARK_ARROW;
std::map<wxString, int>::iterator iter = ms_bookmarkShapes.find(options->GetBookmarkShape());
if(iter != ms_bookmarkShapes.end()) {
marker = iter->second;
}
for(size_t bmt = smt_FIRST_BMK_TYPE; bmt <= smt_LAST_BMK_TYPE; ++bmt) {
MarkerDefine(bmt, marker);
MarkerSetBackground(bmt, options->GetBookmarkBgColour(bmt - smt_FIRST_BMK_TYPE));
MarkerSetForeground(bmt, options->GetBookmarkFgColour(bmt - smt_FIRST_BMK_TYPE));
}
MarkerDefineBitmap(smt_breakpoint, wxBitmap(wxImage(stop_xpm)));
MarkerDefineBitmap(smt_bp_disabled, wxBitmap(wxImage(BreakptDisabled)));
MarkerDefineBitmap(smt_bp_cmdlist, wxBitmap(wxImage(BreakptCommandList)));
MarkerDefineBitmap(smt_bp_cmdlist_disabled, wxBitmap(wxImage(BreakptCommandListDisabled)));
MarkerDefineBitmap(smt_bp_ignored, wxBitmap(wxImage(BreakptIgnore)));
MarkerDefineBitmap(smt_cond_bp, wxBitmap(wxImage(ConditionalBreakpt)));
MarkerDefineBitmap(smt_cond_bp_disabled, wxBitmap(wxImage(ConditionalBreakptDisabled)));
if(options->HasOption(OptionsConfig::Opt_Mark_Debugger_Line)) {
MarkerDefine(smt_indicator, wxSTC_MARK_BACKGROUND, wxNullColour, options->GetDebuggerMarkerLine());
MarkerSetAlpha(smt_indicator, 50);
} else {
wxImage img(arrow_right_green_xpm);
wxBitmap bmp(img);
MarkerDefineBitmap(smt_indicator, bmp);
MarkerSetBackground(smt_indicator, wxT("LIME GREEN"));
MarkerSetForeground(smt_indicator, wxT("BLACK"));
}
// warning and error markers
MarkerDefine(smt_warning, wxSTC_MARK_SHORTARROW);
MarkerSetForeground(smt_error, wxColor(128, 128, 0));
MarkerSetBackground(smt_warning, wxColor(255, 215, 0));
MarkerDefine(smt_error, wxSTC_MARK_SHORTARROW);
MarkerSetForeground(smt_error, wxColor(128, 0, 0));
MarkerSetBackground(smt_error, wxColor(255, 0, 0));
CallTipSetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK));
CallTipSetForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOTEXT));
#if defined(__WXMAC__)
// turning off these two greatly improves performance
// on Mac
SetTwoPhaseDraw(true);
SetBufferedDraw(false);
// // Using BufferedDraw as 'false'
// // improves performance *alot*, however
// // the downside is that the word hightlight does
// // not work...
// // this is why we enable / disable it according to the "highlight word" toggle state
// long highlightWord(1);
// EditorConfigST::Get()->GetLongValue(wxT("highlight_word"), highlightWord);
// SetBufferedDraw(highlightWord == 1 ? true : false);
// //wxLogMessage("Buffered draw is set to %d", (int)highlightWord);
#elif defined(__WXGTK__)
SetTwoPhaseDraw(true);
SetBufferedDraw(false);
#else // MSW
SetTwoPhaseDraw(true);
SetBufferedDraw(true);
#endif
// indentation settings
SetTabIndents(true);
SetBackSpaceUnIndents(true);
// Should we use spaces or tabs for indenting?
// Usually we will ask the configuration, however
// when using Makefile we _must_ use the TABS
wxString contextName = GetContext()->GetName();
contextName.MakeLower();
SetUseTabs((contextName == "makefile") ? true : options->GetIndentUsesTabs());
SetTabWidth(options->GetTabWidth());
SetIndent(options->GetIndentWidth());
SetIndentationGuides(options->GetShowIndentationGuidelines() ? 3 : 0);
SetLayoutCache(wxSTC_CACHE_PAGE);
size_t frame_flags = clMainFrame::Get()->GetFrameGeneralInfo().GetFlags();
SetViewEOL(frame_flags & CL_SHOW_EOL ? true : false);
// if no right click menu is provided by the context, use scintilla default
// right click menu
UsePopUp(m_rightClickMenu ? false : true);
IndicatorSetUnder(1, true);
IndicatorSetUnder(HYPERLINK_INDICATOR, true);
IndicatorSetUnder(MATCH_INDICATOR, false);
IndicatorSetUnder(DEBUGGER_INDICATOR, true);
SetUserIndicatorStyleAndColour(wxSTC_INDIC_SQUIGGLE, wxT("RED"));
wxColour col2(wxT("LIGHT BLUE"));
wxString val2 = EditorConfigST::Get()->GetStringValue(wxT("WordHighlightColour"));
if(val2.IsEmpty() == false) {
col2 = wxColour(val2);
}
IndicatorSetForeground(1, options->GetBookmarkBgColour(smt_find_bookmark - smt_FIRST_BMK_TYPE));
// Word highlight indicator
IndicatorSetStyle(MARKER_WORD_HIGHLIGHT, wxSTC_INDIC_ROUNDBOX);
IndicatorSetUnder(MARKER_WORD_HIGHLIGHT, true);
IndicatorSetForeground(MARKER_WORD_HIGHLIGHT, col2);
long alpha(1);
if(EditorConfigST::Get()->GetLongValue(wxT("WordHighlightAlpha"), alpha)) {
IndicatorSetAlpha(MARKER_WORD_HIGHLIGHT, alpha);
}
IndicatorSetStyle(HYPERLINK_INDICATOR, wxSTC_INDIC_PLAIN);
IndicatorSetStyle(MATCH_INDICATOR, wxSTC_INDIC_BOX);
IndicatorSetForeground(MATCH_INDICATOR, wxT("GREY"));
IndicatorSetStyle(DEBUGGER_INDICATOR, wxSTC_INDIC_BOX);
IndicatorSetForeground(DEBUGGER_INDICATOR, wxT("GREY"));
CmdKeyClear(wxT('L'), wxSTC_SCMOD_CTRL); // clear Ctrl+D because we use it for something else
// Set CamelCase caret movement
if(options->GetCaretUseCamelCase()) {
// selection
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_SCMOD_CTRL | wxSTC_SCMOD_SHIFT, wxSTC_CMD_WORDPARTLEFTEXTEND);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_SCMOD_CTRL | wxSTC_SCMOD_SHIFT, wxSTC_CMD_WORDPARTRIGHTEXTEND);
// movement
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_SCMOD_CTRL, wxSTC_CMD_WORDPARTLEFT);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_SCMOD_CTRL, wxSTC_CMD_WORDPARTRIGHT);
} else {
// selection
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_SCMOD_CTRL | wxSTC_SCMOD_SHIFT, wxSTC_CMD_WORDLEFTEXTEND);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_SCMOD_CTRL | wxSTC_SCMOD_SHIFT, wxSTC_CMD_WORDRIGHTEXTEND);
// movement
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_SCMOD_CTRL, wxSTC_CMD_WORDLEFT);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_SCMOD_CTRL, wxSTC_CMD_WORDRIGHT);
}
}
void LEditor::OnSavePoint(wxStyledTextEvent& event)
{
if(!GetIsVisible())
return;
wxString title;
if(GetModify()) {
title << wxT("*");
} else {
if(GetMarginWidth(EDIT_TRACKER_MARGIN_ID)) {
Freeze();
int numlines = GetLineCount();
for(int i = 0; i < numlines; i++) {
int style = MarginGetStyle(i);
if(style == CL_LINE_MODIFIED_STYLE) {
MarginSetText(i, wxT(" "));
MarginSetStyle(i, CL_LINE_SAVED_STYLE);
}
}
Refresh();
Thaw();
}
}
title << GetFileName().GetFullName();
clMainFrame::Get()->GetMainBook()->SetPageTitle(this, title);
DoUpdateTLWTitle(false);
}
void LEditor::OnCharAdded(wxStyledTextEvent& event)
{
// allways cancel the tip
CodeCompletionBox::Get().CancelTip();
int pos = GetCurrentPos();
bool canShowCompletionBox(true);
// get the word and select it in the completion box
if(IsCompletionBoxShown()) {
int start = WordStartPosition(pos, true);
wxString word = GetTextRange(start, pos);
if(word.IsEmpty()) {
HideCompletionBox();
} else {
if(CodeCompletionBox::Get().SelectWord(word)) {
canShowCompletionBox = false;
HideCompletionBox();
}
}
}
// make sure line is visible
int curLine = LineFromPosition(pos);
if(!GetFoldExpanded(curLine)) {
ToggleFold(curLine);
}
bool bJustAddedIndicator = false;
// add complete quotes; but don't if the next char is alnum,
// which is annoying if you're trying to retrofit quotes around a string!
// Also not if the previous char is alnum: it's more likely (especially in non-code editors)
// that someone is trying to type _don't_ than it's a burning desire to write _don''_
int nextChar = SafeGetChar(pos), prevChar = SafeGetChar(pos - 2);
if(GetOptions()->GetAutoCompleteDoubleQuotes() && !wxIsalnum(nextChar) && !wxIsalnum(prevChar)) {
if(event.GetKey() == wxT('"') && !m_context->IsCommentOrString(pos)) {
InsertText(pos, wxT("\""));
SetIndicatorCurrent(MATCH_INDICATOR);
IndicatorFillRange(pos, 1);
bJustAddedIndicator = true;
} else if(event.GetKey() == wxT('\'') && !m_context->IsCommentOrString(pos)) {
InsertText(pos, wxT("'"));
SetIndicatorCurrent(MATCH_INDICATOR);
IndicatorFillRange(pos, 1);
bJustAddedIndicator = true;
}
}
if(!bJustAddedIndicator && IndicatorValueAt(MATCH_INDICATOR, pos) && event.GetKey() == GetCharAt(pos)) {
CharRight();
DeleteBack();
} else if(m_autoAddNormalBraces && (event.GetKey() == ')' || event.GetKey() == ']') &&
event.GetKey() == GetCharAt(pos)) {
// disable the auto brace adding when inside comment or string
if(!m_context->IsCommentOrString(pos)) {
CharRight();
DeleteBack();
}
}
wxChar matchChar(0);
switch(event.GetKey()) {
case ';':
if(!m_disableSemicolonShift && !m_context->IsCommentOrString(pos))
m_context->SemicolonShift();
break;
case '(':
if(m_context->IsCommentOrString(GetCurrentPos()) == false) {
CodeComplete();
}
matchChar = ')';
break;
case '[':
matchChar = ']';
break;
case '{':
m_context->AutoIndent(event.GetKey());
matchChar = '}';
break;
case ':':
m_context->AutoIndent(event.GetKey());
break;
case ')':
// Remove one tip from the queue. If the queue new size is 0
// the tooltip is then cancelled
GetFunctionTip()->Remove();
break;
case '}':
m_context->AutoIndent(event.GetKey());
break;
case '\n': {
long matchedPos(wxNOT_FOUND);
// incase ENTER was hit immediatly after we inserted '{' into the code...
if(m_lastCharEntered == wxT('{') && // Last char entered was {
m_autoAddMatchedCurlyBrace && // auto-add-match-brace option is enabled
!m_disableSmartIndent && // the disable smart indent option is NOT enabled
MatchBraceBack(wxT('}'), GetCurrentPos(), matchedPos) && // Insert it only if it match an open brace
!m_context->IsDefaultContext() && // the editor's context is NOT the default one
matchedPos == m_lastCharEnteredPos) { // and that open brace must be the one that we have inserted
// Add closing brace only if the last char that was entered is the match for it
matchChar = '}';
InsertText(pos, matchChar);
BeginUndoAction();
CharRight();
m_context->AutoIndent(wxT('}'));
InsertText(pos, GetEolString());
CharRight();
SetCaretAt(pos);
m_context->AutoIndent(wxT('\n'));
EndUndoAction();
} else {
m_context->AutoIndent(event.GetKey());
// incase we are typing in a folded line, make sure it is visible
EnsureVisible(curLine + 1);
}
}
break;
default:
break;
}
// Check for code completion strings
wxChar charTyped = event.GetKey();
// get the previous char. Note that the current position is already *after* the
// current char, so we need to go back 2 chars
wxChar firstChar = SafeGetChar(GetCurrentPos() - 2);
wxString strTyped, strTyped2;
strTyped << charTyped;
strTyped2 << firstChar << charTyped;
if((GetContext()->GetCompletionTriggerStrings().count(strTyped) ||
GetContext()->GetCompletionTriggerStrings().count(strTyped2)) &&
!GetContext()->IsCommentOrString(GetCurrentPos())) {
// this char should trigger a code completion
CodeComplete();
}
if(matchChar && !m_disableSmartIndent && !m_context->IsCommentOrString(pos)) {
if(matchChar == ')' && m_autoAddNormalBraces) {
// Only add a close brace if the next char is whitespace
// or if it's an already-matched ')' (which keeps things syntactically correct)
long matchedPos(wxNOT_FOUND);
int nextChar = SafeGetChar(pos);
switch(nextChar) {
case ')':
if(!MatchBraceBack(matchChar, PositionBeforePos(pos), matchedPos)) {
break;
}
case ' ':
case '\t':
case '\n':
case '\r':
InsertText(pos, matchChar);
SetIndicatorCurrent(MATCH_INDICATOR);
// use grey colour rather than black, otherwise this indicator is invisible when using the
// black theme
IndicatorFillRange(pos, 1);
break;
}
} else if(matchChar != '}' && m_autoAddNormalBraces) {
InsertText(pos, matchChar);
SetIndicatorCurrent(MATCH_INDICATOR);
// use grey colour rather than black, otherwise this indicator is invisible when using the
// black theme
IndicatorFillRange(pos, 1);
}
}
// Show the completion box if needed. canShowCompletionBox is set to false only if it was just dismissed
// at the top of this function
if(IsCompletionBoxShown() == false && canShowCompletionBox) {
// display the keywords completion box only if user typed more than 2
// chars && the caret is placed at the end of that word
long startPos = WordStartPosition(pos, true);
if(GetWordAtCaret().Len() >= 2 && pos - startPos >= 2) {
m_context->OnUserTypedXChars(GetWordAtCaret());
}
if(TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_WORD_ASSIST) {
if(GetWordAtCaret().Len() == (size_t)TagsManagerST::Get()->GetCtagsOptions().GetMinWordLen() &&
pos - startPos >= TagsManagerST::Get()->GetCtagsOptions().GetMinWordLen()) {
CompleteWord();
}
}
}
if(event.GetKey() != 13) {
// Dont store last character if it was \r
m_lastCharEntered = event.GetKey();
// Since we already entered the character...
m_lastCharEnteredPos = PositionBefore(GetCurrentPos());
}
event.Skip();
}
void LEditor::SetEnsureCaretIsVisible(int pos, bool preserveSelection /*=true*/, bool forceDelay /*=false*/)
{
OptionsConfigPtr opts = EditorConfigST::Get()->GetOptions();
if(forceDelay || (opts && opts->GetWordWrap())) {
// If the text may be word-wrapped, don't EnsureVisible immediately but from the
// paintevent handler, so that scintilla has time to take word-wrap into account
m_positionToEnsureVisible = pos;
m_preserveSelection = preserveSelection;
} else {
DoEnsureCaretIsVisible(pos, preserveSelection);
m_positionToEnsureVisible = wxNOT_FOUND;
}
}
void LEditor::OnScnPainted(wxStyledTextEvent& event)
{
event.Skip();
if(m_positionToEnsureVisible == wxNOT_FOUND) {
return;
}
CL_DEBUG1(wxString::Format(wxT("OnScnPainted: position = %i, preserveSelection = %s"),
m_positionToEnsureVisible,
m_preserveSelection ? wxT("true") : wxT("false")));
DoEnsureCaretIsVisible(m_positionToEnsureVisible, m_preserveSelection);
m_positionToEnsureVisible = wxNOT_FOUND;
}
void LEditor::DoEnsureCaretIsVisible(int pos, bool preserveSelection)
{
int start = -1, end = -1;
if(preserveSelection) {
start = GetSelectionStart();
end = GetSelectionEnd();
}
SetCaretAt(pos);
// and finally restore any selection if requested
if(preserveSelection && (start != end)) {
this->SetSelection(start, end);
}
}
void LEditor::OnSciUpdateUI(wxStyledTextEvent& event)
{
event.Skip();
// Get current position
long pos = GetCurrentPos();
// ignore << and >>
int charAfter = SafeGetChar(PositionAfter(pos));
int charBefore = SafeGetChar(PositionBefore(pos));
int beforeBefore = SafeGetChar(PositionBefore(PositionBefore(pos)));
int charCurrnt = SafeGetChar(pos);
bool hasSelection = (GetSelectionStart() != GetSelectionEnd());
if(GetHighlightGuide() != wxNOT_FOUND)
SetHighlightGuide(0);
if(m_hightlightMatchedBraces) {
if(hasSelection) {
wxStyledTextCtrl::BraceHighlight(wxSTC_INVALID_POSITION, wxSTC_INVALID_POSITION);
} else if((charCurrnt == '<' && charAfter == '<') || //<<
(charCurrnt == '<' && charBefore == '<') || //<<
(charCurrnt == '>' && charAfter == '>') || //>>
(charCurrnt == '>' && charBefore == '>') || //>>
(beforeBefore == '<' && charBefore == '<') || //<<
(beforeBefore == '>' && charBefore == '>') || //>>
(beforeBefore == '-' && charBefore == '>') || //->
(charCurrnt == '>' && charBefore == '-')) { //->
wxStyledTextCtrl::BraceHighlight(wxSTC_INVALID_POSITION, wxSTC_INVALID_POSITION);
} else {
if((charCurrnt == '{' || charCurrnt == '[' || GetCharAt(pos) == '<' || charCurrnt == '(') &&
!m_context->IsCommentOrString(pos)) {
BraceMatch((long)pos);
} else if((charBefore == '{' || charBefore == '<' || charBefore == '[' || charBefore == '(') &&
!m_context->IsCommentOrString(PositionBefore(pos))) {
BraceMatch((long)PositionBefore(pos));
} else if((charCurrnt == '}' || charCurrnt == ']' || charCurrnt == '>' || charCurrnt == ')') &&
!m_context->IsCommentOrString(pos)) {
BraceMatch((long)pos);
} else if((charBefore == '}' || charBefore == '>' || charBefore == ']' || charBefore == ')') &&
!m_context->IsCommentOrString(PositionBefore(pos))) {
BraceMatch((long)PositionBefore(pos));
} else {
wxStyledTextCtrl::BraceHighlight(wxSTC_INVALID_POSITION, wxSTC_INVALID_POSITION);
}
}
}
int curLine = LineFromPosition(pos);
// update line number
wxString message;
message << wxT("Ln ") << curLine + 1 << wxT(", Col ") << GetColumn(pos) << wxT(", Pos ") << pos;
wxString bookmarkString = GetBookmarkLabel((sci_marker_types)GetActiveBookmarkType());
message << ", " << bookmarkString;
// Always update the status bar with event, calling it directly causes performance degredation
DoSetStatusMessage(message, 1);
SetIndicatorCurrent(MATCH_INDICATOR);
IndicatorClearRange(0, pos);
int end = PositionFromLine(curLine + 1);
if(end >= pos && end < GetTextLength()) {
IndicatorClearRange(end, GetTextLength() - end);
}
if(!hasSelection) {
// remove indicators
SetIndicatorCurrent(MARKER_WORD_HIGHLIGHT);
int last = IndicatorEnd(2, 0);
if(last != wxNOT_FOUND) {
IndicatorClearRange(0, GetLength());
#if defined(__WXMAC__) || (wxVERSION_NUMBER >= 2900 && defined(__WXMSW__))
Refresh();
#endif
}
}
RecalcHorizontalScrollbar();
// let the context handle this as well
m_context->OnSciUpdateUI(event);
}
void LEditor::OnMarginClick(wxStyledTextEvent& event)
{
int nLine = LineFromPosition(event.GetPosition());
switch(event.GetMargin()) {
case SYMBOLS_MARGIN_ID:
// symbols / breakpoints margin
{
// If Shift-LeftDown, let the user drag any breakpoint marker
if(event.GetShift()) {
int markers = (MarkerGet(nLine) & mmt_all_breakpoints);
if(!markers) {
break;
}
// There doesn't seem to be an elegant way to get the defined bitmap for a marker
wxBitmap bm;
if(markers & mmt_bp_disabled) {
bm = wxBitmap(wxImage(BreakptDisabled));
} else if(markers & mmt_bp_cmdlist) {
bm = wxBitmap(wxImage(BreakptCommandList));
} else if(markers & mmt_bp_cmdlist_disabled) {
bm = wxBitmap(wxImage(BreakptCommandListDisabled));
} else if(markers & mmt_bp_ignored) {
bm = wxBitmap(wxImage(BreakptIgnore));
} else if(markers & mmt_cond_bp) {
bm = wxBitmap(wxImage(ConditionalBreakpt));
} else if(markers & mmt_cond_bp_disabled) {
bm = wxBitmap(wxImage(ConditionalBreakptDisabled));
} else {
// Make the standard bp bitmap the default
bm = wxBitmap(wxImage(stop_xpm));
}
// There'll probably be a tooltip from the marker. Kill it
DoCancelCalltip();
// The breakpoint manager organises the actual drag/drop
BreakptMgr* bpm = ManagerST::Get()->GetBreakpointsMgr();
bpm->DragBreakpoint(this, nLine, bm);
Connect(wxEVT_MOTION, wxMouseEventHandler(myDragImage::OnMotion), NULL, bpm->GetDragImage());
Connect(wxEVT_LEFT_UP, wxMouseEventHandler(myDragImage::OnEndDrag), NULL, bpm->GetDragImage());
} else {
ToggleBreakpoint(nLine + 1);
}
}
break;
case FOLD_MARGIN_ID:
// fold margin
{
ToggleFold(nLine);
int caret_pos = GetCurrentPos();
if(caret_pos != wxNOT_FOUND) {
int caret_line = LineFromPosition(caret_pos);
if(caret_line != wxNOT_FOUND && GetLineVisible(caret_line) == false) {
// the caret line is hidden (i.e. stuck in a fold) so set it somewhere else
while(caret_line >= 0) {
if((GetFoldLevel(caret_line) & wxSTC_FOLDLEVELHEADERFLAG) && GetLineVisible(caret_line)) {
SetCaretAt(PositionFromLine(caret_line));
break;
}
caret_line--;
}
}
}
// Try to make as much as possible of the originally-displayed code stay in the same screen position
// That's no problem if the fold-head is visible: that line and above automatically stay in place
// However if it's off screen and the user clicks in a margin to fold, no part of the function will stay on
// screen
// The following code scrolls the correct amount to keep the position of the lines *below* the function
// unchanged
// This also brings the newly-folded function into view.
// NB It fails if the cursor was originally inside the new fold; but at least then the fold head gets shown
int foldparent = GetFoldParent(nLine);
int firstvisibleline = GetFirstVisibleLine();
if(!(GetFoldLevel(nLine) & wxSTC_FOLDLEVELHEADERFLAG) // If the click was below the fold head
&&
(foldparent < firstvisibleline)) { // and the fold head is off the screen
int linestoscroll = foldparent - GetLastChild(foldparent, -1);
// If there are enough lines above the screen to scroll downwards, do so
if((firstvisibleline + linestoscroll) >= 0) { // linestoscroll will always be negative
LineScroll(0, linestoscroll);
}
}
}
break;
default:
break;
}
}
void LEditor::DefineMarker(int marker, int markerType, wxColor fore, wxColor back)
{
MarkerDefine(marker, markerType);
MarkerSetForeground(marker, fore);
MarkerSetBackground(marker, back);
}
bool LEditor::SaveFile()
{
if(this->GetModify()) {
if(GetFileName().FileExists() == false) {
return SaveFileAs();
}
// first save the file content
if(!SaveToFile(m_fileName))
return false;
// if we managed to save the file, remove the 'read only' attribute
clMainFrame::Get()->GetMainBook()->MarkEditorReadOnly(this, false);
// Take a snapshot of the current deltas. We'll need this as a 'base' for any future FindInFiles call
m_deltas->OnFileSaved();
wxString projName = GetProjectName();
if(projName.Trim().Trim(false).IsEmpty())
return true;
// clear cached file, this function does nothing if the file is not cached
TagsManagerST::Get()->ClearCachedFile(GetFileName().GetFullPath());
//
if(ManagerST::Get()->IsShutdownInProgress() || ManagerST::Get()->IsWorkspaceClosing()) {
return true;
}
if(TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_DISABLE_AUTO_PARSING) {
return true;
}
m_context->RetagFile();
}
return true;
}
bool LEditor::SaveFileAs()
{
// Prompt the user for a new file name
const wxString ALL(wxT("All Files (*)|*"));
wxFileDialog dlg(this,
_("Save As"),
m_fileName.GetPath(),
m_fileName.GetFullName(),
ALL,
wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
wxDefaultPosition);
if(dlg.ShowModal() == wxID_OK) {
// get the path
wxFileName name(dlg.GetPath());
if(!SaveToFile(name)) {
wxMessageBox(_("Failed to save file"), _("Error"), wxOK | wxICON_ERROR);
return false;
}
m_fileName = name;
// update the tab title (again) since we really want to trigger an update to the file tooltip
clMainFrame::Get()->GetMainBook()->SetPageTitle(this, m_fileName.GetFullName());
DoUpdateTLWTitle(false);
// update syntax highlight
SetSyntaxHighlight();
clMainFrame::Get()->GetMainBook()->MarkEditorReadOnly(this, IsFileReadOnly(GetFileName()));
return true;
}
return false;
}
#ifdef __WXGTK__
//--------------------------------
// GTK only get permissions method
//--------------------------------
mode_t GTKGetFilePermissions(const wxString& filename)
{
// keep the original file permissions
struct stat b;
mode_t permissions(0);
if(stat(filename.mb_str(wxConvUTF8).data(), &b) == 0) {
permissions = b.st_mode;
}
return permissions;
}
#endif
// an internal function that does the actual file writing to disk
bool LEditor::SaveToFile(const wxFileName& fileName)
{
#if defined(__WXMSW__)
DWORD dwAttrs = GetFileAttributes(fileName.GetFullPath().c_str());
if(dwAttrs != INVALID_FILE_ATTRIBUTES) {
if(dwAttrs & FILE_ATTRIBUTE_READONLY) {
if(wxMessageBox(wxString::Format(wxT("'%s' \n%s"),
fileName.GetFullPath().c_str(),
_("has the read-only attribute set"),
_("Would you like CodeLite to try and remove it?")),
_("CodeLite"),
wxYES_NO | wxICON_QUESTION | wxCENTER) == wxYES) {
// try to clear the read-only flag from the file
if(SetFileAttributes(fileName.GetFullPath().c_str(), dwAttrs & ~(FILE_ATTRIBUTE_READONLY)) == FALSE) {
wxMessageBox(wxString::Format(wxT("%s '%s' %s"),
_("Failed to open file"),
fileName.GetFullPath().c_str(),
_("for write")),
_("CodeLite"),
wxOK | wxCENTER | wxICON_WARNING);
return false;
}
} else {
return false;
}
}
}
#endif
// save the file using the user's defined encoding
// unless we got a BOM set
wxCSConv fontEncConv(GetOptions()->GetFileFontEncoding());
bool useBuiltIn = (GetOptions()->GetFileFontEncoding() == wxFONTENCODING_UTF8);
// trim lines / append LF if needed
TrimText(GetOptions()->GetTrimLine(), GetOptions()->GetAppendLF());
// BUG#2982452
// try to manually convert the text to make sure that the conversion does not fail
wxString theText = GetText();
// int txtLen = GetTextLength();
// Make sure we can open the file for writing
wxString tmp_file;
#if HAS_LIBCLANG
#ifdef __WXMSW__
// There is a bug in clang that locks the file
wxFFile testFile(fileName.GetFullPath().GetData(),
"wb"); // use ab to make sure that the file content is not discarded
if(!testFile.IsOpened()) {
ClangCodeCompletion::Instance()->ClearCache();
} else {
testFile.Close();
}
#endif
#endif // HAS_LIBCLANG
wxFFile file(fileName.GetFullPath().GetData(), wxT("wb"));
if(file.IsOpened() == false) {
// Nothing to be done
if(wxMessageBox(wxString::Format(wxT("%s '%s' %s, %s"),
_("Failed to open file"),
fileName.GetFullPath().GetData(),
_("for write"),
_("Override it?")),
_("CodeLite"),
wxYES_NO | wxICON_WARNING) == wxYES) {
// try to override it
time_t curt = GetFileModificationTime(fileName.GetFullPath());
tmp_file << fileName.GetFullPath() << curt;
if(file.Open(tmp_file.c_str(), wxT("wb")) == false) {
wxMessageBox(
wxString::Format(wxT("%s '%s' %s"), _("Failed to open file"), tmp_file.c_str(), _("for write")),
_("CodeLite"),
wxOK | wxICON_WARNING);
return false;
}
} else {
return false;
}
}
const wxWX2MBbuf buf = theText.mb_str(useBuiltIn ? (const wxMBConv&)wxConvUTF8 : (const wxMBConv&)fontEncConv);
if(!buf.data()) {
wxMessageBox(wxString::Format(wxT("%s\n%s '%s'"),
_("Save file failed!"),
_("Could not convert the file to the requested encoding"),
wxFontMapper::GetEncodingName(GetOptions()->GetFileFontEncoding()).c_str()),
_("CodeLite"),
wxOK | wxICON_WARNING);
return false;
}
if(buf.length() == 0 && !theText.IsEmpty()) {
// something went wrong in the conversion process
wxString errmsg;
errmsg << _("File text conversion failed!\nCheck your file font encoding from\nSettings | Global Editor "
"Prefernces | Misc | Locale");
wxMessageBox(errmsg, "CodeLite", wxOK | wxICON_ERROR | wxCENTER, wxTheApp->GetTopWindow());
return false;
}
file.Write(buf.data(), strlen(buf.data()));
file.Close();
#ifdef __WXGTK__
// keep the original file permissions
mode_t origPermissions = GTKGetFilePermissions(fileName.GetFullPath());
#endif
// if the saving was done to a temporary file, override it
if(tmp_file.IsEmpty() == false) {
if(wxRenameFile(tmp_file, fileName.GetFullPath(), true) == false) {
wxMessageBox(
wxString::Format(_("Failed to override read-only file")), _("CodeLite"), wxOK | wxICON_WARNING);
return false;
} else {
// override was successful, restore execute permissions
#ifdef __WXGTK__
mode_t newFilePermissions = GTKGetFilePermissions(fileName.GetFullPath());
if(origPermissions & S_IXUSR)
newFilePermissions |= S_IXUSR;
if(origPermissions & S_IXGRP)
newFilePermissions |= S_IXGRP;
if(origPermissions & S_IXOTH)
newFilePermissions |= S_IXOTH;
::chmod(fileName.GetFullPath().mb_str(wxConvUTF8), newFilePermissions);
#endif
}
}
// update the modification time of the file
m_modifyTime = GetFileModificationTime(fileName.GetFullPath());
SetSavePoint();
// update the tab title (remove the star from the file name)
clMainFrame::Get()->GetMainBook()->SetPageTitle(this, fileName.GetFullName());
if(fileName.GetExt() != m_fileName.GetExt()) {
// new context is required
SetSyntaxHighlight();
}
// Fire a wxEVT_FILE_SAVED event
EventNotifier::Get()->PostFileSavedEvent(fileName.GetFullPath());
return true;
}
// this function is called before the debugger startup
void LEditor::UpdateBreakpoints()
{
ManagerST::Get()->GetBreakpointsMgr()->DeleteAllBreakpointsByFileName(GetFileName().GetFullPath());
// iterate over the array and update the breakpoint manager with updated line numbers for each breakpoint
std::map<int, std::vector<BreakpointInfo> >::iterator iter = m_breakpointsInfo.begin();
for(; iter != m_breakpointsInfo.end(); iter++) {
int handle = iter->first;
int line = MarkerLineFromHandle(handle);
if(line >= 0) {
for(size_t i = 0; i < iter->second.size(); i++) {
iter->second.at(i).lineno = line + 1;
iter->second.at(i).origin = BO_Editor;
}
}
ManagerST::Get()->GetBreakpointsMgr()->SetBreakpoints(iter->second);
// update the Breakpoints pane too
clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
}
}
wxString LEditor::GetWordAtCaret()
{
// Get the partial word that we have
long pos = GetCurrentPos();
long start = WordStartPosition(pos, true);
long end = WordEndPosition(pos, true);
return GetTextRange(start, end);
}
//---------------------------------------------------------------------------
// Most of the functionality for this functionality
// is done in the Language & TagsManager objects, however,
// as you can see below, much work still needs to be done in the application
// layer (outside of the library) to provide the input arguments for
// the CodeParser library
//---------------------------------------------------------------------------
void LEditor::CompleteWord(bool onlyRefresh)
{
if(EventNotifier::Get()->IsEventsDiabled())
return;
// Let the plugins a chance to override the default behavior
clCodeCompletionEvent evt(wxEVT_CC_CODE_COMPLETE);
evt.SetPosition(GetCurrentPosition());
evt.SetEditor(this);
evt.SetInsideCommentOrString(m_context->IsCommentOrString(PositionBefore(GetCurrentPos())));
evt.SetEventObject(this);
if(EventNotifier::Get()->ProcessEvent(evt)) {
// the plugin handled the code-complete request
return;
} else {
CodeCompletionManager::Get().SetWordCompletionRefreshNeeded(onlyRefresh);
// let the built-in context do the job
m_context->CompleteWord();
}
}
//------------------------------------------------------------------
// AutoCompletion, by far the nicest feature of a modern IDE
// This function attempts to resolve the string to the left of
// the '.', '->' operator and to display a popup menu with
// list of possible matches
//------------------------------------------------------------------
void LEditor::CodeComplete()
{
if(EventNotifier::Get()->IsEventsDiabled())
return;
clCodeCompletionEvent evt(wxEVT_CC_CODE_COMPLETE);
evt.SetPosition(GetCurrentPosition());
evt.SetInsideCommentOrString(m_context->IsCommentOrString(PositionBefore(GetCurrentPos())));
evt.SetEventObject(this);
evt.SetEditor(this);
if(EventNotifier::Get()->ProcessEvent(evt))
// the plugin handled the code-complete request
return;
else {
// let the built-in context do the job
m_context->CodeComplete();
}
}
//----------------------------------------------------------------
// Demonstrate how to achieve symbol browsing using the CodeLite
// library, in addition we implements here a memory for allowing
// user to go back and forward
//----------------------------------------------------------------
void LEditor::GotoDefinition()
{
// Let the plugins process this first
wxString word = GetWordAtCaret();
clCodeCompletionEvent event(wxEVT_CC_FIND_SYMBOL, GetId());
event.SetEventObject(this);
event.SetEditor(this);
event.SetWord(word);
event.SetPosition(GetCurrentPosition());
event.SetInsideCommentOrString(m_context->IsCommentOrString(PositionBefore(GetCurrentPos())));
if(EventNotifier::Get()->ProcessEvent(event))
return;
m_context->GotoDefinition();
}
void LEditor::OnDwellStart(wxStyledTextEvent& event)
{
// First see if we're hovering over a breakpoint or build marker
// Assume anywhere to the left of the fold margin qualifies
int margin = 0;
wxPoint pt(ScreenToClient(wxGetMousePosition()));
wxRect clientRect = GetClientRect();
for(int n = 0; n < FOLD_MARGIN_ID; ++n) {
margin += GetMarginWidth(n);
}
if(IsContextMenuOn() || IsDragging() || !GetSTCFocus()) {
// Don't cover the context menu or a potential drop-point with a calltip!
// And, especially, try to avoid scintilla's party-piece: placing a permanent calltip on top of some innocent
// app!
} else if(event.GetX() > 0 // It seems that we can get spurious events with x == 0
&&
event.GetX() < margin) {
// We can't use event.GetPosition() here, as in the margin it returns -1
int position = PositionFromPoint(wxPoint(event.GetX(), event.GetY()));
int line = LineFromPosition(position);
wxString tooltip;
wxString fname = GetFileName().GetFullPath();
if(MarkerGet(line) & mmt_all_breakpoints) {
tooltip = ManagerST::Get()->GetBreakpointsMgr()->GetTooltip(fname, line + 1);
}
else if(MarkerGet(line) & mmt_all_bookmarks) {
tooltip = GetBookmarkTooltip(line);
}
// Compiler marker takes precedence over any other tooltip on that margin
if((MarkerGet(line) & mmt_compiler) && m_compilerMessagesMap.count(line)) {
// Get the compiler tooltip
tooltip = m_compilerMessagesMap.find(line)->second;
}
wxString tmpTip = tooltip;
tmpTip.Trim().Trim(false);
if(!tmpTip.IsEmpty()) {
DoShowCalltip(-1, tooltip);
}
} else if(ManagerST::Get()->DbgCanInteract() && clientRect.Contains(pt)) {
m_context->OnDbgDwellStart(event);
} else if(TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_DISP_TYPE_INFO) {
// Allow the plugins to override the default built-in behavior of displaying
// the type info tooltip
clCodeCompletionEvent evtTypeinfo(wxEVT_CC_TYPEINFO_TIP, GetId());
evtTypeinfo.SetEventObject(this);
evtTypeinfo.SetEditor(this);
evtTypeinfo.SetPosition(event.GetPosition());
evtTypeinfo.SetInsideCommentOrString(m_context->IsCommentOrString(event.GetPosition()));
if(EventNotifier::Get()->ProcessEvent(evtTypeinfo))
return;
m_context->OnDwellStart(event);
}
}
void LEditor::OnDwellEnd(wxStyledTextEvent& event)
{
// Allow the plugins to override the default built-in behavior of displaying
wxCommandEvent evtTypeinfo(wxEVT_CMD_EDITOR_TIP_DWELL_END, GetId());
evtTypeinfo.SetEventObject(this);
if(EventNotifier::Get()->ProcessEvent(evtTypeinfo))
return;
m_context->OnDwellEnd(event);
m_context->OnDbgDwellEnd(event);
}
void LEditor::OnCallTipClick(wxStyledTextEvent& event) { m_context->OnCallTipClick(event); }
void LEditor::OnMenuCommand(wxCommandEvent& event)
{
MenuEventHandlerPtr handler = MenuManager::Get()->GetHandler(event.GetId());
if(handler) {
handler->ProcessCommandEvent(this, event);
}
}
void LEditor::OnUpdateUI(wxUpdateUIEvent& event)
{
MenuEventHandlerPtr handler = MenuManager::Get()->GetHandler(event.GetId());
if(handler) {
handler->ProcessUpdateUIEvent(this, event);
}
}
//-----------------------------------------------------------------------
// Misc functions
//-----------------------------------------------------------------------
wxString LEditor::PreviousWord(int pos, int& foundPos)
{
// Get the partial word that we have
wxChar ch = 0;
long curpos = PositionBefore(pos);
if(curpos == 0) {
foundPos = wxNOT_FOUND;
return wxT("");
}
while(true) {
ch = GetCharAt(curpos);
if(ch == wxT('\t') || ch == wxT(' ') || ch == wxT('\r') || ch == wxT('\v') || ch == wxT('\n')) {
long tmpPos = curpos;
curpos = PositionBefore(curpos);
if(curpos == 0 && tmpPos == curpos)
break;
} else {
long start = WordStartPosition(curpos, true);
long end = WordEndPosition(curpos, true);
return GetTextRange(start, end);
}
}
foundPos = wxNOT_FOUND;
return wxT("");
}
wxChar LEditor::PreviousChar(const int& pos, int& foundPos, bool wantWhitespace)
{
wxChar ch = 0;
long curpos = PositionBefore(pos);
if(curpos == 0) {
foundPos = curpos;
return ch;
}
while(true) {
ch = GetCharAt(curpos);
if(ch == wxT('\t') || ch == wxT(' ') || ch == wxT('\r') || ch == wxT('\v') || ch == wxT('\n')) {
// if the caller is intrested in whitepsaces,
// simply return it
if(wantWhitespace) {
foundPos = curpos;
return ch;
}
long tmpPos = curpos;
curpos = PositionBefore(curpos);
if(curpos == 0 && tmpPos == curpos)
break;
} else {
foundPos = curpos;
return ch;
}
}
foundPos = -1;
return ch;
}
wxChar LEditor::NextChar(const int& pos, int& foundPos)
{
wxChar ch = 0;
long nextpos = pos;
while(true) {
if(nextpos >= GetLength())
break;
ch = GetCharAt(nextpos);
if(ch == wxT('\t') || ch == wxT(' ') || ch == wxT('\r') || ch == wxT('\v') || ch == wxT('\n')) {
nextpos = PositionAfter(nextpos);
continue;
} else {
foundPos = nextpos;
return ch;
}
}
foundPos = -1;
return ch;
}
int LEditor::FindString(const wxString& str, int flags, const bool down, long pos)
{
// initialize direction
if(down) {
SetTargetStart(pos);
SetTargetEnd(GetLength());
} else {
SetTargetStart(pos);
SetTargetEnd(0);
}
SetSearchFlags(flags);
// search string
int _pos = SearchInTarget(str);
if(_pos >= 0)
return _pos;
else
return -1;
}
bool LEditor::MatchBraceBack(const wxChar& chCloseBrace, const long& pos, long& matchedPos)
{
if(pos <= 0)
return false;
wxChar chOpenBrace;
switch(chCloseBrace) {
case '}':
chOpenBrace = '{';
break;
case ')':
chOpenBrace = '(';
break;
case ']':
chOpenBrace = '[';
break;
case '>':
chOpenBrace = '<';
break;
default:
return false;
}
long nPrevPos = pos;
wxChar ch;
int depth = 1;
// We go backward
while(true) {
if(nPrevPos == 0)
break;
nPrevPos = PositionBefore(nPrevPos);
// Make sure we are not in a comment
if(m_context->IsCommentOrString(nPrevPos))
continue;
ch = GetCharAt(nPrevPos);
if(ch == chOpenBrace) {
// Dec the depth level
depth--;
if(depth == 0) {
matchedPos = nPrevPos;
return true;
}
} else if(ch == chCloseBrace) {
// Inc depth level
depth++;
}
}
return false;
}
void LEditor::RecalcHorizontalScrollbar()
{
if(m_autoAdjustHScrollbarWidth) {
// recalculate and set the length of horizontal scrollbar
int maxPixel = 0;
int startLine = GetFirstVisibleLine();
int endLine = startLine + LinesOnScreen();
if(endLine >= (GetLineCount() - 1))
endLine--;
for(int i = startLine; i <= endLine; i++) {
int visibleLine = (int)DocLineFromVisible(i); // get actual visible line, folding may offset lines
int endPosition = GetLineEndPosition(visibleLine); // get character position from begin
int beginPosition = PositionFromLine(visibleLine); // and end of line
wxPoint beginPos = PointFromPosition(beginPosition);
wxPoint endPos = PointFromPosition(endPosition);
int curLen = endPos.x - beginPos.x;
if(maxPixel < curLen) // If its the largest line yet
maxPixel = curLen;
}
if(maxPixel == 0)
maxPixel++; // make sure maxPixel is valid
int currentLength = GetScrollWidth(); // Get current scrollbar size
if(currentLength != maxPixel) {
// And if it is not the same, update it
SetScrollWidth(maxPixel);
}
}
}
//--------------------------------------------------------
// Brace match
//--------------------------------------------------------
bool LEditor::IsCloseBrace(int position)
{
return GetCharAt(position) == '}' || GetCharAt(position) == ']' || GetCharAt(position) == ')';
}
bool LEditor::IsOpenBrace(int position)
{
return GetCharAt(position) == '{' || GetCharAt(position) == '[' || GetCharAt(position) == '(';
}
void LEditor::MatchBraceAndSelect(bool selRegion)
{
// Get current position
long pos = GetCurrentPos();
if(IsOpenBrace(pos) && !m_context->IsCommentOrString(pos)) {
BraceMatch(selRegion);
return;
}
if(IsOpenBrace(PositionBefore(pos)) && !m_context->IsCommentOrString(PositionBefore(pos))) {
SetCurrentPos(PositionBefore(pos));
BraceMatch(selRegion);
return;
}
if(IsCloseBrace(pos) && !m_context->IsCommentOrString(pos)) {
BraceMatch(selRegion);
return;
}
if(IsCloseBrace(PositionBefore(pos)) && !m_context->IsCommentOrString(PositionBefore(pos))) {
SetCurrentPos(PositionBefore(pos));
BraceMatch(selRegion);
return;
}
}
void LEditor::BraceMatch(long pos)
{
// Check if we have a match
int indentCol = 0;
long endPos = wxStyledTextCtrl::BraceMatch(pos);
if(endPos != wxSTC_INVALID_POSITION) {
wxStyledTextCtrl::BraceHighlight(pos, endPos);
if(GetIndentationGuides() != 0 && GetIndent() > 0) {
// Highlight indent guide if exist
indentCol =
std::min(GetLineIndentation(LineFromPosition(pos)), GetLineIndentation(LineFromPosition(endPos)));
indentCol /= GetIndent();
indentCol *= GetIndent(); // round down to nearest indentation guide column
SetHighlightGuide(GetLineIndentation(LineFromPosition(pos)));
}
} else {
wxStyledTextCtrl::BraceBadLight(pos);
}
SetHighlightGuide(indentCol);
}
void LEditor::BraceMatch(const bool& bSelRegion)
{
// Check if we have a match
long endPos = wxStyledTextCtrl::BraceMatch(GetCurrentPos());
if(endPos != wxSTC_INVALID_POSITION) {
// Highlight indent guide if exist
long startPos = GetCurrentPos();
if(bSelRegion) {
// Select the range
if(endPos > startPos) {
SetSelectionEnd(PositionAfter(endPos));
SetSelectionStart(startPos);
} else {
SetSelectionEnd(PositionAfter(startPos));
SetSelectionStart(endPos);
}
} else {
SetSelectionEnd(endPos);
SetSelectionStart(endPos);
SetCurrentPos(endPos);
}
EnsureCaretVisible();
}
}
void LEditor::SetActive()
{
// ensure that the top level window parent of this editor is 'Raised'
DoUpdateTLWTitle(true);
// if the find and replace dialog is opened, set ourself
// as the event owners
if(m_findReplaceDlg) {
m_findReplaceDlg->SetEventOwner(GetEventHandler());
}
SetFocus();
SetSTCFocus(true);
m_context->SetActive();
wxStyledTextEvent dummy;
OnSciUpdateUI(dummy);
}
// Popup a Find/Replace dialog
/**
* \brief
* \param isReplaceDlg
*/
void LEditor::DoFindAndReplace(bool isReplaceDlg)
{
if(m_findReplaceDlg == NULL) {
// Create the dialog
m_findReplaceDlg = new FindReplaceDialog(clMainFrame::Get(), m_findReplaceData);
m_findReplaceDlg->SetEventOwner(this->GetEventHandler());
}
if(m_findReplaceDlg->IsShown()) {
// make sure that dialog has focus and that this instace
// of LEditor is the owner for the events
m_findReplaceDlg->SetEventOwner(this->GetEventHandler());
m_findReplaceDlg->SetFocus();
return;
}
// the search always starts from the current line
// if there is a selection, set it
if(GetSelectedText().IsEmpty() == false) {
// if this string does not exist in the array add it
wxString Selection(GetSelectedText());
if(isReplaceDlg) {
if(!Selection.Contains(wxT("\n"))) {
// Don't try to use a multiline selection as the 'find' token. It looks ugly and
// it won't be what the user wants (it'll be the 'Replace in Selection' selection)
m_findReplaceDlg->GetData().SetFindString(GetSelectedText());
} else {
m_findReplaceDlg->GetData().SetFlags(m_findReplaceDlg->GetData().GetFlags() | wxFRD_SELECTIONONLY);
}
} else {
// always set the find string in 'Find' dialog
m_findReplaceDlg->GetData().SetFindString(GetSelectedText());
}
}
if(isReplaceDlg) { // Zeroise
m_findReplaceDlg->ResetReplacedCount();
m_findReplaceDlg->SetReplacementsMessage(frd_dontshowzeros);
}
m_findReplaceDlg->Show(isReplaceDlg ? REPLACE_DLG : FIND_DLG);
}
void LEditor::OnFindDialog(wxCommandEvent& event)
{
wxEventType type = event.GetEventType();
bool dirDown = !(m_findReplaceDlg->GetData().GetFlags() & wxFRD_SEARCHUP ? true : false);
if(type == wxEVT_FRD_FIND_NEXT) {
FindNext(m_findReplaceDlg->GetData());
} else if(type == wxEVT_FRD_REPLACE) {
// Perform a "Replace" operation
if(!Replace()) {
int saved_pos = GetCurrentPos();
// place the caret at the new position
if(dirDown) {
SetCaretAt(0);
} else {
SetCaretAt(GetLength());
}
// replace again
if(!Replace()) {
// restore the caret
SetCaretAt(saved_pos);
// popup a message
wxMessageBox(_("Can not find the string '") + m_findReplaceDlg->GetData().GetFindString() + wxT("'"),
_("CodeLite"),
wxICON_WARNING | wxOK);
}
}
} else if(type == wxEVT_FRD_REPLACEALL) {
ReplaceAll();
} else if(type == wxEVT_FRD_BOOKMARKALL) {
SetFindBookmarksActive(true);
MarkAllFinds();
} else if(type == wxEVT_FRD_CLEARBOOKMARKS) {
DelAllMarkers(smt_find_bookmark);
SetFindBookmarksActive(false);
clMainFrame::Get()->SelectBestEnvSet();
}
}
void LEditor::FindNext(const FindReplaceData& data)
{
bool dirDown = !(data.GetFlags() & wxFRD_SEARCHUP ? true : false);
if(!FindAndSelect(data)) {
int saved_pos = GetCurrentPos();
if(dirDown) {
DoSetCaretAt(0);
} else {
DoSetCaretAt(GetLength());
}
if(!FindAndSelect(data)) {
// restore the caret
DoSetCaretAt(saved_pos);
// Kill the "...continued from start" statusbar message
clMainFrame::Get()->SetStatusMessage(wxEmptyString, 0);
wxMessageBox(
_("Can not find the string '") + data.GetFindString() + wxT("'"), _("CodeLite"), wxOK | wxICON_WARNING);
}
} else {
// The string *was* found, without needing to restart from the top
// So cancel any previous statusbar restart message
clMainFrame::Get()->SetStatusMessage(wxEmptyString, 0);
}
}
bool LEditor::Replace() { return Replace(m_findReplaceDlg->GetData()); }
bool LEditor::FindAndSelect() { return FindAndSelect(m_findReplaceDlg->GetData()); }
bool LEditor::FindAndSelect(const FindReplaceData& data)
{
wxString findWhat = data.GetFindString();
size_t flags = SearchFlags(data);
int offset = GetCurrentPos();
int dummy, dummy_len(0), dummy_c, dummy_len_c(0);
if(GetSelectedText().IsEmpty() == false) {
if(flags & wxSD_SEARCH_BACKWARD) {
// searching up
if(StringFindReplacer::Search(GetSelectedText().wc_str(),
GetSelectedText().Len(),
findWhat.wc_str(),
flags,
dummy,
dummy_len,
dummy_c,
dummy_len_c) &&
dummy_len_c == (int)GetSelectedText().Len()) {
// place the caret at the start of the selection so the search will skip this selected text
int sel_start = GetSelectionStart();
int sel_end = GetSelectionEnd();
sel_end > sel_start ? offset = sel_start : offset = sel_end;
}
} else {
// searching down
if(StringFindReplacer::Search(
GetSelectedText().wc_str(), 0, findWhat.wc_str(), flags, dummy, dummy_len, dummy_c, dummy_len_c) &&
dummy_len_c == (int)GetSelectedText().Len()) {
// place the caret at the end of the selection so the search will skip this selected text
int sel_start = GetSelectionStart();
int sel_end = GetSelectionEnd();
sel_end > sel_start ? offset = sel_end : offset = sel_start;
}
}
}
int pos(0);
int match_len(0);
if(StringFindReplacer::Search(GetText().wc_str(), offset, findWhat.wc_str(), flags, pos, match_len)) {
SetEnsureCaretIsVisible(pos);
if(flags & wxSD_SEARCH_BACKWARD) {
SetSelection(pos + match_len, pos);
} else {
SetSelection(pos, pos + match_len);
}
return true;
}
return false;
}
bool LEditor::FindAndSelect(const wxString& _pattern, const wxString& name)
{
return DoFindAndSelect(_pattern, name, 0, NavMgr::Get());
}
void LEditor::FindAndSelectV(const wxString& _pattern,
const wxString& name,
int pos /*=0*/,
NavMgr* WXUNUSED(unused)) // Similar but returns void, so can be async
{
// Use CallAfter() here. With wxGTK-3.1 (perhaps due to its scintilla update) if the file wasn't already loaded,
// EnsureVisible() is called too early and fails
wxArrayString strings; // CallAfter can only cope with 2 parameters, so combine the wxStrings
strings.Add(_pattern);
strings.Add(name);
CallAfter(&LEditor::DoFindAndSelectV, strings, pos);
}
void LEditor::DoFindAndSelectV(const wxArrayString& strings, int pos) // Called with CallAfter()
{
wxCHECK_RET(strings.Count() == 2, "Unexpected number of wxStrings supplied");
wxString _pattern(strings.Item(0));
wxString name(strings.Item(1));
DoFindAndSelect(_pattern, name, pos, NavMgr::Get());
}
bool LEditor::Replace(const FindReplaceData& data)
{
// the string to be replaced should be selected
if(GetSelectedText().IsEmpty() == false) {
int pos(0);
int match_len(0);
size_t flags = SearchFlags(data);
if(StringFindReplacer::Search(
GetSelectedText().wc_str(), 0, data.GetFindString().wc_str(), flags, pos, match_len)) {
ReplaceSelection(data.GetReplaceString());
m_findReplaceDlg->IncReplacedCount();
m_findReplaceDlg->SetReplacementsMessage();
}
}
// and find another match in the document
return FindAndSelect();
}
size_t LEditor::SearchFlags(const FindReplaceData& data)
{
size_t flags = 0;
size_t wxflags = data.GetFlags();
wxflags& wxFRD_MATCHWHOLEWORD ? flags |= wxSD_MATCHWHOLEWORD : flags = flags;
wxflags& wxFRD_MATCHCASE ? flags |= wxSD_MATCHCASE : flags = flags;
wxflags& wxFRD_REGULAREXPRESSION ? flags |= wxSD_REGULAREXPRESSION : flags = flags;
wxflags& wxFRD_SEARCHUP ? flags |= wxSD_SEARCH_BACKWARD : flags = flags;
return flags;
}
//----------------------------------------------
// Folds
//----------------------------------------------
void LEditor::ToggleCurrentFold()
{
int line = GetCurrentLine();
if(line >= 0) {
ToggleFold(line);
if(GetLineVisible(line) == false) {
// the caret line is hidden, make sure the caret is visible
while(line >= 0) {
if((GetFoldLevel(line) & wxSTC_FOLDLEVELHEADERFLAG) && GetLineVisible(line)) {
SetCaretAt(PositionFromLine(line));
break;
}
line--;
}
}
}
}
void LEditor::DoRecursivelyExpandFolds(bool expand, int startline, int endline)
{
for(int line = startline; line < endline; ++line) {
if(GetFoldLevel(line) & wxSTC_FOLDLEVELHEADERFLAG) {
int BottomOfFold = GetLastChild(line, -1);
if(expand) {
// Expand this fold
SetFoldExpanded(line, true);
ShowLines(line + 1, BottomOfFold);
// Recursively do any contained child folds
DoRecursivelyExpandFolds(expand, line + 1, BottomOfFold);
} else {
DoRecursivelyExpandFolds(expand, line + 1, BottomOfFold);
// Hide this fold
SetFoldExpanded(line, false);
HideLines(line + 1, BottomOfFold);
}
line = BottomOfFold; // Now skip over the fold we've just dealt with, ready for any later siblings
}
}
}
void LEditor::ToggleAllFoldsInSelection()
{
int selStart = GetSelectionStart();
int selEnd = GetSelectionEnd();
if(selStart == selEnd) {
return; // No selection. UpdateUI prevents this from the menu, but not from an accelerator
}
int startline = LineFromPos(selStart);
int endline = LineFromPos(selEnd);
if(startline == endline) {
ToggleFold(startline); // For a single-line selection just toggle
return;
}
if(startline > endline) {
wxSwap(startline, endline);
}
// First see if there are any folded lines in the selection. If there are, we'll be in 'unfold' mode
bool expanding(false);
for(int line = startline; line < endline;
++line) { // not <=. If only the last line of the sel is folded it's unlikely that the user meant it
if(!GetLineVisible(line)) {
expanding = true;
break;
}
}
for(int line = startline; line < endline; ++line) {
if(!(GetFoldLevel(line) & wxSTC_FOLDLEVELHEADERFLAG)) {
continue;
}
int BottomOfFold = GetLastChild(line, -1);
if(BottomOfFold > (endline + 1)) { // GetLastChild() seems to be 1-based, not zero-based. Without the +1, a } at
// endline will be considered outside the selection
continue; // This fold continues past the end of the selection
}
DoRecursivelyExpandFolds(expanding, line, BottomOfFold);
line = BottomOfFold;
}
if(!expanding) {
// The caret will (surely) be inside the selection, and unless it was on the first line or an unfolded one,
// it'll now be hidden
// If so place it at the top, which will be visible. Unfortunately SetCaretAt() destroys the selection,
// and I can't find a way to preserve/reinstate it while still setting the caret. DoEnsureCaretIsVisible() also
// fails :(
int caretline = LineFromPos(GetCurrentPos());
if(!GetLineVisible(caretline)) {
SetCaretAt(selStart);
}
}
}
// If the cursor is on/in/below an open fold, collapse all. Otherwise expand all
void LEditor::FoldAll()
{
// Colourise(0,-1); SciTE did this here, but it doesn't seem to accomplish anything
// First find the current fold-point, and ask it whether or not it's folded
int lineSeek = GetCurrentLine();
while(true) {
if(GetFoldLevel(lineSeek) & wxSTC_FOLDLEVELHEADERFLAG)
break;
int parentline = GetFoldParent(lineSeek); // See if we're inside a fold area
if(parentline >= 0) {
lineSeek = parentline;
break;
} else
lineSeek--; // Must have been between folds
if(lineSeek < 0)
return;
}
bool expanded = GetFoldExpanded(lineSeek);
int maxLine = GetLineCount();
// Some files, especially headers with #ifndef FOO_H, will collapse into one big fold
// So, if we're collapsing, skip any all-encompassing top level fold
bool SkipTopFold = false;
if(expanded) {
int topline = 0;
while(!(GetFoldLevel(topline) & wxSTC_FOLDLEVELHEADERFLAG)) {
// This line wasn't a fold-point, so inc until we find one
if(++topline >= maxLine)
return;
}
int BottomOfFold = GetLastChild(topline, -1);
if(BottomOfFold >= maxLine || BottomOfFold == -1)
return;
// We've found the bottom of the topmost fold-point. See if there's another fold below it
++BottomOfFold;
while(!(GetFoldLevel(BottomOfFold) & wxSTC_FOLDLEVELHEADERFLAG)) {
if(++BottomOfFold >= maxLine) {
// If we're here, the top fold must encompass the whole file, so set the flag
SkipTopFold = true;
break;
}
}
}
// Now go through the whole document, toggling folds that match the original one's level if we're collapsing
// or all collapsed folds if we're expanding (so that internal folds get expanded too).
// The (level & wxSTC_FOLDLEVELHEADERFLAG) means "If this level is a Fold start"
// (level & wxSTC_FOLDLEVELNUMBERMASK) returns a value for the 'indent' of the fold.
// This starts at wxSTC_FOLDLEVELBASE==1024. A sub fold-point == 1025, a subsub 1026...
for(int line = 0; line < maxLine; line++) {
int level = GetFoldLevel(line);
// If we're skipping an all-encompassing fold, we use wxSTC_FOLDLEVELBASE+1
if((level & wxSTC_FOLDLEVELHEADERFLAG) &&
(expanded ? ((level & wxSTC_FOLDLEVELNUMBERMASK) == (wxSTC_FOLDLEVELBASE + SkipTopFold)) :
((level & wxSTC_FOLDLEVELNUMBERMASK) >= wxSTC_FOLDLEVELBASE))) {
if(GetFoldExpanded(line) == expanded)
ToggleFold(line);
}
}
// make sure the caret is visible. If it was hidden, place it at the first visible line
int curpos = GetCurrentPos();
if(curpos != wxNOT_FOUND) {
int curline = LineFromPosition(curpos);
if(curline != wxNOT_FOUND && GetLineVisible(curline) == false) {
// the caret line is hidden, make sure the caret is visible
while(curline >= 0) {
if((GetFoldLevel(curline) & wxSTC_FOLDLEVELHEADERFLAG) && GetLineVisible(curline)) {
SetCaretAt(PositionFromLine(curline));
break;
}
curline--;
}
}
}
}
// Toggle all the highest-level folds in the selection i.e. if the selection contains folds of level 3, 4 and 5, toggle
// all the level 3 ones
void LEditor::ToggleTopmostFoldsInSelection()
{
int selStart = GetSelectionStart();
int selEnd = GetSelectionEnd();
if(selStart == selEnd) {
return; // No selection. UpdateUI prevents this from the menu, but not from an accelerator
}
int startline = LineFromPos(selStart);
int endline = LineFromPos(selEnd);
if(startline == endline) {
ToggleFold(startline); // For a single-line selection just toggle
return;
}
if(startline > endline) {
wxSwap(startline, endline);
}
// Go thru the selection to find the topmost contained fold level. Also ask the first one of this level if it's
// folded
int toplevel(wxSTC_FOLDLEVELNUMBERMASK);
bool expanded(true);
for(int line = startline; line < endline;
++line) { // not <=. If only the last line of the sel is folded it's unlikely that the user meant it
if(!GetLineVisible(line)) {
break;
}
if(GetFoldLevel(line) & wxSTC_FOLDLEVELHEADERFLAG) {
int level = GetFoldLevel(line) & wxSTC_FOLDLEVELNUMBERMASK;
if(level < toplevel) {
toplevel = level;
expanded = GetFoldExpanded(line);
}
}
}
if(toplevel == wxSTC_FOLDLEVELNUMBERMASK) { // No fold found
return;
}
for(int line = startline; line < endline; ++line) {
if(GetFoldLevel(line) & wxSTC_FOLDLEVELHEADERFLAG) {
if((GetFoldLevel(line) & wxSTC_FOLDLEVELNUMBERMASK) == toplevel && GetFoldExpanded(line) == expanded) {
ToggleFold(line);
}
}
}
// make sure the caret is visible. If it was hidden, place it at the first visible line
int curpos = GetCurrentPos();
if(expanded && curpos != wxNOT_FOUND) {
int curline = LineFromPosition(curpos);
if(curline != wxNOT_FOUND && GetLineVisible(curline) == false) {
// the caret line is hidden, make sure the caret is visible
while(curline >= 0) {
if((GetFoldLevel(curline) & wxSTC_FOLDLEVELHEADERFLAG) && GetLineVisible(curline)) {
SetCaretAt(PositionFromLine(curline));
break;
}
curline--;
}
}
}
}
void LEditor::StoreCollapsedFoldsToArray(std::vector<int>& folds) const
{
for(int line = 0; line < GetLineCount(); ++line) {
if((GetFoldLevel(line) & wxSTC_FOLDLEVELHEADERFLAG) && (GetFoldExpanded(line) == false)) {
folds.push_back(line);
}
}
}
void LEditor::LoadCollapsedFoldsFromArray(const std::vector<int>& folds)
{
for(size_t i = 0; i < folds.size(); ++i) {
int line = folds.at(i);
// 'line' was collapsed when serialised, so collapse it now. That assumes that the line-numbers haven't changed
// in the meanwhile.
// If we cared enough, we could have saved a fold-level too, and/or the function name +/- the line's
// displacement within the function. But for now...
if(GetFoldLevel(line) & wxSTC_FOLDLEVELHEADERFLAG) {
ToggleFold(line);
}
}
}
//----------------------------------------------
// Bookmarks
//----------------------------------------------
void LEditor::AddMarker()
{
int nPos = GetCurrentPos();
int nLine = LineFromPosition(nPos);
MarkerAdd(nLine, GetActiveBookmarkType());
}
void LEditor::DelMarker()
{
int nPos = GetCurrentPos();
int nLine = LineFromPosition(nPos);
MarkerDelete(nLine, GetActiveBookmarkType());
}
void LEditor::ToggleMarker()
{
// Add/Remove marker
if(!LineIsMarked(GetActiveBookmarkMask()))
AddMarker();
else
DelMarker();
}
bool LEditor::LineIsMarked(enum marker_mask_type mask)
{
int nPos = GetCurrentPos();
int nLine = LineFromPosition(nPos);
int nBits = MarkerGet(nLine);
// 'mask' is a bitmap representing a bookmark, or a type of breakpt, or...
return (nBits & mask ? true : false);
}
void LEditor::StoreMarkersToArray(wxArrayString& bookmarks)
{
for(int line = 0; (line = MarkerNext(line, mmt_all_bookmarks)) >= 0; ++line) {
for(int type = smt_FIRST_BMK_TYPE; type <= smt_LAST_BMK_TYPE; ++type) {
int mask = (1 << type);
if(MarkerGet(line) & mask) {
// We need to serialise both the line and BM type. To keep things simple in sessionmanager, just merge
// their strings
bookmarks.Add(wxString::Format("%d:%d", line, type));
}
}
}
}
void LEditor::LoadMarkersFromArray(const wxArrayString& bookmarks)
{
for(size_t i = 0; i < bookmarks.GetCount(); i++) {
// Unless this is an old file, each bookmark will have been stored in the form: "linenumber:type"
wxString lineno = bookmarks.Item(i).BeforeFirst(':');
long bmt = smt_bookmark1;
wxString type = bookmarks.Item(i).AfterFirst(':');
if(!type.empty()) {
type.ToLong(&bmt);
}
long line = 0;
if(lineno.ToLong(&line)) {
MarkerAdd(line, bmt);
}
}
}
void LEditor::DelAllMarkers(int which_type)
{
// Delete all relevant markers from the view
// If 0, delete just the currently active type, -1 delete them all.
// Otherwise just the specified type, which will usually be the 'find' bookmark
if(which_type > 0) {
MarkerDeleteAll(which_type);
} else if(which_type == 0) {
MarkerDeleteAll(GetActiveBookmarkType());
} else {
for(size_t bmt = smt_FIRST_BMK_TYPE; bmt <= smt_LAST_BMK_TYPE; ++bmt) {
MarkerDeleteAll(bmt);
}
}
// delete other markers as well
SetIndicatorCurrent(1);
IndicatorClearRange(0, GetLength());
SetIndicatorCurrent(MARKER_WORD_HIGHLIGHT);
IndicatorClearRange(0, GetLength());
SetIndicatorCurrent(HYPERLINK_INDICATOR);
IndicatorClearRange(0, GetLength());
SetIndicatorCurrent(DEBUGGER_INDICATOR);
IndicatorClearRange(0, GetLength());
}
bool LEditor::HasCompilerMarkers()
{
// try to locate *any* compiler marker
int mask = mmt_compiler;
int nFoundLine = MarkerNext(0, mask);
return nFoundLine >= 0;
}
void LEditor::FindNextMarker()
{
int nPos = GetCurrentPos();
int nLine = LineFromPosition(nPos);
int nFoundLine = MarkerNext(nLine + 1, GetActiveBookmarkMask());
if(nFoundLine >= 0) {
// mark this place before jumping to next marker
GotoLine(nFoundLine);
} else {
// We reached the last marker, try again from top
nLine = LineFromPosition(0);
nFoundLine = MarkerNext(nLine, GetActiveBookmarkMask());
if(nFoundLine >= 0) {
GotoLine(nFoundLine);
}
}
if(nFoundLine >= 0) {
EnsureVisible(nFoundLine);
EnsureCaretVisible();
}
}
void LEditor::FindPrevMarker()
{
int nPos = GetCurrentPos();
int nLine = LineFromPosition(nPos);
int mask = GetActiveBookmarkMask();
int nFoundLine = MarkerPrevious(nLine - 1, mask);
if(nFoundLine >= 0) {
GotoLine(nFoundLine);
} else {
// We reached first marker, try again from button
int nFileSize = GetLength();
nLine = LineFromPosition(nFileSize);
nFoundLine = MarkerPrevious(nLine, mask);
if(nFoundLine >= 0) {
GotoLine(nFoundLine);
}
}
if(nFoundLine >= 0) {
EnsureVisible(nFoundLine);
EnsureCaretVisible();
}
}
bool LEditor::ReplaceAll()
{
int offset(0);
wxString findWhat = m_findReplaceDlg->GetData().GetFindString();
wxString replaceWith = m_findReplaceDlg->GetData().GetReplaceString();
size_t flags = SearchFlags(m_findReplaceDlg->GetData());
int pos(0);
int match_len(0);
int posInChars(0);
int match_lenInChars(0);
wxString txt;
if(m_findReplaceDlg->GetData().GetFlags() & wxFRD_SELECTIONONLY) {
txt = GetSelectedText();
} else {
txt = GetText();
}
bool replaceInSelectionOnly = m_findReplaceDlg->GetData().GetFlags() & wxFRD_SELECTIONONLY;
BeginUndoAction();
m_findReplaceDlg->ResetReplacedCount();
long savedPos = GetCurrentPos();
while(StringFindReplacer::Search(
txt.wc_str(), offset, findWhat.wc_str(), flags, pos, match_len, posInChars, match_lenInChars)) {
// Manipulate the buffer
txt.Remove(posInChars, match_lenInChars);
txt.insert(posInChars, replaceWith);
// When not in 'selection only' update the editor buffer as well
if(!replaceInSelectionOnly) {
SetSelectionStart(pos);
SetSelectionEnd(pos + match_len);
ReplaceSelection(replaceWith);
}
m_findReplaceDlg->IncReplacedCount();
offset = pos + clUTF8Length(replaceWith.wc_str(), replaceWith.length()); // match_len;
}
if(replaceInSelectionOnly) {
// Prepare the next selection
int selStart = GetSelectionStart();
int selEnd = selStart + txt.Len();
// replace the selection
ReplaceSelection(txt);
// Keep the selection
SetSelectionStart(selStart);
SetSelectionEnd(selEnd);
// place the caret at the end of the selection
EnsureCaretVisible();
} else {
// The editor buffer was already updated
// Restore the caret
SetCaretAt(savedPos);
}
EndUndoAction();
m_findReplaceDlg->SetReplacementsMessage();
return m_findReplaceDlg->GetReplacedCount() > 0;
}
bool LEditor::MarkAllFinds()
{
wxString findWhat = m_findReplaceDlg->GetData().GetFindString();
if(findWhat.IsEmpty()) {
return false;
}
// Save the caret position
long savedPos = GetCurrentPos();
size_t flags = SearchFlags(m_findReplaceDlg->GetData());
int pos(0);
int match_len(0);
// remove reverse search
flags &= ~wxSD_SEARCH_BACKWARD;
int offset(0);
wxString txt;
int fixed_offset(0);
if(m_findReplaceDlg->GetData().GetFlags() & wxFRD_SELECTIONONLY) {
txt = GetSelectedText();
fixed_offset = GetSelectionStart();
} else {
txt = GetText();
}
DelAllMarkers(smt_find_bookmark);
// set the active indicator to be 1
SetIndicatorCurrent(1);
while(StringFindReplacer::Search(txt.wc_str(), offset, findWhat.wc_str(), flags, pos, match_len)) {
MarkerAdd(LineFromPosition(fixed_offset + pos), smt_find_bookmark);
// add indicator as well
IndicatorFillRange(fixed_offset + pos, match_len);
offset = pos + match_len;
}
// Restore the caret
SetCurrentPos(savedPos);
EnsureCaretVisible();
clMainFrame::Get()->SelectBestEnvSet(); // Updates the statusbar display
return true;
}
int LEditor::GetActiveBookmarkType() const
{
if(IsFindBookmarksActive()) {
return smt_find_bookmark;
} else {
return BookmarkManager::Get().GetActiveBookmarkType();
}
}
enum marker_mask_type LEditor::GetActiveBookmarkMask() const
{
wxASSERT(1 << smt_find_bookmark == mmt_find_bookmark);
if(IsFindBookmarksActive()) {
return mmt_find_bookmark;
} else {
return (marker_mask_type)(1 << BookmarkManager::Get().GetActiveBookmarkType());
}
}
wxString LEditor::GetBookmarkLabel(sci_marker_types type)
{
wxCHECK_MSG(type >= smt_FIRST_BMK_TYPE && type <= smt_LAST_BMK_TYPE, "", "Invalid marker type");
wxString label = BookmarkManager::Get().GetMarkerLabel(type);
if(label.empty()) {
label = wxString::Format("Type %i", type - smt_FIRST_BMK_TYPE + 1);
}
return label;
}
void LEditor::OnChangeActiveBookmarkType(wxCommandEvent& event)
{
int requested = event.GetId() - XRCID("BookmarkTypes[start]");
BookmarkManager::Get().SetActiveBookmarkType(requested + smt_FIRST_BMK_TYPE - 1);
if((requested + smt_FIRST_BMK_TYPE - 1) != smt_find_bookmark) {
SetFindBookmarksActive(false);
}
clMainFrame::Get()->SelectBestEnvSet(); // Updates the statusbar display
}
wxString LEditor::GetBookmarkTooltip(const int lineno)
{
wxString active, others;
// If we've arrived here we know there's a bookmark on the line; however we don't know which type(s)
// If multiple, list each, with the visible one first
int linebits = MarkerGet(lineno);
if(linebits & GetActiveBookmarkMask()) {
wxString label = GetBookmarkLabel((sci_marker_types)GetActiveBookmarkType());
wxString suffix = label.Lower().Contains("bookmark") ? "" : " bookmark";
active = "<b>" + label + suffix + "</b>";
}
for(int bmt = smt_FIRST_BMK_TYPE; bmt <= smt_LAST_BMK_TYPE; ++bmt) {
if(bmt != GetActiveBookmarkType()) {
if(linebits & (1 << bmt)) {
if(!others.empty()) {
others << "\n";
}
wxString label = GetBookmarkLabel((sci_marker_types)bmt);
wxString suffix = label.Lower().Contains("bookmark") ? "" : " bookmark";
others << label << suffix << "";
}
}
}
if(!active.empty() && !others.empty()) {
active << "\n<hr>";
}
return active + others;
}
void LEditor::ReloadFile()
{
wxWindowUpdateLocker locker(this);
SetReloadingFile(true);
HideCompletionBox();
DoCancelCalltip();
if(m_fileName.GetFullPath().IsEmpty() == true || !m_fileName.FileExists()) {
SetEOLMode(GetEOLByOS());
SetReloadingFile(false);
return;
}
// Store a 'template' of the current file, so that it can be reapplied after
wxArrayString bookmarks;
StoreMarkersToArray(bookmarks);
std::vector<int> folds;
StoreCollapsedFoldsToArray(folds);
int lineNumber = GetCurrentLine();
clMainFrame::Get()->SetStatusMessage(_("Loading file..."), 0);
wxString text;
// Read the file we currently support:
// BOM, Auto-Detect encoding & User defined encoding
m_fileBom.Clear();
ReadFileWithConversion(m_fileName.GetFullPath(), text, GetOptions()->GetFileFontEncoding(), &m_fileBom);
SetText(text);
m_modifyTime = GetFileLastModifiedTime();
SetSavePoint();
EmptyUndoBuffer();
GetCommandsProcessor().Reset();
// remove breakpoints belongs to this file
DelAllBreakpointMarkers();
UpdateColours();
SetEOL();
int doclen = GetLength();
int lastLine = LineFromPosition(doclen);
lineNumber > lastLine ? lineNumber = lastLine : lineNumber;
SetEnsureCaretIsVisible(PositionFromLine(lineNumber));
// mark read only files
clMainFrame::Get()->GetMainBook()->MarkEditorReadOnly(this, IsFileReadOnly(GetFileName()));
SetReloadingFile(false);
// Now restore as far as possible the look'n'feel of the file
ManagerST::Get()->GetBreakpointsMgr()->RefreshBreakpointsForEditor(this);
LoadMarkersFromArray(bookmarks);
LoadCollapsedFoldsFromArray(folds);
clMainFrame::Get()->SetStatusMessage(_("Ready"), 0);
}
void LEditor::SetEditorText(const wxString& text)
{
wxWindowUpdateLocker locker(this);
HideCompletionBox();
SetText(text);
// remove breakpoints belongs to this file
DelAllBreakpointMarkers();
}
void LEditor::Create(const wxString& project, const wxFileName& fileName)
{
// set the file name
SetFileName(fileName);
// set the project name
SetProject(project);
// let the editor choose the syntax highlight to use according to file extension
// and set the editor properties to default
SetSyntaxHighlight(false); // Dont call 'UpdateColors' it is called in 'ReloadFile'
// reload the file from disk
ReloadFile();
}
void LEditor::InsertTextWithIndentation(const wxString& text, int lineno)
{
wxString textTag = FormatTextKeepIndent(text, PositionFromLine(lineno));
InsertText(PositionFromLine(lineno), textTag);
}
wxString LEditor::FormatTextKeepIndent(const wxString& text, int pos, size_t flags)
{
// keep the page idnetation level
wxString textToInsert(text);
wxString indentBlock;
int indentSize = 0;
int indent = 0;
if(flags & Format_Text_Indent_Prev_Line) {
indentSize = GetIndent();
int foldLevel = (GetFoldLevel(LineFromPosition(pos)) & wxSTC_FOLDLEVELNUMBERMASK) - wxSTC_FOLDLEVELBASE;
indent = foldLevel * indentSize;
} else {
indentSize = GetIndent();
indent = GetLineIndentation(LineFromPosition(pos));
}
if(GetUseTabs()) {
if(indentSize)
indent = indent / indentSize;
for(int i = 0; i < indent; i++) {
indentBlock << wxT("\t");
}
} else {
for(int i = 0; i < indent; i++) {
indentBlock << wxT(" ");
}
}
wxString eol = GetEolString();
textToInsert.Replace(wxT("\r"), wxT("\n"));
wxStringTokenizerMode tokenizerMode = (flags & Format_Text_Save_Empty_Lines) ? wxTOKEN_RET_EMPTY : wxTOKEN_STRTOK;
wxArrayString lines = wxStringTokenize(textToInsert, wxT("\n"), tokenizerMode);
textToInsert.Clear();
for(size_t i = 0; i < lines.GetCount(); i++) {
textToInsert << indentBlock;
textToInsert << lines.Item(i) << eol;
}
return textToInsert;
}
void LEditor::OnContextMenu(wxContextMenuEvent& event)
{
wxString selectText = GetSelectedText();
wxPoint pt = event.GetPosition();
wxPoint clientPt = ScreenToClient(pt);
// If the right-click is in the margin, provide a different context menu: bookmarks/breakpts
int margin = 0;
for(int n = 0; n < FOLD_MARGIN_ID; ++n) { // Assume a click anywhere to the left of the fold margin is for markers
margin += GetMarginWidth(n);
}
if(clientPt.x < margin) {
GotoPos(PositionFromPoint(clientPt));
// Let the plugins handle this event first
wxCommandEvent marginContextMenuEvent(wxEVT_CMD_EDITOR_MARGIN_CONTEXT_MENU, GetId());
marginContextMenuEvent.SetEventObject(this);
if(EventNotifier::Get()->ProcessEvent(marginContextMenuEvent))
return;
DoBreakptContextMenu(clientPt);
return;
}
int closePos = PositionFromPointClose(clientPt.x, clientPt.y);
if(closePos != wxNOT_FOUND) {
if(!selectText.IsEmpty()) {
// If the selection text is placed under the cursor,
// keep it selected, else, unselect the text
// and place the caret to be under cursor
int selStart = GetSelectionStart();
int selEnd = GetSelectionEnd();
if(closePos < selStart || closePos > selEnd) {
// cursor is not over the selected text, unselect and re-position caret
SetCaretAt(closePos);
}
} else {
// no selection, just place the caret
SetCaretAt(closePos);
}
}
// Let the plugins handle this event first
wxCommandEvent contextMenuEvent(wxEVT_CMD_EDITOR_CONTEXT_MENU, GetId());
contextMenuEvent.SetEventObject(this);
if(EventNotifier::Get()->ProcessEvent(contextMenuEvent))
return;
if(!m_rightClickMenu)
return;
// Let the context add it dynamic content
m_context->AddMenuDynamicContent(m_rightClickMenu);
// add the debugger (if currently running) to add its dynamic content
IDebugger* debugger = DebuggerMgr::Get().GetActiveDebugger();
if(debugger && debugger->IsRunning()) {
AddDebuggerContextMenu(m_rightClickMenu);
}
// turn the popupIsOn value to avoid annoying
// calltips from firing while our menu is popped
m_popupIsOn = true;
// let the plugins hook their content
if(!m_pluginInitializedRMenu) {
PluginManager::Get()->HookPopupMenu(m_rightClickMenu, MenuTypeEditor);
m_pluginInitializedRMenu = true;
}
{
// Notify about menu is about to be shown
clContextMenuEvent menuEvent(wxEVT_CONTEXT_MENU_EDITOR_SHOWING);
menuEvent.SetEditor(this);
menuEvent.SetMenu(m_rightClickMenu);
EventNotifier::Get()->ProcessEvent(menuEvent);
}
// Popup the menu
PopupMenu(m_rightClickMenu);
{
// notify that the menu was dismissed
clContextMenuEvent menuEvent(wxEVT_CONTEXT_MENU_EDITOR_DISMISSED);
menuEvent.SetEditor(this);
menuEvent.SetMenu(m_rightClickMenu);
EventNotifier::Get()->ProcessEvent(menuEvent);
}
m_popupIsOn = false;
// Let the context remove the dynamic content
m_context->RemoveMenuDynamicContent(m_rightClickMenu);
RemoveDebuggerContextMenu(m_rightClickMenu);
event.Skip();
}
void LEditor::OnKeyDown(wxKeyEvent& event)
{
// always cancel the tip
CodeCompletionBox::Get().CancelTip();
bool escapeUsed = false; // If the quickfind bar is open we'll use an ESC to close it; but only if we've not already
// used it for something else
// Hide tooltip dialog if its ON
IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
bool dbgTipIsShown = ManagerST::Get()->GetDebuggerTip()->IsShown();
bool keyIsControl = event.GetKeyCode() == WXK_CONTROL;
if(keyIsControl) {
// Debugger tooltip is shown when clicking 'Control/CMD'
// while the mouse is over a word
clDebugEvent event(wxEVT_DBG_EXPR_TOOLTIP);
event.SetString(this->GetWordAtMousePointer());
if(EventNotifier::Get()->ProcessEvent(event)) {
return;
}
}
if(dbgTipIsShown && !keyIsControl) {
// If any key is pressed, but the CONTROL key hide the
// debugger tip
ManagerST::Get()->GetDebuggerTip()->HideDialog();
escapeUsed = true;
} else if(dbgr && dbgr->IsRunning() && ManagerST::Get()->DbgCanInteract() && keyIsControl) {
DebuggerInformation info;
DebuggerMgr::Get().GetDebuggerInformation(dbgr->GetName(), info);
if(info.showTooltipsOnlyWithControlKeyIsDown) {
// CONTROL Key + Debugger is running and interactive
// and no debugger tip is shown -> emulate "Dwell" event
wxStyledTextEvent sciEvent;
wxPoint pt(ScreenToClient(wxGetMousePosition()));
sciEvent.SetPosition(PositionFromPointClose(pt.x, pt.y));
m_context->OnDbgDwellStart(sciEvent);
}
}
// let the context process it as well
if(GetFunctionTip()->IsActive() && event.GetKeyCode() == WXK_ESCAPE) {
GetFunctionTip()->Deactivate();
escapeUsed = true;
}
if(IsCompletionBoxShown()) {
switch(event.GetKeyCode()) {
case WXK_NUMPAD_ENTER:
case WXK_RETURN:
case WXK_TAB:
CodeCompletionBox::Get().InsertSelection();
HideCompletionBox();
return;
case WXK_ESCAPE:
case WXK_LEFT:
case WXK_RIGHT:
case WXK_HOME:
case WXK_END:
case WXK_DELETE:
case WXK_NUMPAD_DELETE:
HideCompletionBox();
return;
case WXK_UP:
CodeCompletionBox::Get().Previous();
return;
case WXK_DOWN:
CodeCompletionBox::Get().Next();
return;
case WXK_PAGEUP:
CodeCompletionBox::Get().PreviousPage();
return;
case WXK_PAGEDOWN:
CodeCompletionBox::Get().NextPage();
return;
case WXK_BACK: {
if(event.ControlDown()) {
HideCompletionBox();
} else {
wxString word = GetWordAtCaret();
if(word.IsEmpty()) {
HideCompletionBox();
} else {
word.RemoveLast();
if(CodeCompletionBox::Get().SelectWord(word)) {
HideCompletionBox();
}
}
}
break;
}
default:
break;
}
}
// If we've not already used ESC, there's a reasonable chance that the user wants to close the QuickFind bar
if(event.GetKeyCode() == WXK_ESCAPE && !escapeUsed) {
clMainFrame::Get()->GetMainBook()->ShowQuickBar(
false); // There's no easy way to tell if it's actually showing, so just do a Close
}
m_context->OnKeyDown(event);
}
void LEditor::OnLeftUp(wxMouseEvent& event)
{
m_isDragging = false; // We can't still be in D'n'D, so stop disabling callticks
long value(0);
EditorConfigST::Get()->GetLongValue(wxT("QuickCodeNavigationUsesMouseMiddleButton"), value);
if(!value) {
DoQuickJump(event, false);
}
PostCmdEvent(wxEVT_EDITOR_CLICKED);
event.Skip();
}
void LEditor::OnLeaveWindow(wxMouseEvent& event)
{
m_hyperLinkIndicatroStart = wxNOT_FOUND;
m_hyperLinkIndicatroEnd = wxNOT_FOUND;
m_hyperLinkType = wxID_NONE;
SetIndicatorCurrent(HYPERLINK_INDICATOR);
IndicatorClearRange(0, GetLength());
event.Skip();
}
void LEditor::OnFocusLost(wxFocusEvent& event)
{
m_isFocused = false;
event.Skip();
}
void LEditor::OnRightUp(wxMouseEvent& event) { event.Skip(); }
void LEditor::OnRightDown(wxMouseEvent& event)
{
int mod = GetCodeNavModifier();
if(event.GetModifiers() == mod && mod != wxMOD_NONE) {
ClearSelections();
long pos = PositionFromPointClose(event.GetX(), event.GetY());
if(pos != wxNOT_FOUND) {
DoSetCaretAt(pos);
}
clCodeCompletionEvent event(wxEVT_CC_SHOW_QUICK_NAV_MENU);
event.SetEditor(this);
event.SetPosition(pos);
event.SetInsideCommentOrString(m_context->IsCommentOrString(pos));
EventNotifier::Get()->AddPendingEvent(event);
} else {
event.Skip();
}
}
void LEditor::OnMotion(wxMouseEvent& event)
{
int mod = GetCodeNavModifier();
if(event.GetModifiers() == mod && mod != wxMOD_NONE) {
m_hyperLinkIndicatroStart = wxNOT_FOUND;
m_hyperLinkIndicatroEnd = wxNOT_FOUND;
m_hyperLinkType = wxID_NONE;
SetIndicatorCurrent(HYPERLINK_INDICATOR);
IndicatorClearRange(0, GetLength());
DoMarkHyperlink(event, true);
} else {
event.Skip();
}
}
void LEditor::OnLeftDown(wxMouseEvent& event)
{
#if wxVERSION_NUMBER >= 2900
HighlightWord(false);
#endif
// hide completion box
HideCompletionBox();
CodeCompletionBox::Get().CancelTip();
GetFunctionTip()->Deactivate();
if(ManagerST::Get()->GetDebuggerTip()->IsShown()) {
ManagerST::Get()->GetDebuggerTip()->HideDialog();
}
int mod = GetCodeNavModifier();
if(m_hyperLinkType != wxID_NONE && event.GetModifiers() == mod && mod != wxMOD_NONE) {
ClearSelections();
SetCaretAt(PositionFromPointClose(event.GetX(), event.GetY()));
}
SetActive();
event.Skip();
}
void LEditor::OnPopupMenuUpdateUI(wxUpdateUIEvent& event)
{
// pass it to the context
m_context->ProcessEvent(event);
}
BrowseRecord LEditor::CreateBrowseRecord()
{
// Remember this position before skipping to the next one
BrowseRecord record;
record.lineno = LineFromPosition(GetCurrentPos()) + 1; // scintilla counts from zero, while tagentry from 1
record.filename = GetFileName().GetFullPath();
record.project = GetProject();
// if the file is part of the workspace set the project name
// else, open it with empty project
record.position = GetCurrentPos();
return record;
}
void LEditor::DoBreakptContextMenu(wxPoint pt)
{
// turn the popupIsOn value to avoid annoying
// calltips from firing while our menu is popped
m_popupIsOn = true;
int ToHereId = 0;
wxMenu menu;
// First, add/del bookmark
menu.Append(XRCID("toggle_bookmark"),
LineIsMarked(GetActiveBookmarkMask()) ? wxString(_("Remove Bookmark")) : wxString(_("Add Bookmark")));
menu.Append(XRCID("removeall_bookmarks"), _("Remove All Bookmarks"));
BookmarkManager::Get().CreateBookmarksSubmenu(&menu);
menu.AppendSeparator();
menu.Append(XRCID("add_breakpoint"), wxString(_("Add Breakpoint")));
menu.Append(XRCID("insert_temp_breakpoint"), wxString(_("Add a Temporary Breakpoint")));
menu.Append(XRCID("insert_disabled_breakpoint"), wxString(_("Add a Disabled Breakpoint")));
menu.Append(XRCID("insert_cond_breakpoint"), wxString(_("Add a Conditional Breakpoint..")));
BreakpointInfo& bp =
ManagerST::Get()->GetBreakpointsMgr()->GetBreakpoint(GetFileName().GetFullPath(), GetCurrentLine() + 1);
// What we show depends on whether there's already a bp here (or several)
if(!bp.IsNull()) {
// Disable all the "Add*" entries
menu.Enable(XRCID("add_breakpoint"), false);
menu.Enable(XRCID("insert_temp_breakpoint"), false);
menu.Enable(XRCID("insert_disabled_breakpoint"), false);
menu.Enable(XRCID("insert_cond_breakpoint"), false);
menu.AppendSeparator();
menu.Append(XRCID("delete_breakpoint"), wxString(_("Remove Breakpoint")));
menu.Append(XRCID("ignore_breakpoint"), wxString(_("Ignore Breakpoint")));
// On MSWin it often crashes the debugger to try to load-then-disable a bp
// so don't show the menu item unless the debugger is running *** Hmm, that was written about 4 years ago. Let's
// try it again...
menu.Append(XRCID("toggle_breakpoint_enabled_status"),
bp.is_enabled ? wxString(_("Disable Breakpoint")) : wxString(_("Enable Breakpoint")));
menu.Append(XRCID("edit_breakpoint"), wxString(_("Edit Breakpoint")));
}
if(ManagerST::Get()->DbgCanInteract()) {
menu.AppendSeparator();
ToHereId = wxNewId();
menu.Append(ToHereId, _("Run to here"));
menu.Connect(
ToHereId, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(LEditor::OnDbgRunToCursor), NULL, this);
}
PopupMenu(&menu, pt.x, pt.y);
m_popupIsOn = false;
if(ToHereId) {
menu.Disconnect(
ToHereId, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(LEditor::OnDbgRunToCursor), NULL, this);
}
}
void LEditor::AddOtherBreakpointType(wxCommandEvent& event)
{
bool is_temp = (event.GetId() == XRCID("insert_temp_breakpoint"));
bool is_disabled = (event.GetId() == XRCID("insert_disabled_breakpoint"));
wxString conditions;
if(event.GetId() == XRCID("insert_cond_breakpoint")) {
conditions = wxGetTextFromUser(_("Enter the condition statement"), _("Create Conditional Breakpoint"));
if(conditions.IsEmpty()) {
return;
}
}
AddBreakpoint(-1, conditions, is_temp, is_disabled);
}
void LEditor::OnIgnoreBreakpoint()
{
if(ManagerST::Get()->GetBreakpointsMgr()->IgnoreByLineno(GetFileName().GetFullPath(), GetCurrentLine() + 1)) {
clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
}
}
void LEditor::OnEditBreakpoint()
{
ManagerST::Get()->GetBreakpointsMgr()->EditBreakpointByLineno(GetFileName().GetFullPath(), GetCurrentLine() + 1);
clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
}
void LEditor::AddBreakpoint(int lineno /*= -1*/,
const wxString& conditions /*=wxT("")*/,
const bool is_temp /*=false*/,
const bool is_disabled /*=false*/)
{
if(lineno == -1) {
lineno = GetCurrentLine() + 1;
}
ManagerST::Get()->GetBreakpointsMgr()->SetExpectingControl(true);
if(!ManagerST::Get()->GetBreakpointsMgr()->AddBreakpointByLineno(
GetFileName().GetFullPath(), lineno, conditions, is_temp, is_disabled)) {
wxMessageBox(_("Failed to insert breakpoint"));
} else {
clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
wxString message(_("Breakpoint successfully added")), prefix;
if(is_temp) {
prefix = _("Temporary ");
} else if(is_disabled) {
prefix = _("Disabled ");
} else if(!conditions.IsEmpty()) {
prefix = _("Conditional ");
}
DoSetStatusMessage(prefix + message, 0);
}
}
void LEditor::DelBreakpoint(int lineno /*= -1*/)
{
if(lineno == -1) {
lineno = GetCurrentLine() + 1;
}
wxString message;
// enable the 'expectingControl' to 'true'
// this is used by Manager class to detect whether the control
// was triggered by user action
ManagerST::Get()->GetBreakpointsMgr()->SetExpectingControl(true);
int result = ManagerST::Get()->GetBreakpointsMgr()->DelBreakpointByLineno(GetFileName().GetFullPath(), lineno);
switch(result) {
case true:
clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
DoSetStatusMessage(_("Breakpoint successfully deleted"), 0);
return;
case wxID_CANCEL:
return;
case false:
message = _("No breakpoint found on this line");
break;
default:
message = _("Breakpoint deletion failed");
}
wxMessageBox(message, _("Breakpoint not deleted"), wxICON_ERROR | wxOK);
}
void LEditor::ToggleBreakpoint(int lineno)
{
// Coming from OnMarginClick() means that lineno comes from the mouse position, not necessarily the current line
if(lineno == -1) {
lineno = GetCurrentLine() + 1;
}
// Does any of the plugins want to handle this?
clDebugEvent dbgEvent(wxEVT_DBG_UI_TOGGLE_BREAKPOINT);
dbgEvent.SetInt(lineno);
dbgEvent.SetFileName(GetFileName().GetFullPath());
if(EventNotifier::Get()->ProcessEvent(dbgEvent)) {
return;
}
const BreakpointInfo& bp =
ManagerST::Get()->GetBreakpointsMgr()->GetBreakpoint(GetFileName().GetFullPath(), lineno);
if(bp.IsNull()) {
// This will (always?) be from a margin mouse-click, so assume it's a standard breakpt that's wanted
AddBreakpoint(lineno);
} else {
DelBreakpoint(lineno);
}
}
void LEditor::SetWarningMarker(int lineno, const wxString& annotationText)
{
if(lineno >= 0) {
// Keep the text message
if(m_compilerMessagesMap.count(lineno)) {
m_compilerMessagesMap.erase(lineno);
}
m_compilerMessagesMap.insert(std::make_pair(lineno, annotationText));
BuildTabSettingsData options;
EditorConfigST::Get()->ReadObject(wxT("build_tab_settings"), &options);
if(options.GetErrorWarningStyle() & BuildTabSettingsData::EWS_Bookmarks) {
MarkerAdd(lineno, smt_warning);
}
if(options.GetErrorWarningStyle() & BuildTabSettingsData::EWS_Annotate) {
// define the warning marker
AnnotationSetText(lineno, annotationText);
AnnotationSetStyle(lineno, ANNOTATION_STYLE_WARNING);
}
}
}
void LEditor::SetErrorMarker(int lineno, const wxString& annotationText)
{
if(lineno >= 0) {
// Keep the text message
if(m_compilerMessagesMap.count(lineno)) {
m_compilerMessagesMap.erase(lineno);
}
m_compilerMessagesMap.insert(std::make_pair(lineno, annotationText));
BuildTabSettingsData options;
EditorConfigST::Get()->ReadObject(wxT("build_tab_settings"), &options);
if(options.GetErrorWarningStyle() & BuildTabSettingsData::EWS_Bookmarks) {
MarkerAdd(lineno, smt_error);
}
if(options.GetErrorWarningStyle() & BuildTabSettingsData::EWS_Annotate) {
AnnotationSetText(lineno, annotationText);
AnnotationSetStyle(lineno, ANNOTATION_STYLE_ERROR);
}
}
}
void LEditor::DelAllCompilerMarkers()
{
MarkerDeleteAll(smt_warning);
MarkerDeleteAll(smt_error);
AnnotationClearAll();
m_compilerMessagesMap.clear();
}
// Maybe one day we'll display multiple bps differently
void LEditor::SetBreakpointMarker(int lineno,
BreakpointType bptype,
bool is_disabled,
const std::vector<BreakpointInfo>& bps)
{
BPtoMarker bpm = GetMarkerForBreakpt(bptype);
sci_marker_types markertype = is_disabled ? bpm.marker_disabled : bpm.marker;
int markerHandle = MarkerAdd(lineno - 1, markertype);
// keep the breakpoint info vector for this marker
m_breakpointsInfo.insert(std::make_pair(markerHandle, bps));
}
void LEditor::DelAllBreakpointMarkers()
{
// remove the stored information
m_breakpointsInfo.clear();
for(int bp_type = BP_FIRST_ITEM; bp_type <= BP_LAST_MARKED_ITEM; ++bp_type) {
BPtoMarker bpm = GetMarkerForBreakpt((BreakpointType)bp_type);
MarkerDeleteAll(bpm.marker);
MarkerDeleteAll(bpm.marker_disabled);
}
}
void LEditor::HighlightLine(int lineno)
{
if(GetLineCount() <= 0) {
return;
}
int sci_line = lineno - 1;
if(GetLineCount() < sci_line - 1) {
sci_line = GetLineCount() - 1;
}
MarkerAdd(sci_line, smt_indicator);
}
void LEditor::UnHighlightAll() { MarkerDeleteAll(smt_indicator); }
void LEditor::AddDebuggerContextMenu(wxMenu* menu)
{
if(!ManagerST::Get()->DbgCanInteract()) {
return;
}
wxString word = GetSelectedText();
if(word.IsEmpty()) {
word = GetWordAtCaret();
if(word.IsEmpty()) {
return;
}
}
m_customCmds.clear();
wxString menuItemText;
wxMenuItem* item;
item = new wxMenuItem(menu, wxID_SEPARATOR);
menu->Prepend(item);
m_dynItems.push_back(item);
//---------------------------------------------
// Add custom commands
//---------------------------------------------
menu->Prepend(XRCID("debugger_watches"), _("More Watches"), DoCreateDebuggerWatchMenu(word));
menuItemText.Clear();
menuItemText << _("Add Watch") << wxT(" '") << word << wxT("'");
item = new wxMenuItem(menu, wxNewId(), menuItemText);
menu->Prepend(item);
menu->Connect(
item->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(LEditor::OnDbgAddWatch), NULL, this);
m_dynItems.push_back(item);
menuItemText.Clear();
item = new wxMenuItem(menu, wxNewId(), _("Run to cursor"));
menu->Prepend(item);
menu->Connect(
item->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(LEditor::OnDbgRunToCursor), NULL, this);
m_dynItems.push_back(item);
item = new wxMenuItem(menu, wxNewId(), _("Jump to cursor"));
menu->Prepend(item);
menu->Connect(
item->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(LEditor::OnDbgJumpToCursor), NULL, this);
m_dynItems.push_back(item);
}
void LEditor::RemoveDebuggerContextMenu(wxMenu* menu)
{
std::vector<wxMenuItem*>::iterator iter = m_dynItems.begin();
// disconnect all event handlers
for(; iter != m_dynItems.end(); iter++) {
Disconnect((*iter)->GetId(),
wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler(LEditor::OnDbgCustomWatch),
NULL,
this);
menu->Remove(*iter);
}
wxMenuItem* item = menu->FindItem(XRCID("debugger_watches"));
while(item) {
if(item) {
menu->Destroy(item);
}
item = menu->FindItem(XRCID("debugger_watches"));
}
m_dynItems.clear();
m_customCmds.clear();
}
void LEditor::OnDbgAddWatch(wxCommandEvent& event)
{
wxUnusedVar(event);
wxString word = GetSelectedText();
if(word.IsEmpty()) {
word = GetWordAtCaret();
if(word.IsEmpty()) {
return;
}
}
clMainFrame::Get()->GetDebuggerPane()->GetWatchesTable()->AddExpression(word);
clMainFrame::Get()->GetDebuggerPane()->SelectTab(DebuggerPane::WATCHES);
clMainFrame::Get()->GetDebuggerPane()->GetWatchesTable()->RefreshValues();
}
void LEditor::OnDbgCustomWatch(wxCommandEvent& event)
{
wxUnusedVar(event);
wxString word = GetSelectedText();
if(word.IsEmpty()) {
word = GetWordAtCaret();
if(word.IsEmpty()) {
return;
}
}
// find the custom command to run
std::map<int, wxString>::iterator iter = m_customCmds.find(event.GetId());
if(iter != m_customCmds.end()) {
// Replace $(Variable) with the actual string
wxString command = iter->second;
command = MacroManager::Instance()->Replace(command, wxT("variable"), word, true);
clMainFrame::Get()->GetDebuggerPane()->GetWatchesTable()->AddExpression(command);
clMainFrame::Get()->GetDebuggerPane()->SelectTab(DebuggerPane::WATCHES);
clMainFrame::Get()->GetDebuggerPane()->GetWatchesTable()->RefreshValues();
}
}
void LEditor::UpdateColours()
{
// disable macros tracking (if needed it will be re-enabled by
// the Clang Worker Thread
SetProperty(wxT("lexer.cpp.track.preprocessor"), wxT("0"));
SetProperty(wxT("lexer.cpp.update.preprocessor"), wxT("0"));
Colourise(0, wxSTC_INVALID_POSITION);
if(TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_COLOUR_VARS ||
TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_COLOUR_WORKSPACE_TAGS ||
TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_COLOUR_MACRO_BLOCKS) {
m_context->OnFileSaved();
} else {
if(m_context->GetName() == wxT("C++")) {
SetKeyWords(1, wxEmptyString);
SetKeyWords(2, wxEmptyString);
SetKeyWords(3, wxEmptyString);
SetKeyWords(4, wxEmptyString);
}
}
}
int LEditor::SafeGetChar(int pos)
{
if(pos < 0 || pos >= GetLength()) {
return 0;
}
return GetCharAt(pos);
}
void LEditor::OnDragStart(wxStyledTextEvent& e)
{
m_isDragging = true; // Otherwise it sometimes obscures the desired drop zone!
e.Skip();
}
void LEditor::OnDragEnd(wxStyledTextEvent& e)
{
// For future reference, this will only be called when D'n'D ends successfully with a drop.
// Unfortunately scintilla doesn't seem to provide any notification when ESC is pressed, or the drop-zone is invalid
m_isDragging = false; // Turn on calltips again
e.Skip();
}
void LEditor::ShowCompletionBox(const std::vector<TagEntryPtr>& tags,
const wxString& word,
bool autoRefreshList,
wxEvtHandler* owner)
{
if(tags.empty()) {
return;
}
// If the number of elements exceeds the maximum query result,
// alert the user
// int limit(TagsManagerST::Get()->GetDatabase()->GetSingleSearchLimit());
//
// int ccTooManyMatches(0);
// ccTooManyMatches = clConfig::Get().GetAnnoyingDlgAnswer("CodeCompletionTooManyMatches", 0);
// if(tags.size() >= (size_t)limit && !ccTooManyMatches) {
// wxString msg =
// wxString::Format(_("Too many matches found, displaying %u. Keep typing to narrow the choices\nYou can "
// "increase the number of displayed items from the menu: 'Settings | Tags Settings'"),
// (unsigned int)tags.size());
// clMainFrame::Get()->GetMainBook()->ShowMessage(
// msg,
// true,
// PluginManager::Get()->GetStdIcons()->LoadBitmap(wxT("messages/48/tip")),
// ButtonDetails(),
// ButtonDetails(),
// ButtonDetails(),
// CheckboxDetails(wxT("CodeCompletionTooManyMatches")));
// }
CodeCompletionBox::Get().Display(this, tags, word, !autoRefreshList, owner);
}
void LEditor::ShowCompletionBox(const std::vector<TagEntryPtr>& tags,
const wxString& word,
bool showFullDecl,
bool autoHide,
bool autoInsertSingleChoice)
{
// bool isRefereshing = CodeCompletionManager::Get().GetWordCompletionRefreshNeeded();
if(tags.empty()) {
return;
}
// If the number of elements exceeds the maximum query result,
// alert the user
// int limit(TagsManagerST::Get()->GetDatabase()->GetSingleSearchLimit());
// int ccTooManyMatches(0);
// ccTooManyMatches = clConfig::Get().GetAnnoyingDlgAnswer("CodeCompletionTooManyMatches", 0);
// if(tags.size() >= (size_t)limit && !ccTooManyMatches) {
// wxString msg =
// wxString::Format(_("Too many matches found, displaying %u. Keep typing to narrow the choices\nYou can "
// "increase the number of displayed items from the menu: 'Settings | Tags Settings'"),
// (unsigned int)tags.size());
// clMainFrame::Get()->GetMainBook()->ShowMessage(
// msg,
// true,
// PluginManager::Get()->GetStdIcons()->LoadBitmap(wxT("messages/48/tip")),
// ButtonDetails(),
// ButtonDetails(),
// ButtonDetails(),
// CheckboxDetails(wxT("CodeCompletionTooManyMatches")));
// }
CodeCompletionBox::Get().Display(this, tags, word, tags.at(0)->GetKind() == wxT("cpp_keyword"), NULL);
}
void LEditor::HideCompletionBox() { CodeCompletionBox::Get().Hide(); }
int LEditor::GetCurrLineHeight()
{
int point = GetCurrentPos();
wxPoint pt = PointFromPosition(point);
// calculate the line height
int curline = LineFromPosition(point);
int ll;
int hh(0);
if(curline > 0) {
ll = curline - 1;
int pp = PositionFromLine(ll);
wxPoint p = PointFromPosition(pp);
hh = pt.y - p.y;
} else {
ll = curline + 1;
int pp = PositionFromLine(ll);
wxPoint p = PointFromPosition(pp);
hh = p.y - pt.y;
}
if(hh == 0) {
hh = 12; // default height on most OSs
}
return hh;
}
void LEditor::DoHighlightWord()
{
wxString word = GetSelectedText();
if(word.IsEmpty()) {
return;
}
// to make the code "smoother" we move the search task to different thread
StringHighlighterJob* j = new StringHighlighterJob(
clMainFrame::Get()->GetMainBook(), GetText().c_str(), word.c_str(), GetFileName().GetFullPath().c_str());
JobQueueSingleton::Instance()->PushJob(j);
}
void LEditor::HighlightWord(bool highlight)
{
if(highlight) {
DoHighlightWord();
} else {
SetIndicatorCurrent(MARKER_WORD_HIGHLIGHT);
IndicatorClearRange(0, GetLength());
}
}
void LEditor::OnLeftDClick(wxStyledTextEvent& event)
{
long highlight_word(0);
EditorConfigST::Get()->GetLongValue(wxT("highlight_word"), highlight_word);
if(GetSelectedText().IsEmpty() == false && highlight_word) {
DoHighlightWord();
}
event.Skip();
}
bool LEditor::IsCompletionBoxShown() { return CodeCompletionBox::Get().IsShown(); }
int LEditor::GetCurrentLine()
{
// return the current line number
int pos = GetCurrentPos();
return LineFromPosition(pos);
}
void LEditor::DoSetCaretAt(long pos)
{
SetCurrentPos(pos);
SetSelectionStart(pos);
SetSelectionEnd(pos);
int line = LineFromPosition(pos);
if(line >= 0) {
// This is needed to unfold the line if it were folded
// The various other 'EnsureVisible' things don't do this
EnsureVisible(line);
}
}
int LEditor::GetEOLByContent()
{
if(GetLength() == 0) {
return wxNOT_FOUND;
}
// locate the first EOL
wxString txt = GetText();
size_t pos1 = static_cast<size_t>(txt.Find(wxT("\n")));
size_t pos2 = static_cast<size_t>(txt.Find(wxT("\r\n")));
size_t pos3 = static_cast<size_t>(txt.Find(wxT("\r")));
size_t max_size_t = static_cast<size_t>(-1);
// the buffer is not empty but it does not contain any EOL as well
if(pos1 == max_size_t && pos2 == max_size_t && pos3 == max_size_t) {
return wxNOT_FOUND;
}
size_t first_eol_pos(0);
pos2 < pos1 ? first_eol_pos = pos2 : first_eol_pos = pos1;
pos3 < first_eol_pos ? first_eol_pos = pos3 : first_eol_pos = first_eol_pos;
// get the EOL at first_eol_pos
wxChar ch = SafeGetChar(first_eol_pos);
if(ch == wxT('\n')) {
return wxSTC_EOL_LF;
}
if(ch == wxT('\r')) {
wxChar secondCh = SafeGetChar(first_eol_pos + 1);
if(secondCh == wxT('\n')) {
return wxSTC_EOL_CRLF;
} else {
return wxSTC_EOL_CR;
}
}
return wxNOT_FOUND;
}
int LEditor::GetEOLByOS()
{
OptionsConfigPtr options = GetOptions();
if(options->GetEolMode() == wxT("Unix (LF)")) {
return wxSTC_EOL_LF;
} else if(options->GetEolMode() == wxT("Mac (CR)")) {
return wxSTC_EOL_CR;
} else if(options->GetEolMode() == wxT("Windows (CRLF)")) {
return wxSTC_EOL_CRLF;
} else {
// set the EOL by the hosting OS
#if defined(__WXMAC__)
return wxSTC_EOL_LF;
#elif defined(__WXGTK__)
return wxSTC_EOL_LF;
#else
return wxSTC_EOL_CRLF;
#endif
}
}
void LEditor::ShowFunctionTipFromCurrentPos()
{
if(TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_DISP_FUNC_CALLTIP) {
if(EventNotifier::Get()->IsEventsDiabled())
return;
int pos = DoGetOpenBracePos();
// see if any of the plugins want to handle it
clCodeCompletionEvent evt(wxEVT_CC_CODE_COMPLETE_FUNCTION_CALLTIP, GetId());
evt.SetEventObject(this);
evt.SetEditor(this);
evt.SetPosition(pos);
evt.SetInsideCommentOrString(m_context->IsCommentOrString(pos));
if(EventNotifier::Get()->ProcessEvent(evt))
return;
if(pos != wxNOT_FOUND) {
m_context->CodeComplete(pos);
}
}
}
wxString LEditor::GetSelection() { return wxStyledTextCtrl::GetSelectedText(); }
int LEditor::GetSelectionStart() { return wxStyledTextCtrl::GetSelectionStart(); }
int LEditor::GetSelectionEnd() { return wxStyledTextCtrl::GetSelectionEnd(); }
void LEditor::ReplaceSelection(const wxString& text) { wxStyledTextCtrl::ReplaceSelection(text); }
void LEditor::ClearUserIndicators()
{
SetIndicatorCurrent(USER_INDICATOR);
IndicatorClearRange(0, GetLength());
}
int LEditor::GetUserIndicatorEnd(int pos) { return wxStyledTextCtrl::IndicatorEnd(USER_INDICATOR, pos); }
int LEditor::GetUserIndicatorStart(int pos) { return wxStyledTextCtrl::IndicatorStart(USER_INDICATOR, pos); }
void LEditor::SelectText(int startPos, int len)
{
SetSelectionStart(startPos);
SetSelectionEnd(startPos + len);
}
void LEditor::SetUserIndicator(int startPos, int len)
{
SetIndicatorCurrent(USER_INDICATOR);
IndicatorFillRange(startPos, len);
}
void LEditor::SetUserIndicatorStyleAndColour(int style, const wxColour& colour)
{
IndicatorSetForeground(USER_INDICATOR, colour);
IndicatorSetStyle(USER_INDICATOR, style);
IndicatorSetUnder(USER_INDICATOR, true);
}
int LEditor::GetLexerId() { return GetLexer(); }
int LEditor::GetStyleAtPos(int pos) { return GetStyleAt(pos); }
void LEditor::RegisterImageForKind(const wxString& kind, const wxBitmap& bmp)
{
CodeCompletionBox::Get().RegisterImage(kind, bmp);
}
int LEditor::WordStartPos(int pos, bool onlyWordCharacters)
{
return wxStyledTextCtrl::WordStartPosition(pos, onlyWordCharacters);
}
int LEditor::WordEndPos(int pos, bool onlyWordCharacters)
{
return wxStyledTextCtrl::WordEndPosition(pos, onlyWordCharacters);
}
void LEditor::DoMarkHyperlink(wxMouseEvent& event, bool isMiddle)
{
if(event.m_controlDown || isMiddle) {
SetIndicatorCurrent(HYPERLINK_INDICATOR);
long pos = PositionFromPointClose(event.GetX(), event.GetY());
IndicatorSetForeground(HYPERLINK_INDICATOR, wxT("NAVY"));
if(pos != wxSTC_INVALID_POSITION) {
m_hyperLinkType = m_context->GetHyperlinkRange(pos, m_hyperLinkIndicatroStart, m_hyperLinkIndicatroEnd);
if(m_hyperLinkType != wxID_NONE) {
IndicatorFillRange(m_hyperLinkIndicatroStart, m_hyperLinkIndicatroEnd - m_hyperLinkIndicatroStart);
} else {
m_hyperLinkIndicatroStart = wxNOT_FOUND;
m_hyperLinkIndicatroEnd = wxNOT_FOUND;
}
}
}
}
void LEditor::DoQuickJump(wxMouseEvent& event, bool isMiddle)
{
if(m_hyperLinkIndicatroStart != wxNOT_FOUND && m_hyperLinkIndicatroEnd != wxNOT_FOUND) {
// indicator is highlighted
long pos = PositionFromPointClose(event.GetX(), event.GetY());
if(m_hyperLinkIndicatroStart <= pos && pos <= m_hyperLinkIndicatroEnd) {
bool altLink = (isMiddle && event.m_controlDown) || (!isMiddle && event.m_altDown);
m_context->GoHyperlink(m_hyperLinkIndicatroStart, m_hyperLinkIndicatroEnd, m_hyperLinkType, altLink);
}
}
// clear the hyper link indicators
m_hyperLinkIndicatroStart = wxNOT_FOUND;
m_hyperLinkIndicatroEnd = wxNOT_FOUND;
SetIndicatorCurrent(HYPERLINK_INDICATOR);
IndicatorClearRange(0, GetLength());
event.Skip();
}
void LEditor::TrimText(bool trim, bool appendLf)
{
bool dontTrimCaretLine = GetOptions()->GetDontTrimCaretLine();
bool trimOnlyModifiedLInes = GetOptions()->GetTrimOnlyModifiedLines();
if(!trim && !appendLf) {
return;
}
// wrap the entire operation in a single undo action
BeginUndoAction();
if(trim) {
int maxLines = GetLineCount();
int currLine = GetCurrentLine();
for(int line = 0; line < maxLines; line++) {
// only trim lines modified by the user in this session
if(trimOnlyModifiedLInes && (MarginGetStyle(line) != CL_LINE_MODIFIED_STYLE))
continue;
// We can trim in the following cases:
// 1) line is is NOT the caret line OR
// 2) line is the caret line, however dontTrimCaretLine is FALSE
bool canTrim = ((line != currLine) || (line == currLine && !dontTrimCaretLine));
if(canTrim) {
int lineStart = PositionFromLine(line);
int lineEnd = GetLineEndPosition(line);
int i = lineEnd - 1;
wxChar ch = (wxChar)(GetCharAt(i));
while((i >= lineStart) && ((ch == _T(' ')) || (ch == _T('\t')))) {
i--;
ch = (wxChar)(GetCharAt(i));
}
if(i < (lineEnd - 1)) {
SetTargetStart(i + 1);
SetTargetEnd(lineEnd);
ReplaceTarget(_T(""));
}
}
}
}
if(appendLf) {
// The following code was adapted from the SciTE sourcecode
int maxLines = GetLineCount();
int enddoc = PositionFromLine(maxLines);
if(maxLines <= 1 || enddoc > PositionFromLine(maxLines - 1))
InsertText(enddoc, GetEolString());
}
EndUndoAction();
}
wxString LEditor::GetEolString()
{
wxString eol;
switch(this->GetEOLMode()) {
case wxSTC_EOL_CR:
eol = wxT("\r");
break;
case wxSTC_EOL_CRLF:
eol = wxT("\r\n");
break;
case wxSTC_EOL_LF:
eol = wxT("\n");
break;
}
return eol;
}
void LEditor::OnDbgRunToCursor(wxCommandEvent& event)
{
IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
if(dbgr && dbgr->IsRunning() && ManagerST::Get()->DbgCanInteract()) {
BreakpointInfo bp;
bp.Create(
GetFileName().GetFullPath(), GetCurrentLine() + 1, ManagerST::Get()->GetBreakpointsMgr()->GetNextID());
bp.bp_type = BP_type_tempbreak;
dbgr->Break(bp);
dbgr->Continue();
}
}
void LEditor::OnDbgJumpToCursor(wxCommandEvent& event)
{
IDebugger* dbgr = DebuggerMgr::Get().GetActiveDebugger();
if(dbgr && dbgr->IsRunning() && ManagerST::Get()->DbgCanInteract()) {
dbgr->Jump(GetFileName().GetFullPath(), GetCurrentLine() + 1);
}
}
void LEditor::DoSetStatusMessage(const wxString& msg, int col, int seconds_to_live /*=wxID_ANY*/)
{
wxCommandEvent e(wxEVT_UPDATE_STATUS_BAR);
e.SetEventObject(this);
e.SetString(msg);
e.SetInt(col);
e.SetId(seconds_to_live);
clMainFrame::Get()->GetEventHandler()->AddPendingEvent(e);
}
void LEditor::DoShowCalltip(int pos, const wxString& tip)
{
CodeCompletionBox::Get().CancelTip();
if(pos == wxNOT_FOUND) {
CodeCompletionBox::Get().ShowTip(tip, wxGetMousePosition(), this);
} else {
CodeCompletionBox::Get().ShowTip(tip, this);
}
}
void LEditor::DoCancelCalltip()
{
CodeCompletionBox::Get().CancelTip();
CallTipCancel();
GetFunctionTip()->Deactivate();
m_context->OnCalltipCancel();
}
int LEditor::DoGetOpenBracePos()
{
// determine the closest open brace from the current caret position
int depth(0);
int char_tested(0); // we add another performance tuning here: dont test more than 256 characters backward
bool exit_loop(false);
int pos = PositionBefore(GetCurrentPos());
while(pos > 0 && char_tested < 256) {
wxChar ch = SafeGetChar(pos);
if(m_context->IsCommentOrString(pos)) {
pos = PositionBefore(pos);
continue;
}
char_tested++;
switch(ch) {
case wxT('{'):
case wxT('}'):
case wxT(';'):
exit_loop = true;
break;
case wxT('('):
depth++;
if(depth == 1) {
pos = PositionAfter(pos);
exit_loop = true;
} else {
pos = PositionBefore(pos);
}
break;
case wxT(')'):
depth--;
// fall through
default:
pos = PositionBefore(pos);
break;
}
if(exit_loop)
break;
}
if(char_tested == 256) {
return wxNOT_FOUND;
} else if(depth == 1 && pos >= 0) {
return pos;
}
return wxNOT_FOUND;
}
void LEditor::SetEOL()
{
// set the EOL mode
int eol = GetEOLByOS();
int alternate_eol = GetEOLByContent();
if(alternate_eol != wxNOT_FOUND) {
eol = alternate_eol;
}
SetEOLMode(eol);
}
void LEditor::OnChange(wxStyledTextEvent& event)
{
bool isCoalesceStart = event.GetModificationType() & wxSTC_STARTACTION;
bool isInsert = event.GetModificationType() & wxSTC_MOD_INSERTTEXT;
bool isDelete = event.GetModificationType() & wxSTC_MOD_DELETETEXT;
bool isUndo = event.GetModificationType() & wxSTC_PERFORMED_UNDO;
bool isRedo = event.GetModificationType() & wxSTC_PERFORMED_REDO;
if((m_autoAddNormalBraces && !m_disableSmartIndent) || GetOptions()->GetAutoCompleteDoubleQuotes()) {
if((event.GetModificationType() & wxSTC_MOD_BEFOREDELETE) &&
(event.GetModificationType() & wxSTC_PERFORMED_USER)) {
wxString deletedText = GetTextRange(event.GetPosition(), event.GetPosition() + event.GetLength());
if(deletedText.IsEmpty() == false && deletedText.Length() == 1) {
if(deletedText.GetChar(0) == wxT('[') || deletedText.GetChar(0) == wxT('(')) {
int where = wxStyledTextCtrl::BraceMatch(event.GetPosition());
if(where != wxNOT_FOUND) {
wxCommandEvent e(wxCMD_EVENT_REMOVE_MATCH_INDICATOR);
// the removal will take place after the actual deletion of the
// character, so we set it to be position before
e.SetInt(PositionBefore(where));
AddPendingEvent(e);
}
} else if(deletedText.GetChar(0) == '\'' || deletedText.GetChar(0) == '"') {
wxChar searchChar = deletedText.GetChar(0);
// search for the matching close quote
int from = event.GetPosition() + 1;
int until = GetLineEndPosition(GetCurrentLine());
for(int i = from; i < until; ++i) {
if(SafeGetChar(i) == searchChar) {
wxCommandEvent e(wxCMD_EVENT_REMOVE_MATCH_INDICATOR);
// the removal will take place after the actual deletion of the
// character, so we set it to be position before
e.SetInt(PositionBefore(i));
AddPendingEvent(e);
}
}
}
}
}
}
if(event.GetModificationType() & wxSTC_MOD_CHANGESTYLE) {
#ifdef __WXGTK__
// Contents, styling or markers have been changed
// Refresh();
#endif
}
if(isCoalesceStart && GetCommandsProcessor().HasOpenCommand()) {
// The user has changed mode e.g. from inserting to deleting, so the current command must be closed
GetCommandsProcessor().CommandProcessorBase::ProcessOpenCommand(); // Use the base-class method, as this time we
// don't need to tell scintilla too
}
if(isInsert || isDelete) {
if(!GetReloadingFile() && !isUndo && !isRedo) {
CLCommand::Ptr_t currentOpen = GetCommandsProcessor().GetOpenCommand();
if(!currentOpen) {
GetCommandsProcessor().StartNewTextCommand(isInsert ? CLC_insert : CLC_delete);
}
// We need to cope with a selection being deleted by typing; this results in 0x2012 followed immediately by
// 0x11 i.e. with no intervening wxSTC_STARTACTION
else if(isInsert && currentOpen->GetCommandType() != CLC_insert) {
GetCommandsProcessor().ProcessOpenCommand();
GetCommandsProcessor().StartNewTextCommand(CLC_insert);
} else if(isDelete && currentOpen->GetCommandType() != CLC_delete) {
GetCommandsProcessor().ProcessOpenCommand();
GetCommandsProcessor().StartNewTextCommand(CLC_delete);
}
wxCHECK_RET(GetCommandsProcessor().HasOpenCommand(), "Trying to add to a non-existent or closed command");
wxCHECK_RET(GetCommandsProcessor().CanAppend(isInsert ? CLC_insert : CLC_delete),
"Trying to add to the wrong type of command");
GetCommandsProcessor().AppendToTextCommand(event.GetText(), event.GetPosition());
}
// Cache details of the number of lines added/removed
// This is used to 'update' any affected FindInFiles result. See bug 3153847
if(event.GetModificationType() & wxSTC_PERFORMED_UNDO) {
m_deltas->Pop();
} else {
m_deltas->Push(event.GetPosition(),
event.GetLength() * (event.GetModificationType() & wxSTC_MOD_DELETETEXT ? -1 : 1));
}
int numlines(event.GetLinesAdded());
if(numlines) {
if(GetReloadingFile() == false) {
// a line was added to or removed from the document, so synchronize the breakpoints on this editor
// and the breakpoint manager
UpdateBreakpoints();
} else {
// The file has been reloaded, so the cached line-changes are no longer relevant
m_deltas->Clear();
}
}
// ignore this event incase we are in the middle of file reloading
if(GetReloadingFile() == false && GetMarginWidth(EDIT_TRACKER_MARGIN_ID) /* margin is visible */) {
int curline(LineFromPosition(event.GetPosition()));
if(numlines == 0) {
// probably only the current line was modified
MarginSetText(curline, wxT(" "));
MarginSetStyle(curline, CL_LINE_MODIFIED_STYLE);
} else {
for(int i = 0; i <= numlines; i++) {
MarginSetText(curline + i, wxT(" "));
MarginSetStyle(curline + i, CL_LINE_MODIFIED_STYLE);
}
}
}
}
}
void LEditor::OnRemoveMatchInidicator(wxCommandEvent& e)
{
// get the current indicator end range
if(IndicatorValueAt(MATCH_INDICATOR, e.GetInt()) == 1) {
int curpos = GetCurrentPos();
SetSelection(e.GetInt(), e.GetInt() + 1);
ReplaceSelection(wxEmptyString);
SetCaretAt(curpos);
}
}
bool LEditor::FindAndSelect(const wxString& pattern, const wxString& what, int pos, NavMgr* navmgr)
{
return DoFindAndSelect(pattern, what, pos, navmgr);
}
bool LEditor::DoFindAndSelect(const wxString& _pattern, const wxString& what, int start_pos, NavMgr* navmgr)
{
BrowseRecord jumpfrom = CreateBrowseRecord();
bool realPattern(false);
wxString pattern(_pattern);
pattern.StartsWith(wxT("/^"), &pattern);
if(_pattern.Length() != pattern.Length()) {
realPattern = true;
}
if(pattern.EndsWith(wxT("$/"))) {
pattern = pattern.Left(pattern.Len() - 2);
realPattern = true;
} else if(pattern.EndsWith(wxT("/"))) {
pattern = pattern.Left(pattern.Len() - 1);
realPattern = true;
}
size_t flags = wxSD_MATCHCASE | wxSD_MATCHWHOLEWORD;
pattern.Trim();
if(pattern.IsEmpty())
return false;
FindReplaceData data;
data.SetFindString(pattern);
data.SetFlags(flags);
// keep current position
long curr_pos = GetCurrentPos();
int match_len(0), pos(0);
// set the caret at the document start
if(start_pos < 0 || start_pos > GetLength()) {
start_pos = 0;
}
// set the starting point
SetCurrentPos(0);
SetSelectionStart(0);
SetSelectionEnd(0);
int offset(start_pos);
bool again(false);
bool res(false);
do {
again = false;
flags = wxSD_MATCHCASE | wxSD_MATCHWHOLEWORD;
;
if(StringFindReplacer::Search(GetText().wc_str(), offset, pattern.wc_str(), flags, pos, match_len)) {
int line = LineFromPosition(pos);
wxString dbg_line = GetLine(line).Trim().Trim(false);
wxString tmp_pattern(pattern);
tmp_pattern.Trim().Trim(false);
if(dbg_line.Len() != tmp_pattern.Len() && tmp_pattern != what) {
offset = pos + match_len;
again = true;
} else {
// select only the name at the given text range
wxString display_name = what.BeforeFirst(wxT('('));
int match_len1(0), pos1(0);
flags |= wxSD_SEARCH_BACKWARD;
flags |= wxSD_MATCHWHOLEWORD;
if(realPattern) {
// the inner search is done on the pattern without the part of the
// signature
pattern = pattern.BeforeFirst(wxT('('));
}
if(StringFindReplacer::Search(pattern.wc_str(),
clUTF8Length(pattern.wc_str(), pattern.Len()),
display_name.wc_str(),
flags,
pos1,
match_len1)) {
// select only the word
// Check that pos1 is *not* 0 otherwise will get into an infinite loop
if(pos1 && GetContext()->IsCommentOrString(pos + pos1)) {
// try again
offset = pos + pos1;
again = true;
} else {
SetSelection(pos + pos1, pos + pos1 + match_len1);
res = true;
}
} else {
// as a fallback, mark the whole line
SetSelection(pos, pos + match_len);
res = true;
}
if(res && (line >= 0) && !again) {
SetEnsureCaretIsVisible(pos);
SetLineVisible(LineFromPosition(pos));
}
}
} else {
wxLogMessage(wxT("Failed to find[") + pattern + wxT("]"));
// match failed, restore the caret
SetCurrentPos(curr_pos);
SetSelectionStart(curr_pos);
SetSelectionEnd(curr_pos);
}
} while(again);
if(res && navmgr) {
navmgr->AddJump(jumpfrom, CreateBrowseRecord());
}
this->ScrollToColumn(0);
return res;
}
wxMenu* LEditor::DoCreateDebuggerWatchMenu(const wxString& word)
{
DebuggerSettingsPreDefMap data;
DebuggerConfigTool::Get()->ReadObject(wxT("DebuggerCommands"), &data);
DebuggerPreDefinedTypes preDefTypes = data.GetActiveSet();
DebuggerCmdDataVec cmds = preDefTypes.GetCmds();
wxMenu* menu = new wxMenu();
wxMenuItem* item(NULL);
wxString menuItemText;
for(size_t i = 0; i < cmds.size(); i++) {
DebuggerCmdData cmd = cmds.at(i);
menuItemText.Clear();
menuItemText << _("Watch") << wxT(" '") << word << wxT("' ") << _("as") << wxT(" '") << cmd.GetName()
<< wxT("'");
item = new wxMenuItem(menu, wxNewId(), menuItemText);
menu->Prepend(item);
Connect(
item->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(LEditor::OnDbgCustomWatch), NULL, this);
m_customCmds[item->GetId()] = cmd.GetCommand();
}
return menu;
}
OptionsConfigPtr LEditor::GetOptions()
{
// Start by getting the global settings
OptionsConfigPtr options = EditorConfigST::Get()->GetOptions();
// Now let any local preferences overwrite the global equivalent
if(ManagerST::Get()->IsWorkspaceOpen()) {
LocalWorkspaceST::Get()->GetOptions(options, GetProject());
}
return options;
}
bool LEditor::ReplaceAllExactMatch(const wxString& what, const wxString& replaceWith)
{
int offset(0);
wxString findWhat = what;
size_t flags = wxSD_MATCHWHOLEWORD | wxSD_MATCHCASE;
int pos(0);
int match_len(0);
int posInChars(0);
int match_lenInChars(0);
int matchCount(0);
wxString txt = GetText();
while(StringFindReplacer::Search(
txt.wc_str(), offset, findWhat.wc_str(), flags, pos, match_len, posInChars, match_lenInChars)) {
txt.Remove(posInChars, match_lenInChars);
txt.insert(posInChars, replaceWith);
matchCount++;
offset = pos + clUTF8Length(replaceWith.wc_str(), replaceWith.length()); // match_len;
}
// replace the buffer
BeginUndoAction();
long savedPos = GetCurrentPos();
SetText(txt);
// Restore the caret
SetCaretAt(savedPos);
EndUndoAction();
return (matchCount > 0);
}
void LEditor::SetLexerName(const wxString& lexerName) { SetSyntaxHighlight(lexerName); }
void LEditor::HighlightWord(StringHighlightOutput* highlightOutput)
{
// the search highlighter thread has completed the calculations, fetch the results and mark them in the editor
std::vector<std::pair<int, int> >* matches = highlightOutput->matches;
SetIndicatorCurrent(MARKER_WORD_HIGHLIGHT);
#ifdef __WXMAC__
IndicatorSetUnder(MARKER_WORD_HIGHLIGHT, true);
#endif
// clear the old markers
IndicatorClearRange(0, GetLength());
int selStart = GetSelectionStart();
for(size_t i = 0; i < matches->size(); i++) {
std::pair<int, int> p = matches->at(i);
// Dont highlight the current selection
if(p.first != selStart) {
IndicatorFillRange(p.first, p.second);
}
}
}
void LEditor::ChangeCase(bool toLower)
{
bool hasSelection = (GetSelectedText().IsEmpty() == false);
if(hasSelection) {
// Simply change the case of the selection
toLower ? LowerCase() : UpperCase();
} else {
if(GetCurrentPos() >= GetLength())
return;
// Select the char
SelectText(GetCurrentPos(), 1);
toLower ? LowerCase() : UpperCase();
CharRight();
}
}
int LEditor::LineFromPos(int pos) { return wxStyledTextCtrl::LineFromPosition(pos); }
int LEditor::PosFromLine(int line) { return wxStyledTextCtrl::PositionFromLine(line); }
int LEditor::LineEnd(int line)
{
int pos = wxStyledTextCtrl::PositionFromLine(line);
return pos + wxStyledTextCtrl::LineLength(line);
}
wxString LEditor::GetTextRange(int startPos, int endPos) { return wxStyledTextCtrl::GetTextRange(startPos, endPos); }
void LEditor::DelayedSetActive() { CallAfter(&LEditor::SetActive); }
void LEditor::OnSetActive(wxCommandEvent& e)
{
wxUnusedVar(e);
SetActive();
}
void LEditor::OnFocus(wxFocusEvent& event)
{
m_isFocused = true;
event.Skip();
}
bool LEditor::IsFocused() const
{
#ifdef __WXGTK__
// Under GTK, when popup menu is ON, we will receive a "FocusKill" event
// which means that we lost the focus. So the IsFocused() method is using
// either the m_isFocused flag or the m_popupIsOn flag
return m_isFocused || m_popupIsOn;
#else
return m_isFocused;
#endif
}
void LEditor::ShowCalltip(clCallTipPtr tip)
{
GetFunctionTip()->AddCallTip(tip);
GetFunctionTip()->Highlight(m_context->DoGetCalltipParamterIndex());
// In an ideal world, we would like our tooltip to be placed
// on top of the caret.
wxPoint pt = PointFromPosition(GetCurrentPosition());
GetFunctionTip()->Activate(pt, GetCurrLineHeight(), StyleGetBackground(wxSTC_C_DEFAULT));
}
int LEditor::PositionAfterPos(int pos) { return wxStyledTextCtrl::PositionAfter(pos); }
int LEditor::GetCharAtPos(int pos) { return wxStyledTextCtrl::GetCharAt(pos); }
int LEditor::PositionBeforePos(int pos) { return wxStyledTextCtrl::PositionBefore(pos); }
void LEditor::GetChanges(std::vector<int>& changes) { m_deltas->GetChanges(changes); }
void LEditor::OnFindInFiles() { m_deltas->Clear(); }
void LEditor::OnHighlightWordChecked(wxCommandEvent& e)
{
e.Skip();
// Mainly needed under Mac to toggle the
// buffered drawing on and off
#ifdef __WXMAC__
SetBufferedDraw(e.GetInt() == 1 ? true : false);
// wxLogMessage("Settings buffered drawing to: %d", e.GetInt());
if(e.GetInt()) {
Refresh();
}
#endif
}
void LEditor::PasteLineAbove()
{
// save the current column / line
int curpos = GetCurrentPos();
int col = GetColumn(curpos);
int line = GetCurrentLine();
int pasteLine = line;
if(pasteLine > 0) {
++line;
}
int pastePos = PositionFromLine(pasteLine);
SetCaretAt(pastePos);
Paste();
// restore caret position
int newpos = FindColumn(line, col);
SetCaretAt(newpos);
}
void LEditor::OnKeyUp(wxKeyEvent& event)
{
event.Skip();
if(event.GetKeyCode() == WXK_SHIFT || event.GetKeyCode() == WXK_CONTROL || event.GetKeyCode() == WXK_ALT) {
// Clear hyperlink markers
SetIndicatorCurrent(HYPERLINK_INDICATOR);
IndicatorClearRange(0, GetLength());
// Clear debugger marker
SetIndicatorCurrent(DEBUGGER_INDICATOR);
IndicatorClearRange(0, GetLength());
}
}
size_t LEditor::GetCodeNavModifier()
{
size_t mod = wxMOD_NONE;
if(GetOptions()->GetOptions() & OptionsConfig::Opt_NavKey_Alt)
mod |= wxMOD_ALT;
if(GetOptions()->GetOptions() & OptionsConfig::Opt_NavKey_Control)
mod |= wxMOD_CONTROL;
if(GetOptions()->GetOptions() & OptionsConfig::Opt_NavKey_Shift)
mod |= wxMOD_SHIFT;
return mod;
}
void LEditor::OnFileFormatDone(wxCommandEvent& e)
{
if(e.GetString() != GetFileName().GetFullPath()) {
// not this file
e.Skip();
return;
}
// Restore the markers
DoRestoreMarkers();
}
void LEditor::OnFileFormatStarting(wxCommandEvent& e)
{
if(e.GetString() != GetFileName().GetFullPath()) {
// not this file
e.Skip();
return;
}
DoSaveMarkers();
}
void LEditor::DoRestoreMarkers()
{
MarkerDeleteAll(mmt_all_bookmarks);
for(size_t i = smt_FIRST_BMK_TYPE; i < m_savedMarkers.size(); ++i) {
MarkerAdd(m_savedMarkers.at(i).first, m_savedMarkers.at(i).second);
}
m_savedMarkers.clear();
}
void LEditor::DoSaveMarkers()
{
m_savedMarkers.clear();
int nLine = LineFromPosition(0);
int nFoundLine = MarkerNext(nLine, mmt_all_bookmarks);
while(nFoundLine >= 0) {
for(size_t type = smt_FIRST_BMK_TYPE; type < smt_LAST_BMK_TYPE; ++type) {
int mask = (1 << type);
if(MarkerGet(nLine) & mask) {
m_savedMarkers.push_back(std::make_pair(nFoundLine, type));
}
}
nFoundLine = MarkerNext(nFoundLine + 1, mmt_all_bookmarks);
}
}
void LEditor::InitializeAnnotations()
{
// Warning style
StyleSetBackground(ANNOTATION_STYLE_WARNING, wxColor(255, 215, 0));
StyleSetForeground(ANNOTATION_STYLE_WARNING, *wxBLACK);
StyleSetSizeFractional(ANNOTATION_STYLE_WARNING, (StyleGetSizeFractional(wxSTC_STYLE_DEFAULT) * 4) / 5);
// Error style
StyleSetBackground(ANNOTATION_STYLE_ERROR, wxColour(244, 220, 220));
StyleSetForeground(ANNOTATION_STYLE_ERROR, *wxBLACK);
StyleSetSizeFractional(ANNOTATION_STYLE_ERROR, (StyleGetSizeFractional(wxSTC_STYLE_DEFAULT) * 4) / 5);
// default all line style
AnnotationSetVisible(wxSTC_ANNOTATION_STANDARD);
}
void LEditor::ToggleBreakpointEnablement()
{
int lineno = GetCurrentLine() + 1;
BreakptMgr* bm = ManagerST::Get()->GetBreakpointsMgr();
BreakpointInfo bp = bm->GetBreakpoint(GetFileName().GetFullPath(), lineno);
if(bp.IsNull())
return;
if(!bm->DelBreakpointByLineno(bp.file, bp.lineno))
return;
bp.is_enabled = !bp.is_enabled;
bp.debugger_id = wxNOT_FOUND;
bp.internal_id = bm->GetNextID();
ManagerST::Get()->GetBreakpointsMgr()->AddBreakpoint(bp);
clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
}
void LEditor::DoUpdateTLWTitle(bool raise)
{
// ensure that the top level window parent of this editor is 'Raised'
wxWindow* tlw = ::wxGetTopLevelParent(this);
if(tlw && raise) {
tlw->Raise();
}
if(!IsDetached()) {
clMainFrame::Get()->SetFrameTitle(this);
} else {
wxString title;
title << GetFileName().GetFullPath();
if(GetModify()) {
title.Prepend("*");
}
tlw->SetLabel(title);
}
}
bool LEditor::IsDetached() const
{
const wxWindow* tlw = ::wxGetTopLevelParent(const_cast<LEditor*>(this));
return (tlw && (clMainFrame::Get() != tlw));
}
wxString LEditor::GetWordAtMousePointer()
{
if(GetSelectedText().IsEmpty()) {
wxPoint mousePtInScreenCoord = ::wxGetMousePosition();
wxPoint clientPt = ScreenToClient(mousePtInScreenCoord);
int pos = PositionFromPoint(clientPt);
if(pos != wxNOT_FOUND) {
long start = WordStartPosition(pos, true);
long end = WordEndPosition(pos, true);
return GetTextRange(start, end);
} else {
return "";
}
} else {
return GetSelectedText();
}
}
void LEditor::ShowRichTooltip(const wxString& tip, int pos) { DoShowCalltip(pos, tip); }
wxString LEditor::GetFirstSelection()
{
int nNumSelections = GetSelections();
if(nNumSelections > 1) {
for(int i = 0; i < nNumSelections; ++i) {
int startPos = GetSelectionNStart(i);
int endPos = GetSelectionNEnd(i);
if(endPos > startPos) {
return wxStyledTextCtrl::GetTextRange(startPos, endPos);
}
}
// default
return wxEmptyString;
} else {
return wxStyledTextCtrl::GetSelectedText();
}
}
void LEditor::SetLineVisible(int lineno)
{
int offsetFromTop = 10;
if(lineno != wxNOT_FOUND) {
// try this: set the first visible line to be -10 lines from
// the requested lineNo
lineno -= offsetFromTop;
if(lineno < 0) {
lineno = 0;
}
SetFirstVisibleLine(VisibleFromDocLine(lineno));
// If the line is hidden - expand it
EnsureVisible(lineno);
}
}
|