1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962
|
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// 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 "ColoursAndFontsManager.h"
#include "ServiceProviderManager.h"
#include "addincludefiledlg.h"
#include "bitmap_loader.h"
#include "bookmark_manager.h"
#include "breakpointdlg.h"
#include "buildtabsettingsdata.h"
#include "cc_box_tip_window.h"
#include "clEditorStateLocker.h"
#include "clFileSystemWorkspace.hpp"
#include "clPrintout.h"
#include "clResizableTooltip.h"
#include "clSTCLineKeeper.h"
#include "cl_command_event.h"
#include "cl_editor.h"
#include "cl_editor_tip_window.h"
#include "code_completion_manager.h"
#include "codelite_events.h"
#include "colourrequest.h"
#include "colourthread.h"
#include "context_manager.h"
#include "ctags_manager.h"
#include "debuggerconfigtool.h"
#include "debuggerpane.h"
#include "debuggersettings.h"
#include "drawingutils.h"
#include "editor_config.h"
#include "event_notifier.h"
#include "file_logger.h"
#include "filedroptarget.h"
#include "fileutils.h"
#include "findreplacedlg.h"
#include "findresultstab.h"
#include "frame.h"
#include "globals.h"
#include "imanager.h"
#include "job.h"
#include "jobqueue.h"
#include "lexer_configuration.h"
#include "localworkspace.h"
#include "macromanager.h"
#include "manager.h"
#include "menumanager.h"
#include "new_build_tab.h"
#include "new_quick_watch_dlg.h"
#include "parse_thread.h"
#include "pluginmanager.h"
#include "precompiled_header.h"
#include "quickfindbar.h"
#include "simpletable.h"
#include "stringhighlighterjob.h"
#include "stringsearcher.h"
#include "wxCodeCompletionBoxManager.h"
#include <wx/dataobj.h>
#include <wx/dcmemory.h>
#include <wx/log.h>
#include <wx/printdlg.h>
#include <wx/regex.h>
#include <wx/richtooltip.h> // wxRichToolTip
#include <wx/wupdlock.h>
//#include "clFileOrFolderDropTarget.h"
#if wxUSE_PRINTING_ARCHITECTURE
#include "wx/paper.h"
#endif // wxUSE_PRINTING_ARCHITECTURE
#if defined(USE_UCHARDET)
#include "uchardet/uchardet.h"
#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
// 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[];
wxDEFINE_EVENT(wxCMD_EVENT_REMOVE_MATCH_INDICATOR, wxCommandEvent);
wxDEFINE_EVENT(wxCMD_EVENT_ENABLE_WORD_HIGHLIGHT, wxCommandEvent);
// Instantiate statics
FindReplaceDialog* clEditor::m_findReplaceDlg = NULL;
FindReplaceData clEditor::m_findReplaceData;
std::map<wxString, int> clEditor::ms_bookmarkShapes;
bool clEditor::m_ccShowPrivateMembers = true;
bool clEditor::m_ccShowItemsComments = true;
bool clEditor::m_ccInitialized = false;
wxPrintData* g_printData = NULL;
wxPageSetupDialogData* g_pageSetupData = NULL;
static int ID_OPEN_URL = wxNOT_FOUND;
// This is needed for wxWidgets < 3.1
#ifndef wxSTC_MARK_BOOKMARK
#define wxSTC_MARK_BOOKMARK wxSTC_MARK_LEFTRECT
#endif
static bool IsWordChar(const wxChar& ch)
{
static wxStringSet_t wordsChar;
if(wordsChar.empty()) {
wxString chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.>";
for(size_t i = 0; i < chars.size(); ++i) {
wordsChar.insert(chars[i]);
}
}
return (wordsChar.count(ch) != 0);
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
class clEditorDropTarget : public wxDropTarget
{
wxStyledTextCtrl* m_stc;
public:
clEditorDropTarget(wxStyledTextCtrl* stc)
: m_stc(stc)
{
wxDataObjectComposite* dataobj = new wxDataObjectComposite();
dataobj->Add(new wxTextDataObject(), true);
dataobj->Add(new wxFileDataObject());
SetDataObject(dataobj);
}
/**
* @brief do the actual drop action
* we support both text and file names
*/
wxDragResult OnData(wxCoord x, wxCoord y, wxDragResult defaultDragResult)
{
if(!GetData()) {
return wxDragError;
}
wxDataObjectComposite* dataobjComp = static_cast<wxDataObjectComposite*>(GetDataObject());
if(!dataobjComp)
return wxDragError;
wxDataFormat format = dataobjComp->GetReceivedFormat();
wxDataObject* dataobj = dataobjComp->GetObject(format);
switch(format.GetType()) {
case wxDF_FILENAME: {
wxFileDataObject* fileNameObj = static_cast<wxFileDataObject*>(dataobj);
DoFilesDrop(fileNameObj->GetFilenames());
} break;
case wxDF_UNICODETEXT: {
wxTextDataObject* textObj = static_cast<wxTextDataObject*>(dataobj);
wxString text = textObj->GetText();
#ifdef __WXOSX__
// On OSX, textObj->GetText() returns some garbeled text
// so use the editor to get the text that we want to copy/move
text = m_stc->GetSelectedText();
#endif
if(!DoTextDrop(text, x, y, (defaultDragResult == wxDragMove))) {
return wxDragCancel;
}
} break;
default:
break;
}
return defaultDragResult;
}
/**
* @brief open list of files in the editor
*/
bool DoTextDrop(const wxString& text, wxCoord x, wxCoord y, bool moving)
{
// insert the text
int pos = m_stc->PositionFromPoint(wxPoint(x, y));
if(pos == wxNOT_FOUND)
return false;
// Don't allow dropping tabs on the editor
static wxRegEx re("\\{Class:Notebook,TabIndex:([0-9]+)\\}\\{.*?\\}", wxRE_ADVANCED);
if(re.Matches(text))
return false;
int selStart = m_stc->GetSelectionStart();
int selEnd = m_stc->GetSelectionEnd();
// No text dnd if the drop is on the selection
if((pos >= selStart) && (pos <= selEnd))
return false;
int length = (selEnd - selStart);
m_stc->BeginUndoAction();
if(moving) {
// Clear the selection
bool movingForward = (pos > selEnd);
m_stc->InsertText(pos, text);
if(movingForward) {
m_stc->Replace(selStart, selEnd, "");
pos -= length;
} else {
m_stc->Replace(selStart + length, selEnd + length, "");
}
m_stc->SetSelectionStart(pos);
m_stc->SetSelectionEnd(pos);
m_stc->SetCurrentPos(pos);
} else {
m_stc->SelectNone();
m_stc->SetSelectionStart(pos);
m_stc->SetSelectionEnd(pos);
m_stc->InsertText(pos, text);
m_stc->SetCurrentPos(pos);
}
m_stc->EndUndoAction();
#ifndef __WXOSX__
m_stc->CallAfter(&wxStyledTextCtrl::SetSelection, pos, pos + length);
#endif
return true;
}
/**
* @brief open list of files in the editor
*/
void DoFilesDrop(const wxArrayString& filenames)
{
// Split the list into 2: files and folders
wxArrayString files, folders;
for(size_t i = 0; i < filenames.size(); ++i) {
if(wxFileName::DirExists(filenames.Item(i))) {
folders.Add(filenames.Item(i));
} else {
files.Add(filenames.Item(i));
}
}
for(size_t i = 0; i < files.size(); ++i) {
clMainFrame::Get()->GetMainBook()->OpenFile(files.Item(i));
}
}
bool OnDrop(wxCoord x, wxCoord y) { return true; }
wxDragResult OnDragOver(wxCoord x, wxCoord y, wxDragResult defResult) { return m_stc->DoDragOver(x, y, defResult); }
};
//=====================================================================
#if defined(__WXMSW__)
static bool MSWRemoveROFileAttribute(const wxFileName& fileName)
{
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\n%s"), fileName.GetFullPath(),
_("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;
}
}
}
return true;
}
#endif
//=====================================================================
clEditor::clEditor(wxWindow* parent)
: m_popupIsOn(false)
, m_isDragging(false)
, m_modifyTime(0)
, m_modificationCount(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_calltip(NULL)
, m_lastCharEntered(0)
, m_lastCharEnteredPos(0)
, m_isFocused(true)
, m_pluginInitializedRMenu(false)
, m_positionToEnsureVisible(wxNOT_FOUND)
, m_findBookmarksActive(false)
, m_mgr(PluginManager::Get())
, m_hasCCAnnotation(false)
, m_richTooltip(NULL)
, m_lastEndLine(0)
, m_lastLineCount(0)
{
Hide();
#ifdef __WXGTK3__
wxStyledTextCtrl::Create(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_DEFAULT);
#else
wxStyledTextCtrl::Create(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNO_BORDER);
#endif
MSWSetWindowDarkTheme(this);
Bind(wxEVT_STC_CHARADDED, &clEditor::OnCharAdded, this);
Bind(wxEVT_STC_MARGINCLICK, &clEditor::OnMarginClick, this);
Bind(wxEVT_STC_CALLTIP_CLICK, &clEditor::OnCallTipClick, this);
Bind(wxEVT_STC_DWELLEND, &clEditor::OnDwellEnd, this);
Bind(wxEVT_STC_START_DRAG, &clEditor::OnDragStart, this);
Bind(wxEVT_STC_DO_DROP, &clEditor::OnDragEnd, this);
Bind(wxEVT_STC_UPDATEUI, &clEditor::OnSciUpdateUI, this);
Bind(wxEVT_STC_SAVEPOINTREACHED, &clEditor::OnSavePoint, this);
Bind(wxEVT_STC_SAVEPOINTLEFT, &clEditor::OnSavePoint, this);
Bind(wxEVT_STC_MODIFIED, &clEditor::OnChange, this);
Bind(wxEVT_CONTEXT_MENU, &clEditor::OnContextMenu, this);
Bind(wxEVT_KEY_DOWN, &clEditor::OnKeyDown, this);
Bind(wxEVT_KEY_UP, &clEditor::OnKeyUp, this);
Bind(wxEVT_LEFT_DOWN, &clEditor::OnLeftDown, this);
Bind(wxEVT_RIGHT_DOWN, &clEditor::OnRightDown, this);
Bind(wxEVT_MOTION, &clEditor::OnMotion, this);
Bind(wxEVT_MOUSEWHEEL, &clEditor::OnMouseWheel, this);
Bind(wxEVT_LEFT_UP, &clEditor::OnLeftUp, this);
Bind(wxEVT_LEAVE_WINDOW, &clEditor::OnLeaveWindow, this);
Bind(wxEVT_KILL_FOCUS, &clEditor::OnFocusLost, this);
Bind(wxEVT_SET_FOCUS, &clEditor::OnFocus, this);
Bind(wxEVT_STC_DOUBLECLICK, &clEditor::OnLeftDClick, this);
Bind(wxEVT_FRD_FIND_NEXT, &clEditor::OnFindDialog, this);
Bind(wxEVT_FRD_REPLACE, &clEditor::OnFindDialog, this);
Bind(wxEVT_FRD_REPLACEALL, &clEditor::OnFindDialog, this);
Bind(wxEVT_FRD_BOOKMARKALL, &clEditor::OnFindDialog, this);
Bind(wxEVT_FRD_CLOSE, &clEditor::OnFindDialog, this);
Bind(wxEVT_FRD_CLEARBOOKMARKS, &clEditor::OnFindDialog, this);
Bind(wxCMD_EVENT_REMOVE_MATCH_INDICATOR, &clEditor::OnRemoveMatchInidicator, this);
Bind(wxEVT_STC_ZOOM, &clEditor::OnZoom, this);
DoUpdateOptions();
PreferencesChanged();
EventNotifier::Get()->Bind(wxEVT_EDITOR_CONFIG_CHANGED, &clEditor::OnEditorConfigChanged, this);
m_commandsProcessor.SetParent(this);
SetDropTarget(new clEditorDropTarget(this));
// User timer to check if we need to highlight markers
m_timerHighlightMarkers = new wxTimer(this);
m_timerHighlightMarkers->Start(100, true);
Connect(m_timerHighlightMarkers->GetId(), wxEVT_TIMER, wxTimerEventHandler(clEditor::OnTimer), NULL, 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;
ms_bookmarkShapes[wxT("Bookmark")] = wxSTC_MARK_BOOKMARK;
SetSyntaxHighlight();
CmdKeyClear(wxT('D'), wxSTC_KEYMOD_CTRL); // clear Ctrl+D because we use it for something else
Connect(wxEVT_STC_DWELLSTART, wxStyledTextEventHandler(clEditor::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(clEditor::OnHighlightWordChecked), NULL, this);
EventNotifier::Get()->Connect(wxEVT_CODEFORMATTER_INDENT_STARTING,
wxCommandEventHandler(clEditor::OnFileFormatStarting), NULL, this);
EventNotifier::Get()->Connect(wxEVT_CODEFORMATTER_INDENT_COMPLETED,
wxCommandEventHandler(clEditor::OnFileFormatDone), NULL, this);
Bind(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(clEditor::OnChangeActiveBookmarkType), this,
XRCID("BookmarkTypes[start]"), XRCID("BookmarkTypes[end]"));
// Notify that this instance is being instantiated
clCommandEvent initEvent(wxEVT_EDITOR_INITIALIZING);
initEvent.SetEventObject(this);
EventNotifier::Get()->AddPendingEvent(initEvent);
}
clEditor::~clEditor()
{
// Report file-close event
if(GetFileName().IsOk() && GetFileName().FileExists()) {
clCommandEvent eventClose(wxEVT_FILE_CLOSED);
eventClose.SetFileName(GetFileName().GetFullPath());
EventNotifier::Get()->AddPendingEvent(eventClose);
}
wxDELETE(m_richTooltip);
EventNotifier::Get()->Unbind(wxEVT_EDITOR_CONFIG_CHANGED, &clEditor::OnEditorConfigChanged, this);
EventNotifier::Get()->Disconnect(wxCMD_EVENT_ENABLE_WORD_HIGHLIGHT,
wxCommandEventHandler(clEditor::OnHighlightWordChecked), NULL, this);
EventNotifier::Get()->Disconnect(wxEVT_CODEFORMATTER_INDENT_STARTING,
wxCommandEventHandler(clEditor::OnFileFormatStarting), NULL, this);
EventNotifier::Get()->Disconnect(wxEVT_CODEFORMATTER_INDENT_COMPLETED,
wxCommandEventHandler(clEditor::OnFileFormatDone), NULL, this);
Unbind(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(clEditor::OnChangeActiveBookmarkType), this,
XRCID("BookmarkTypes[start]"), XRCID("BookmarkTypes[end]"));
// free the timer
Disconnect(m_timerHighlightMarkers->GetId(), wxEVT_TIMER, wxTimerEventHandler(clEditor::OnTimer), NULL, this);
m_timerHighlightMarkers->Stop();
wxDELETE(m_timerHighlightMarkers);
// find deltas
wxDELETE(m_deltas);
if(this->HasCapture()) {
this->ReleaseMouse();
}
}
time_t clEditor::GetFileLastModifiedTime() const { return GetFileModificationTime(m_fileName.GetFullPath()); }
void clEditor::SetSyntaxHighlight(const wxString& lexerName)
{
ClearDocumentStyle();
m_context = ContextManager::Get()->NewContext(this, lexerName);
// Apply the lexer fonts and colours before we call
// "SetProperties". (SetProperties function needs the correct font for
// some of its settings)
LexerConf::Ptr_t lexer = ColoursAndFontsManager::Get().GetLexer(lexerName);
if(lexer) {
lexer->Apply(this);
}
SetProperties();
SetEOL();
m_context->SetActive();
m_context->ApplySettings();
UpdateColours();
}
void clEditor::SetSyntaxHighlight(bool bUpdateColors)
{
ClearDocumentStyle();
m_context = ContextManager::Get()->NewContextByFileName(this, m_fileName);
SetProperties();
m_context->SetActive();
m_context->ApplySettings();
if(bUpdateColors) {
UpdateColours();
}
}
// Fills the struct array that marries breakpoint type to marker and mask
void clEditor::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 clEditor::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;
}
}
clLogMessage(wxT("Breakpoint type not in vector!?"));
return *iter;
}
void clEditor::SetCaretAt(long pos)
{
DoSetCaretAt(pos);
CallAfter(&clEditor::EnsureCaretVisible);
}
/// Setup some scintilla properties
void clEditor::SetProperties()
{
#ifndef __WXMSW__
UsePopUp(false);
#else
UsePopUp(0);
#endif
SetRectangularSelectionModifier(wxSTC_KEYMOD_CTRL);
SetAdditionalSelectionTyping(true);
OptionsConfigPtr options = GetOptions();
CallTipUseStyle(1);
int lineSpacing = clConfig::Get().Read("extra_line_spacing", (int)0);
SetExtraAscent(lineSpacing);
SetExtraDescent(lineSpacing);
CallTipSetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK));
CallTipSetForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOTEXT));
MarkerEnableHighlight(options->IsHighlightFoldWhenActive());
m_hightlightMatchedBraces = options->GetHighlightMatchedBraces();
m_autoAddMatchedCurlyBrace = options->GetAutoAddMatchedCurlyBraces();
m_autoAddNormalBraces = options->GetAutoAddMatchedNormalBraces();
m_smartParen = options->IsSmartParen();
m_autoAdjustHScrollbarWidth = options->GetAutoAdjustHScrollBarWidth();
m_disableSmartIndent = options->GetDisableSmartIndent();
m_disableSemicolonShift = options->GetDisableSemicolonShift();
SetMultipleSelection(true);
SetMultiPaste(1);
if(!m_hightlightMatchedBraces) {
wxStyledTextCtrl::BraceHighlight(wxSTC_INVALID_POSITION, wxSTC_INVALID_POSITION);
SetHighlightGuide(0);
}
SetVirtualSpaceOptions(options->GetOptions() & OptionsConfig::Opt_AllowCaretAfterEndOfLine ? 2 : 1);
SetCaretStyle(options->GetOptions() & OptionsConfig::Opt_UseBlockCaret ? wxSTC_CARETSTYLE_BLOCK
: wxSTC_CARETSTYLE_LINE);
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"));
// Fold and comments as well
SetProperty(wxT("fold.comment"), wxT("1"));
SetProperty("fold.hypertext.comment", "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);
// Set the caret width
int caretWidth = clConfig::Get().Read("editor/caret_width", 2);
caretWidth = ::clGetSize(caretWidth, this);
SetCaretWidth(caretWidth);
SetCaretPeriod(options->GetCaretBlinkPeriod());
SetMarginLeft(1);
// Mark current line
SetCaretLineVisible(options->GetHighlightCaretLine());
SetCaretLineBackground(options->GetCaretLineColour());
SetCaretLineBackAlpha(options->GetCaretLineAlpha());
SetFoldFlags(options->GetUnderlineFoldLine()
? wxSTC_FOLDFLAG_LINEAFTER_CONTRACTED | wxSTC_FOLDFLAG_LINEBEFORE_CONTRACTED
: 0);
SetEndAtLastLine(!options->GetScrollBeyondLastLine());
//------------------------------------------
// Margin settings
//------------------------------------------
// symbol margin
SetMarginType(SYMBOLS_MARGIN_ID, wxSTC_MARGIN_SYMBOL);
// Line numbers
if(options->GetRelativeLineNumbers()) {
SetMarginType(NUMBER_MARGIN_ID, wxSTC_MARGIN_RTEXT);
} else {
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 | mmt_line_marker));
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
#if wxCHECK_VERSION(3, 1, 0)
SetMarginType(SYMBOLS_MARGIN_SEP_ID, wxSTC_MARGIN_COLOUR);
SetMarginMask(SYMBOLS_MARGIN_SEP_ID, 0);
SetMarginWidth(SYMBOLS_MARGIN_SEP_ID, clGetSize(1, this));
wxColour bgColour = StyleGetBackground(0);
SetMarginBackground(SYMBOLS_MARGIN_SEP_ID,
DrawingUtils::IsDark(bgColour) ? bgColour.ChangeLightness(120) : bgColour.ChangeLightness(60));
#else
SetMarginType(SYMBOLS_MARGIN_SEP_ID, wxSTC_MARGIN_FORE);
SetMarginMask(SYMBOLS_MARGIN_SEP_ID, 0);
// Show the separator margin only if the fold margin is hidden
// (otherwise the fold margin is the separator)
SetMarginWidth(SYMBOLS_MARGIN_SEP_ID,
(GetLexer() == wxSTC_LEX_CPP && FileExtManager::IsCxxFile(GetFileName())) ? 1 : 0);
#endif
// Fold margin - allow only folder symbols to display
SetMarginMask(FOLD_MARGIN_ID, wxSTC_MASK_FOLDERS);
// Set margins' width
SetMarginWidth(SYMBOLS_MARGIN_ID, options->GetDisplayBookmarkMargin() ? clGetSize(16, this) : 0); // Symbol margin
// allow everything except for the folding symbols
SetMarginMask(SYMBOLS_MARGIN_ID, ~(wxSTC_MASK_FOLDERS));
// Show number margin according to settings.
UpdateLineNumberMarginWidth();
// Show the fold margin
SetMarginWidth(FOLD_MARGIN_ID, options->GetDisplayFoldMargin() ? clGetSize(16, this) : 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
//---------------------------------------------------
// Determine the folding symbols colours
wxColour foldFgColour = wxColor(0xff, 0xff, 0xff);
wxColour foldBgColour = wxColor(0x80, 0x80, 0x80);
LexerConf::Ptr_t lexer = ColoursAndFontsManager::Get().GetLexer(GetContext()->GetName());
if(lexer) {
const StyleProperty& sp = lexer->GetProperty(SEL_TEXT_ATTR_ID);
m_selTextBgColour = sp.GetBgColour();
m_selTextColour = sp.GetFgColour();
} else {
m_selTextBgColour = StyleGetBackground(0);
m_selTextColour = StyleGetForeground(0);
}
MarkerDefine(smt_line_marker, wxSTC_MARK_LEFTRECT, StyleGetForeground(0));
if(lexer && lexer->IsDark()) {
const StyleProperty& defaultProperty = lexer->GetProperty(0);
if(!defaultProperty.IsNull()) {
foldFgColour = wxColour(defaultProperty.GetBgColour()).ChangeLightness(130);
foldBgColour = wxColour(defaultProperty.GetBgColour());
}
} else if(lexer) {
const StyleProperty& defaultProperty = lexer->GetProperty(0);
if(!defaultProperty.IsNull()) {
foldFgColour = wxColour(defaultProperty.GetBgColour()).ChangeLightness(70);
foldBgColour = wxColour(defaultProperty.GetBgColour());
}
}
// Define the folding style to be square
if(options->GetFoldStyle() == wxT("Flatten Tree Square Headers")) {
DefineMarker(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_BOXMINUS, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_BOXPLUS, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_VLINE, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_LCORNER, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_BOXPLUSCONNECTED, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_BOXMINUSCONNECTED, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_TCORNER, foldFgColour, foldBgColour);
} else if(options->GetFoldStyle() == wxT("Flatten Tree Circular Headers")) {
DefineMarker(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_CIRCLEMINUS, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_CIRCLEPLUS, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_VLINE, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_LCORNERCURVE, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_CIRCLEPLUSCONNECTED, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_CIRCLEMINUSCONNECTED, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_TCORNER, foldFgColour, foldBgColour);
} else if(options->GetFoldStyle() == wxT("Simple")) {
DefineMarker(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_MINUS, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_PLUS, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_BACKGROUND, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_BACKGROUND, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_PLUS, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_MINUS, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_BACKGROUND, foldFgColour, foldBgColour);
} else { // use wxT("Arrows") as the default
DefineMarker(wxSTC_MARKNUM_FOLDEROPEN, wxSTC_MARK_ARROWDOWN, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDER, wxSTC_MARK_ARROW, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERSUB, wxSTC_MARK_BACKGROUND, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERTAIL, wxSTC_MARK_BACKGROUND, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDEREND, wxSTC_MARK_ARROW, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDEROPENMID, wxSTC_MARK_ARROWDOWN, foldFgColour, foldBgColour);
DefineMarker(wxSTC_MARKNUM_FOLDERMIDTAIL, wxSTC_MARK_BACKGROUND, foldFgColour, foldBgColour);
}
// Bookmark
int marker = wxSTC_MARK_BOOKMARK;
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));
}
// Breakpoints
for(size_t bmt = smt_FIRST_BP_TYPE; bmt <= smt_LAST_BP_TYPE; ++bmt) {
MarkerSetBackground(smt_breakpoint, "RED");
MarkerSetAlpha(smt_breakpoint, 30);
}
wxBitmap breakpointBmp = clGetManager()->GetStdIcons()->LoadBitmap("breakpoint");
wxBitmap breakpointCondBmp = clGetManager()->GetStdIcons()->LoadBitmap("breakpoint_cond");
wxBitmap breakpointCmdList = clGetManager()->GetStdIcons()->LoadBitmap("breakpoint_cmdlist");
wxBitmap breakpointIgnored = clGetManager()->GetStdIcons()->LoadBitmap("breakpoint_ignored");
wxColour breakpointColour = wxColour("#FF5733");
wxColour disabledColour = breakpointColour.ChangeLightness(165);
wxColour defaultBgColour = StyleGetBackground(0); // Default style background colour
MarkerDefine(smt_breakpoint, wxSTC_MARK_CIRCLE);
this->MarkerSetBackground(smt_breakpoint, breakpointColour);
this->MarkerSetForeground(smt_breakpoint, breakpointColour);
MarkerDefine(smt_bp_disabled, wxSTC_MARK_CIRCLE);
this->MarkerSetBackground(smt_bp_disabled, disabledColour);
this->MarkerSetForeground(smt_bp_disabled, disabledColour);
MarkerDefine(smt_bp_cmdlist, wxSTC_MARK_CHARACTER + 33); // !
this->MarkerSetBackground(smt_bp_cmdlist, breakpointColour);
this->MarkerSetForeground(smt_bp_cmdlist, breakpointColour);
MarkerDefine(smt_bp_cmdlist_disabled, wxSTC_MARK_CHARACTER + 33); // !
this->MarkerSetForeground(smt_bp_cmdlist, disabledColour);
this->MarkerSetBackground(smt_bp_cmdlist, defaultBgColour);
MarkerDefine(smt_bp_ignored, wxSTC_MARK_CHARACTER + 105); // i
this->MarkerSetForeground(smt_bp_ignored, breakpointColour);
this->MarkerSetBackground(smt_bp_ignored, defaultBgColour);
MarkerDefine(smt_cond_bp, wxSTC_MARK_CHARACTER + 63); // ?
this->MarkerSetForeground(smt_cond_bp, breakpointColour);
this->MarkerSetBackground(smt_cond_bp, defaultBgColour);
MarkerDefine(smt_cond_bp_disabled, wxSTC_MARK_CHARACTER + 63); // ?
this->MarkerSetForeground(smt_cond_bp_disabled, disabledColour);
this->MarkerSetBackground(smt_cond_bp_disabled, defaultBgColour);
if(options->HasOption(OptionsConfig::Opt_Mark_Debugger_Line)) {
MarkerDefine(smt_indicator, wxSTC_MARK_BACKGROUND, wxNullColour, options->GetDebuggerMarkerLine());
MarkerSetAlpha(smt_indicator, 50);
} else {
MarkerDefine(smt_indicator, wxSTC_MARK_SHORTARROW);
wxColour debuggerMarkerColour(136, 170, 0);
MarkerSetBackground(smt_indicator, debuggerMarkerColour);
MarkerSetForeground(smt_indicator, debuggerMarkerColour.ChangeLightness(50));
}
// 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(true);
SetLayoutCache(wxSTC_CACHE_DOCUMENT);
#elif defined(__WXGTK__)
// SetLayoutCache(wxSTC_CACHE_PAGE);
#else // MSW
SetTwoPhaseDraw(true);
SetBufferedDraw(true);
SetLayoutCache(wxSTC_CACHE_PAGE);
#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
SetUseTabs((GetContext()->GetName().Lower() == "makefile") ? true : options->GetIndentUsesTabs());
SetTabWidth(options->GetTabWidth());
SetIndent(options->GetIndentWidth());
SetIndentationGuides(options->GetShowIndentationGuidelines() ? 3 : 0);
size_t frame_flags = clMainFrame::Get()->GetFrameGeneralInfo().GetFlags();
SetViewEOL(frame_flags & CL_SHOW_EOL ? true : false);
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()->GetString(wxT("WordHighlightColour"));
if(val2.IsEmpty() == false) {
col2 = wxColour(val2);
}
IndicatorSetForeground(1, options->GetBookmarkBgColour(smt_find_bookmark - smt_FIRST_BMK_TYPE));
IndicatorSetUnder(MARKER_WORD_HIGHLIGHT, true);
IndicatorSetForeground(MARKER_WORD_HIGHLIGHT, col2);
long alpha = EditorConfigST::Get()->GetInteger(wxT("WordHighlightAlpha"));
if(alpha != wxNOT_FOUND) {
IndicatorSetAlpha(MARKER_WORD_HIGHLIGHT, alpha);
}
IndicatorSetUnder(MARKER_FIND_BAR_WORD_HIGHLIGHT, true);
IndicatorSetStyle(MARKER_FIND_BAR_WORD_HIGHLIGHT, wxSTC_INDIC_BOX);
bool isDarkTheme = (lexer && lexer->IsDark());
IndicatorSetForeground(MARKER_FIND_BAR_WORD_HIGHLIGHT, isDarkTheme ? "WHITE" : "BLACK");
if(alpha != wxNOT_FOUND) {
IndicatorSetAlpha(MARKER_FIND_BAR_WORD_HIGHLIGHT, alpha);
}
IndicatorSetUnder(MARKER_CONTEXT_WORD_HIGHLIGHT, true);
IndicatorSetStyle(MARKER_CONTEXT_WORD_HIGHLIGHT, wxSTC_INDIC_BOX);
IndicatorSetForeground(MARKER_CONTEXT_WORD_HIGHLIGHT, isDarkTheme ? "WHITE" : "BLACK");
if(alpha != wxNOT_FOUND) {
IndicatorSetAlpha(MARKER_CONTEXT_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_KEYMOD_CTRL); // clear Ctrl+D because we use it for something else
// Set CamelCase caret movement
if(options->GetCaretUseCamelCase()) {
// selection
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_KEYMOD_CTRL | wxSTC_KEYMOD_SHIFT, wxSTC_CMD_WORDPARTLEFTEXTEND);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_KEYMOD_CTRL | wxSTC_KEYMOD_SHIFT, wxSTC_CMD_WORDPARTRIGHTEXTEND);
// movement
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_KEYMOD_CTRL, wxSTC_CMD_WORDPARTLEFT);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_KEYMOD_CTRL, wxSTC_CMD_WORDPARTRIGHT);
} else {
// selection
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_KEYMOD_CTRL | wxSTC_KEYMOD_SHIFT, wxSTC_CMD_WORDLEFTEXTEND);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_KEYMOD_CTRL | wxSTC_KEYMOD_SHIFT, wxSTC_CMD_WORDRIGHTEXTEND);
// movement
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_KEYMOD_CTRL, wxSTC_CMD_WORDLEFT);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_KEYMOD_CTRL, wxSTC_CMD_WORDRIGHT);
}
#ifdef __WXOSX__
CmdKeyAssign(wxSTC_KEY_DOWN, wxSTC_KEYMOD_CTRL, wxSTC_CMD_DOCUMENTEND);
CmdKeyAssign(wxSTC_KEY_UP, wxSTC_KEYMOD_CTRL, wxSTC_CMD_DOCUMENTSTART);
// OSX: wxSTC_KEYMOD_CTRL => CMD key
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_KEYMOD_CTRL, wxSTC_CMD_LINEEND);
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_KEYMOD_CTRL, wxSTC_CMD_HOME);
// OSX: wxSTC_KEYMOD_META => CONTROL key
CmdKeyAssign(wxSTC_KEY_LEFT, wxSTC_KEYMOD_META, wxSTC_CMD_WORDPARTLEFT);
CmdKeyAssign(wxSTC_KEY_RIGHT, wxSTC_KEYMOD_META, wxSTC_CMD_WORDPARTRIGHT);
#endif
}
void clEditor::OnSavePoint(wxStyledTextEvent& event)
{
if(!GetIsVisible())
return;
wxString title;
if(!GetModify()) {
if(GetMarginWidth(EDIT_TRACKER_MARGIN_ID)) {
wxWindowUpdateLocker locker(this);
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();
}
}
clMainFrame::Get()->GetMainBook()->SetPageTitle(this, GetFileName(), GetModify());
DoUpdateTLWTitle(false);
}
void clEditor::OnCharAdded(wxStyledTextEvent& event)
{
bool hasSingleCaret = (GetSelections() == 1);
OptionsConfigPtr options = GetOptions();
if(m_prevSelectionInfo.IsOk()) {
if(event.GetKey() == '"' && options->IsWrapSelectionWithQuotes()) {
DoWrapPrevSelectionWithChars('"', '"');
return;
} else if(event.GetKey() == '[' && options->IsWrapSelectionBrackets()) {
DoWrapPrevSelectionWithChars('[', ']');
return;
} else if(event.GetKey() == '\'' && options->IsWrapSelectionWithQuotes()) {
DoWrapPrevSelectionWithChars('\'', '\'');
return;
} else if(event.GetKey() == '(' && options->IsWrapSelectionBrackets()) {
DoWrapPrevSelectionWithChars('(', ')');
return;
}
}
// reset the flag
m_prevSelectionInfo.Clear();
bool addClosingBrace = m_autoAddNormalBraces && hasSingleCaret;
bool addClosingDoubleQuotes = options->GetAutoCompleteDoubleQuotes() && hasSingleCaret;
int pos = GetCurrentPos();
bool canShowCompletionBox(true);
// make sure line is visible
int curLine = LineFromPosition(pos);
if(!GetFoldExpanded(curLine)) {
DoToggleFold(curLine, "...");
}
bool bJustAddedIndicator = false;
int nextChar = SafeGetChar(pos), prevChar = SafeGetChar(pos - 2);
//-------------------------------------
// Smart quotes management
//-------------------------------------
if(addClosingDoubleQuotes) {
if((event.GetKey() == '"' || event.GetKey() == '\'') && event.GetKey() == GetCharAt(pos)) {
CharRight();
DeleteBack();
} else if(!wxIsalnum(nextChar) && !wxIsalnum(prevChar)) {
// 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''_
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;
}
}
}
//-------------------------------------
// Smart quotes management
//-------------------------------------
if(!bJustAddedIndicator && IndicatorValueAt(MATCH_INDICATOR, pos) && event.GetKey() == GetCharAt(pos)) {
CharRight();
DeleteBack();
} else if(m_smartParen && (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 '@': // PHP / Java document style
case '\\': // Qt Style
if(m_context->IsAtBlockComment()) {
m_context->BlockCommentComplete();
}
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
matchChar = '}';
BeginUndoAction();
// Check to see if there are more chars on the line
int curline = GetCurrentLine();
// get the line end position, but without the EOL
int lineEndPos = LineEnd(curline) - GetEolString().length();
wxString restOfLine = GetTextRange(pos, lineEndPos);
wxString restOfLineTrimmed = restOfLine;
restOfLineTrimmed.Trim().Trim(false);
bool shiftCode = (!restOfLineTrimmed.StartsWith(")")) && (!restOfLineTrimmed.IsEmpty());
if(shiftCode) {
SetSelection(pos, lineEndPos);
ReplaceSelection("");
}
InsertText(pos, matchChar);
CharRight();
m_context->AutoIndent(wxT('}'));
InsertText(pos, GetEolString());
CharRight();
SetCaretAt(pos);
if(shiftCode) {
// restore the content that we just removed
InsertText(pos, restOfLine);
}
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()->IsStringTriggerCodeComplete(strTyped) || GetContext()->IsStringTriggerCodeComplete(strTyped2)) &&
!GetContext()->IsCommentOrString(GetCurrentPos())) {
// this char should trigger a code completion
CallAfter(&clEditor::CodeComplete, false);
}
if(matchChar && !m_disableSmartIndent && !m_context->IsCommentOrString(pos)) {
if(matchChar == ')' && addClosingBrace) {
// 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 != '}' && addClosingBrace) {
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()) {
// We need to use here 'CallAfter' since the style is not updated until next Paint
CallAfter(&clEditor::CompleteWord, LSP::CompletionItem::kTriggerKindInvoked, false);
}
}
}
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 clEditor::SetEnsureCaretIsVisible(int pos, bool preserveSelection /*=true*/, bool forceDelay /*=false*/)
{
wxUnusedVar(forceDelay);
DoEnsureCaretIsVisible(pos, preserveSelection);
// 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 clEditor::OnScnPainted(wxStyledTextEvent& event)
{
event.Skip();
if(m_positionToEnsureVisible == wxNOT_FOUND) {
return;
}
DoEnsureCaretIsVisible(m_positionToEnsureVisible, m_preserveSelection);
m_positionToEnsureVisible = wxNOT_FOUND;
}
void clEditor::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 clEditor::OnSciUpdateUI(wxStyledTextEvent& event)
{
event.Skip();
// Update the line numbers if needed (only when using custom drawing line numbers)
UpdateLineNumbers();
// 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);
int selectionSize = std::abs(GetSelectionEnd() - GetSelectionStart());
if(GetHighlightGuide() != wxNOT_FOUND) {
SetHighlightGuide(0);
}
if(m_hightlightMatchedBraces) {
if(selectionSize) {
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 mainSelectionPos = GetSelectionNCaret(GetMainSelection());
int curLine = LineFromPosition(mainSelectionPos);
wxString message;
if(m_statusBarFields & kShowLine) {
message << "Ln " << curLine + 1;
}
if(m_statusBarFields & kShowColumn) {
message << (!message.empty() ? ", " : "") << "Col " << GetColumn(mainSelectionPos);
}
if(m_statusBarFields & kShowPosition) {
message << (!message.empty() ? ", " : "") << "Pos " << mainSelectionPos;
}
if(m_statusBarFields & kShowLen) {
message << (!message.empty() ? ", " : "") << "Len " << GetLength();
}
if((m_statusBarFields & kShowSelectedChars) && selectionSize) {
message << (!message.empty() ? ", " : "") << "Sel " << selectionSize;
}
// Always update the status bar with event, calling it directly causes performance degredation
m_mgr->GetStatusBar()->SetLinePosColumn(message);
SetIndicatorCurrent(MATCH_INDICATOR);
IndicatorClearRange(0, pos);
int end = PositionFromLine(curLine + 1);
if(end >= pos && end < GetTextLength()) {
IndicatorClearRange(end, GetTextLength() - end);
}
RecalcHorizontalScrollbar();
// get the current position
if((curLine != m_lastLine) && clMainFrame::Get()->GetMainBook()->IsNavBarShown()) {
clCodeCompletionEvent evtUpdateNavBar(wxEVT_CC_UPDATE_NAVBAR);
evtUpdateNavBar.SetEditor(this);
evtUpdateNavBar.SetLineNumber(curLine);
EventNotifier::Get()->AddPendingEvent(evtUpdateNavBar);
}
// let the context handle this as well
m_context->OnSciUpdateUI(event);
// TODO:: mark the current line
// Keep the last line
m_lastLine = curLine;
}
void clEditor::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));
}
// 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
{
DoToggleFold(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 clEditor::DefineMarker(int marker, int markerType, wxColor fore, wxColor back)
{
MarkerDefine(marker, markerType);
MarkerSetForeground(marker, fore);
MarkerSetBackground(marker, back);
}
bool clEditor::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);
// Take a snapshot of the current deltas. We'll need this as a 'base' for any future FindInFiles call
m_deltas->OnFileSaved();
if(::clIsCxxWorkspaceOpened()) {
// 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 clEditor::SaveFileAs(const wxString& newname, const wxString& savePath)
{
// Prompt the user for a new file name
const wxString ALL(wxT("All Files (*)|*"));
wxFileDialog dlg(this, _("Save As"), savePath.IsEmpty() ? m_fileName.GetPath() : savePath,
newname.IsEmpty() ? m_fileName.GetFullName() : newname, ALL, wxFD_SAVE | wxFD_OVERWRITE_PROMPT,
wxDefaultPosition);
if(dlg.ShowModal() == wxID_OK) {
// get the path
wxFileName name(dlg.GetPath());
// Prepare the "SaveAs" event, but dont send it just yet
clFileSystemEvent saveAsEvent(wxEVT_FILE_SAVEAS);
saveAsEvent.SetPath(m_fileName.Exists() ? m_fileName.GetFullPath() : wxString(""));
saveAsEvent.SetNewpath(name.GetFullPath());
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, false);
DoUpdateTLWTitle(false);
// update syntax highlight
SetSyntaxHighlight();
clMainFrame::Get()->GetMainBook()->MarkEditorReadOnly(this);
// Fire the "File renamed" event
EventNotifier::Get()->AddPendingEvent(saveAsEvent);
return true;
}
return false;
}
// an internal function that does the actual file writing to disk
bool clEditor::SaveToFile(const wxFileName& fileName)
{
{
// Notify about file being saved
clCommandEvent beforeSaveEvent(wxEVT_BEFORE_EDITOR_SAVE);
beforeSaveEvent.SetFileName(fileName.GetFullPath());
EventNotifier::Get()->ProcessEvent(beforeSaveEvent);
if(!beforeSaveEvent.IsAllowed()) {
// A plugin vetoed the file save
return false;
}
}
// Do all the writing on the temporary file
wxFileName intermediateFile(fileName);
intermediateFile.SetFullName("~" + fileName.GetFullName() + "." + ::wxGetUserId());
{
// Ensure that a temporary file with this name does not exist
FileUtils::Deleter deleter(intermediateFile);
}
// Ensure that the temporary file that we will be creating
// is removed when leaving the function
FileUtils::Deleter deleter(intermediateFile);
// 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();
// If the intermediate file exists, it means that we got problems deleting it (usually permissions)
// Notify the user and continue
if(intermediateFile.Exists()) {
// We failed to delete the intermediate file
::wxMessageBox(
wxString::Format(_("Unable to create intermediate file\n'%s'\nfor writing. File already exists!"),
intermediateFile.GetFullPath()),
"CodeLite", wxOK | wxCENTER | wxICON_ERROR, EventNotifier::Get()->TopFrame());
return false;
}
wxFFile file(intermediateFile.GetFullPath().GetData(), "wb");
if(!file.IsOpened()) {
// Nothing to be done
wxMessageBox(wxString::Format(_("Failed to open file\n'%s'\nfor write"), fileName.GetFullPath()), "CodeLite",
wxOK | wxCENTER | wxICON_ERROR);
return false;
}
// Convert the text
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())),
"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 | Preferences | Misc | Locale");
wxMessageBox(errmsg, "CodeLite", wxOK | wxICON_ERROR | wxCENTER, wxTheApp->GetTopWindow());
return false;
}
if(!m_fileBom.IsEmpty()) {
// restore the BOM
file.Write(m_fileBom.GetData(), m_fileBom.Len());
}
file.Write(buf.data(), strlen(buf.data()));
file.Close();
wxFileName symlinkedFile = fileName;
if(wxIsFileSymlink(fileName)) {
symlinkedFile = wxReadLink(fileName);
}
// keep the original file permissions
mode_t origPermissions = 0;
if(!FileUtils::GetFilePermissions(symlinkedFile, origPermissions)) {
clWARNING() << "Failed to read file permissions." << fileName << clEndl;
}
// If this file is not writable, prompt the user before we do something stupid
if(symlinkedFile.FileExists() && !symlinkedFile.IsFileWritable()) {
// Prompt the user
if(::wxMessageBox(wxString() << _("The file\n") << fileName.GetFullPath()
<< _("\nis a read only file, continue?"),
"CodeLite", wxYES_NO | wxCANCEL | wxCANCEL_DEFAULT | wxICON_WARNING,
EventNotifier::Get()->TopFrame()) != wxYES) {
return false;
}
}
// The write was done to a temporary file, override it
#ifdef __WXMSW__
if(!::wxRenameFile(intermediateFile.GetFullPath(), symlinkedFile.GetFullPath(), true)) {
// Check if the file has the ReadOnly attribute and attempt to remove it
if(MSWRemoveROFileAttribute(symlinkedFile)) {
if(!::wxRenameFile(intermediateFile.GetFullPath(), symlinkedFile.GetFullPath(), true)) {
wxMessageBox(wxString::Format(_("Failed to override read-only file")), "CodeLite",
wxOK | wxICON_WARNING);
return false;
}
}
}
#else
if(!::wxRenameFile(intermediateFile.GetFullPath(), symlinkedFile.GetFullPath(), true)) {
// Try clearing the clang cache and try again
wxMessageBox(wxString::Format(_("Failed to override read-only file")), "CodeLite", wxOK | wxICON_WARNING);
return false;
}
#endif
// Restore the orig file permissions
if(origPermissions) {
FileUtils::SetFilePermissions(symlinkedFile, origPermissions);
}
// update the modification time of the file
m_modifyTime = GetFileModificationTime(symlinkedFile.GetFullPath());
SetSavePoint();
// update the tab title (remove the star from the file name)
clMainFrame::Get()->GetMainBook()->SetPageTitle(this, fileName, false);
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 clEditor::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 clEditor::GetWordAtCaret(bool wordCharsOnly) { return GetWordAtPosition(GetCurrentPos(), wordCharsOnly); }
//---------------------------------------------------------------------------
// 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 clEditor::CompleteWord(LSP::CompletionItem::eTriggerKind triggerKind, bool onlyRefresh)
{
if(EventNotifier::Get()->IsEventsDiabled())
return;
if(AutoCompActive())
return; // Don't clobber the boxes
if(GetContext()->IsAtBlockComment()) {
// Check if the current word starts with \ or @
int wordStartPos = GetFirstNonWhitespacePos(true);
if(wordStartPos != wxNOT_FOUND) {
wxChar firstChar = GetCtrl()->GetCharAt(wordStartPos);
if((firstChar == '@') || (firstChar == '\\')) {
// Change the event to wxEVT_CC_BLOCK_COMMENT_WORD_COMPLETE
clCodeCompletionEvent evt(wxEVT_CC_BLOCK_COMMENT_WORD_COMPLETE);
evt.SetPosition(GetCurrentPosition());
evt.SetEditor(this);
evt.SetInsideCommentOrString(m_context->IsCommentOrString(PositionBefore(GetCurrentPos())));
evt.SetEventObject(this);
evt.SetTriggerKind(triggerKind);
EventNotifier::Get()->ProcessEvent(evt);
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.SetTriggerKind(triggerKind);
evt.SetEventObject(this);
ServiceProviderManager::Get().ProcessEvent(evt);
}
//------------------------------------------------------------------
// 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 clEditor::CodeComplete(bool refreshingList)
{
if(EventNotifier::Get()->IsEventsDiabled())
return;
if(AutoCompActive())
return; // Don't clobber the boxes..
if(!refreshingList) {
clCodeCompletionEvent evt(wxEVT_CC_CODE_COMPLETE);
evt.SetPosition(GetCurrentPosition());
evt.SetTriggerKind(LSP::CompletionItem::kTriggerCharacter);
evt.SetInsideCommentOrString(m_context->IsCommentOrString(PositionBefore(GetCurrentPos())));
evt.SetEventObject(this);
evt.SetEditor(this);
ServiceProviderManager::Get().ProcessEvent(evt);
} else {
CompleteWord(LSP::CompletionItem::kTriggerCharacter);
}
}
//----------------------------------------------------------------
// 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 clEditor::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())));
ServiceProviderManager::Get().ProcessEvent(event);
}
void clEditor::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();
// If the mouse is no longer over the editor, cancel the tooltip
if(!clientRect.Contains(pt)) {
return;
}
// Always cancel the previous tooltip...
DoCancelCodeCompletionBox();
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, title;
wxString fname = GetFileName().GetFullPath();
if(MarkerGet(line) & mmt_all_breakpoints) {
ManagerST::Get()->GetBreakpointsMgr()->GetTooltip(fname, line + 1, tooltip, title);
}
else if(MarkerGet(line) & mmt_all_bookmarks) {
GetBookmarkTooltip(line, tooltip, title);
}
bool compilerMarker = false;
// Compiler marker takes precedence over any other tooltip on that margin
if((MarkerGet(line) & mmt_compiler) && m_compilerMessagesMap.count(line)) {
compilerMarker = true;
// Get the compiler tooltip
tooltip = m_compilerMessagesMap.find(line)->second;
}
if(!tooltip.IsEmpty()) {
// if the marker is a compiler marker, dont manipulate the text
DoShowCalltip(-1, title, tooltip, !compilerMarker);
}
} 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(ServiceProviderManager::Get().ProcessEvent(evtTypeinfo)) {
if(!evtTypeinfo.GetTooltip().IsEmpty()) {
DoShowCalltip(wxNOT_FOUND, "", evtTypeinfo.GetTooltip(), true);
}
}
}
}
void clEditor::OnDwellEnd(wxStyledTextEvent& event)
{
DoCancelCalltip();
m_context->OnDwellEnd(event);
m_context->OnDbgDwellEnd(event);
}
void clEditor::OnCallTipClick(wxStyledTextEvent& event) { m_context->OnCallTipClick(event); }
void clEditor::OnMenuCommand(wxCommandEvent& event)
{
MenuEventHandlerPtr handler = MenuManager::Get()->GetHandler(event.GetId());
if(handler) {
handler->ProcessCommandEvent(this, event);
}
}
void clEditor::OnUpdateUI(wxUpdateUIEvent& event)
{
MenuEventHandlerPtr handler = MenuManager::Get()->GetHandler(event.GetId());
if(handler) {
handler->ProcessUpdateUIEvent(this, event);
}
}
//-----------------------------------------------------------------------
// Misc functions
//-----------------------------------------------------------------------
wxString clEditor::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 clEditor::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 clEditor::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 clEditor::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 clEditor::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 clEditor::RecalcHorizontalScrollbar()
{
if(m_autoAdjustHScrollbarWidth) {
::clRecalculateSTCHScrollBar(this);
}
}
//--------------------------------------------------------
// Brace match
//--------------------------------------------------------
bool clEditor::IsCloseBrace(int position)
{
return GetCharAt(position) == '}' || GetCharAt(position) == ']' || GetCharAt(position) == ')';
}
bool clEditor::IsOpenBrace(int position)
{
return GetCharAt(position) == '{' || GetCharAt(position) == '[' || GetCharAt(position) == '(';
}
void clEditor::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 clEditor::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);
#ifdef __WXMSW__
Refresh();
#endif
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 clEditor::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 clEditor::SetActive()
{
// ensure that the top level window parent of this editor is 'Raised'
bool raise(true);
#ifdef __WXGTK__
// On Wayland and gtk+3.22, raise not only fails, it hangs the subsequent DnD call. See
// http://trac.wxwidgets.org/ticket/17853
raise = !clMainFrame::Get()->GetIsWaylandSession();
#endif
DoUpdateTLWTitle(raise);
// 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 clEditor::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 clEditor 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 clEditor::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 clEditor::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
m_mgr->GetStatusBar()->SetMessage("");
::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
m_mgr->GetStatusBar()->SetMessage("");
}
}
bool clEditor::Replace() { return Replace(m_findReplaceDlg->GetData()); }
bool clEditor::FindAndSelect() { return FindAndSelect(m_findReplaceDlg->GetData()); }
bool clEditor::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 clEditor::FindAndSelect(const wxString& _pattern, const wxString& name)
{
return DoFindAndSelect(_pattern, name, 0, NavMgr::Get());
}
void clEditor::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
ClearSelections();
strings.Add(_pattern);
strings.Add(name);
CallAfter(&clEditor::DoFindAndSelectV, strings, pos);
}
void clEditor::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 clEditor::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 clEditor::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 clEditor::ToggleCurrentFold()
{
int line = GetCurrentLine();
if(line >= 0) {
DoToggleFold(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 clEditor::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 clEditor::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) {
DoToggleFold(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 clEditor::FoldAll()
{
// >(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)
DoToggleFold(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 clEditor::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) {
DoToggleFold(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) {
DoToggleFold(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 clEditor::StoreCollapsedFoldsToArray(clEditorStateLocker::VecInt_t& folds) const
{
clEditorStateLocker::SerializeFolds(const_cast<wxStyledTextCtrl*>(static_cast<const wxStyledTextCtrl*>(this)),
folds);
}
void clEditor::LoadCollapsedFoldsFromArray(const clEditorStateLocker::VecInt_t& folds)
{
clEditorStateLocker::ApplyFolds(GetCtrl(), folds);
}
//----------------------------------------------
// Bookmarks
//----------------------------------------------
void clEditor::AddMarker()
{
int nPos = GetCurrentPos();
int nLine = LineFromPosition(nPos);
int nBits = MarkerGet(nLine);
if(nBits & mmt_standard_bookmarks) {
clDEBUG() << "Marker already exists in" << GetFileName() << ":" << nLine;
return;
}
MarkerAdd(nLine, GetActiveBookmarkType());
// Notify about marker changes
NotifyMarkerChanged(nLine);
}
void clEditor::DelMarker()
{
int nPos = GetCurrentPos();
int nLine = LineFromPosition(nPos);
for(int i = smt_FIRST_BMK_TYPE; i < smt_LAST_BMK_TYPE; ++i) {
MarkerDelete(nLine, i);
// Notify about marker changes
NotifyMarkerChanged(nLine);
}
}
void clEditor::ToggleMarker()
{
// Add/Remove marker
if(!LineIsMarked(mmt_standard_bookmarks)) {
AddMarker();
} else {
DelMarker();
}
}
bool clEditor::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 clEditor::StoreMarkersToArray(wxArrayString& bookmarks)
{
clEditorStateLocker::SerializeBookmarks(GetCtrl(), bookmarks);
}
void clEditor::LoadMarkersFromArray(const wxArrayString& bookmarks)
{
clEditorStateLocker::ApplyBookmarks(GetCtrl(), bookmarks);
}
void clEditor::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());
SetIndicatorCurrent(MARKER_FIND_BAR_WORD_HIGHLIGHT);
IndicatorClearRange(0, GetLength());
// Notify about marker changes
NotifyMarkerChanged();
}
bool clEditor::HasCompilerMarkers()
{
// try to locate *any* compiler marker
int mask = mmt_compiler;
int nFoundLine = MarkerNext(0, mask);
return nFoundLine >= 0;
}
size_t clEditor::GetFindMarkers(std::vector<std::pair<int, wxString>>& bookmarksVector)
{
int nPos = 0;
int nFoundLine = LineFromPosition(nPos);
while(nFoundLine < GetLineCount()) {
nFoundLine = MarkerNext(nFoundLine, GetActiveBookmarkMask());
if(nFoundLine == wxNOT_FOUND) {
break;
}
wxString snippet = GetLine(nFoundLine);
snippet.Trim().Trim(false);
if(!snippet.IsEmpty()) {
snippet = snippet.Mid(0, snippet.size() > 40 ? 40 : snippet.size());
if(snippet.size() == 40) {
snippet << "...";
}
}
bookmarksVector.push_back({ nFoundLine + 1, snippet });
++nFoundLine;
}
return bookmarksVector.size();
}
void clEditor::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
CenterLine(nFoundLine);
} else {
// We reached the last marker, try again from top
nLine = LineFromPosition(0);
nFoundLine = MarkerNext(nLine, GetActiveBookmarkMask());
if(nFoundLine >= 0) {
CenterLine(nFoundLine);
}
}
if(nFoundLine >= 0) {
EnsureVisible(nFoundLine);
EnsureCaretVisible();
}
}
void clEditor::FindPrevMarker()
{
int nPos = GetCurrentPos();
int nLine = LineFromPosition(nPos);
int mask = GetActiveBookmarkMask();
int nFoundLine = MarkerPrevious(nLine - 1, mask);
if(nFoundLine >= 0) {
CenterLine(nFoundLine);
} else {
// We reached first marker, try again from button
int nFileSize = GetLength();
nLine = LineFromPosition(nFileSize);
nFoundLine = MarkerPrevious(nLine, mask);
if(nFoundLine >= 0) {
CenterLine(nFoundLine);
}
}
if(nFoundLine >= 0) {
EnsureVisible(nFoundLine);
EnsureCaretVisible();
}
}
bool clEditor::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 clEditor::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
NotifyMarkerChanged();
return true;
}
int clEditor::GetActiveBookmarkType() const
{
if(IsFindBookmarksActive()) {
return smt_find_bookmark;
} else {
return BookmarkManager::Get().GetActiveBookmarkType();
}
}
enum marker_mask_type clEditor::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 clEditor::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 clEditor::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
}
void clEditor::GetBookmarkTooltip(int lineno, wxString& tip, wxString& title)
{
title << "<b>Bookmarks</b>";
// 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";
tip << label << suffix;
}
for(int bmt = smt_FIRST_BMK_TYPE; bmt <= smt_LAST_BMK_TYPE; ++bmt) {
if(bmt != GetActiveBookmarkType()) {
if(linebits & (1 << bmt)) {
if(!tip.empty()) {
tip << "\n";
}
wxString label = GetBookmarkLabel((sci_marker_types)bmt);
wxString suffix = label.Lower().Contains("bookmark") ? "" : " bookmark";
tip << label << suffix;
}
}
}
}
wxFontEncoding clEditor::DetectEncoding(const wxString& filename)
{
wxFontEncoding encoding = GetOptions()->GetFileFontEncoding();
#if defined(USE_UCHARDET)
wxFile file(filename);
if(!file.IsOpened())
return encoding;
size_t size = file.Length();
if(size == 0) {
file.Close();
return encoding;
}
wxByte* buffer = (wxByte*)malloc(sizeof(wxByte) * (size + 4));
if(!buffer) {
file.Close();
return encoding;
}
buffer[size + 0] = 0;
buffer[size + 1] = 0;
buffer[size + 2] = 0;
buffer[size + 3] = 0;
size_t readBytes = file.Read((void*)buffer, size);
bool result = false;
if(readBytes > 0) {
uchardet_t ud = uchardet_new();
if(0 == uchardet_handle_data(ud, (const char*)buffer, readBytes)) {
uchardet_data_end(ud);
wxString charset(uchardet_get_charset(ud));
charset.MakeUpper();
if(charset.find("UTF-8") != wxString::npos) {
encoding = wxFONTENCODING_UTF8;
} else if(charset.find("GB18030") != wxString::npos) {
encoding = wxFONTENCODING_GB2312;
} else if(charset.find("BIG5") != wxString::npos) {
encoding = wxFONTENCODING_BIG5;
} else if(charset.find("EUC-JP") != wxString::npos) {
encoding = wxFONTENCODING_EUC_JP;
} else if(charset.find("EUC-KR") != wxString::npos) {
encoding = wxFONTENCODING_EUC_KR;
} else if(charset.find("WINDOWS-1252") != wxString::npos) {
encoding = wxFONTENCODING_CP1252;
} else if(charset.find("WINDOWS-1255") != wxString::npos) {
encoding = wxFONTENCODING_CP1255;
} else if(charset.find("ISO-8859-8") != wxString::npos) {
encoding = wxFONTENCODING_ISO8859_8;
} else if(charset.find("SHIFT_JIS") != wxString::npos) {
encoding = wxFONTENCODING_SHIFT_JIS;
}
}
uchardet_delete(ud);
}
file.Close();
free(buffer);
#endif
return encoding;
}
void clEditor::DoUpdateLineNumbers() { return; }
void clEditor::DoUpdateRelativeLineNumbers()
{
int beginLine = std::max(0, GetFirstVisibleLine() - 10);
int curLine = GetCurrentLine();
int lineCount = GetLineCount();
int endLine = std::min(lineCount, GetFirstVisibleLine() + LinesOnScreen() + 10);
if((m_lastBeginLine == beginLine) && (m_lastLine == curLine) && (m_lastEndLine == endLine) &&
(m_lastLineCount == lineCount)) {
return;
}
m_lastBeginLine = beginLine;
m_lastLineCount = lineCount;
m_lastEndLine = endLine;
MarginSetText(curLine, (wxString() << " " << (curLine + 1)));
// Use a distinct style to highlight the current line number
StyleSetBackground(CUR_LINE_NUMBER_STYLE, m_selTextBgColour);
StyleSetForeground(CUR_LINE_NUMBER_STYLE, m_selTextColour);
MarginSetStyle(curLine, CUR_LINE_NUMBER_STYLE);
for(int i = std::min(endLine, curLine - 1); i >= beginLine; --i) {
MarginSetText(i, (wxString() << " " << (curLine - i)));
MarginSetStyle(i, 0);
}
for(int i = std::max(beginLine, curLine + 1); i <= endLine; ++i) {
MarginSetText(i, (wxString() << " " << (i - curLine)));
MarginSetStyle(i, 0);
}
}
void clEditor::UpdateLineNumbers()
{
OptionsConfigPtr c = GetOptions();
if(!c->GetDisplayLineNumbers()) {
return;
} else if(c->GetRelativeLineNumbers()) {
DoUpdateRelativeLineNumbers();
} else if(c->GetHighlightCurrentLineNumber()) {
DoUpdateLineNumbers();
}
}
void clEditor::OpenFile()
{
wxBusyCursor bc;
wxWindowUpdateLocker locker(this);
SetReloadingFile(true);
DoCancelCalltip();
GetFunctionTip()->Deactivate();
if(m_fileName.GetFullPath().IsEmpty() == true || !m_fileName.FileExists()) {
SetEOLMode(GetEOLByOS());
SetReloadingFile(false);
return;
}
// State locker (on dtor it restores: bookmarks, current line, breakpoints and folds)
clEditorStateLocker stateLocker(GetCtrl());
int lineNumber = GetCurrentLine();
m_mgr->GetStatusBar()->SetMessage(_("Loading file..."));
wxString text;
// Read the file we currently support:
// BOM, Auto-Detect encoding & User defined encoding
m_fileBom.Clear();
ReadFileWithConversion(m_fileName.GetFullPath(), text, DetectEncoding(m_fileName.GetFullPath()), &m_fileBom);
SetText(text);
m_modifyTime = GetFileLastModifiedTime();
SetSavePoint();
EmptyUndoBuffer();
GetCommandsProcessor().Reset();
// Update the editor properties
DoUpdateOptions();
SetProperties();
UpdateLineNumberMarginWidth();
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);
SetReloadingFile(false);
// Notify that a file has been loaded into the editor
clCommandEvent fileLoadedEvent(wxEVT_FILE_LOADED);
fileLoadedEvent.SetFileName(GetFileName().GetFullPath());
EventNotifier::Get()->AddPendingEvent(fileLoadedEvent);
SetProperty(wxT("lexer.cpp.track.preprocessor"), wxT("0"));
SetProperty(wxT("lexer.cpp.update.preprocessor"), wxT("0"));
m_mgr->GetStatusBar()->SetMessage(_("Ready"));
}
void clEditor::SetEditorText(const wxString& text)
{
wxWindowUpdateLocker locker(this);
SetText(text);
// remove breakpoints belongs to this file
DelAllBreakpointMarkers();
}
void clEditor::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 'OpenFile'
// reload the file from disk
OpenFile();
}
void clEditor::InsertTextWithIndentation(const wxString& text, int lineno)
{
wxString textTag = FormatTextKeepIndent(text, PositionFromLine(lineno));
InsertText(PositionFromLine(lineno), textTag);
}
wxString clEditor::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 clEditor::OnContextMenu(wxContextMenuEvent& event)
{
wxString selectText = GetSelectedText();
wxPoint pt = event.GetPosition();
if(pt != wxDefaultPosition) { // Analyze position only for mouse-originated events
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));
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;
wxMenu* menu = m_context->GetMenu();
if(!menu)
return;
// Let the context add it dynamic content
m_context->AddMenuDynamicContent(menu);
// add the debugger (if currently running) to add its dynamic content
IDebugger* debugger = DebuggerMgr::Get().GetActiveDebugger();
if(debugger && debugger->IsRunning()) {
AddDebuggerContextMenu(menu);
}
// turn the popupIsOn value to avoid annoying
// calltips from firing while our menu is popped
m_popupIsOn = true;
// Notify about menu is about to be shown
clContextMenuEvent menuEvent(wxEVT_CONTEXT_MENU_EDITOR);
menuEvent.SetEditor(this);
menuEvent.SetMenu(menu);
EventNotifier::Get()->ProcessEvent(menuEvent);
// let the plugins hook their content
PluginManager::Get()->HookPopupMenu(menu, MenuTypeEditor);
// +++++------------------------------------------------------
// if the selection is URL, offer to open it in the browser
// +++++------------------------------------------------------
wxString selectedText = GetSelectedText();
if(!selectedText.IsEmpty() && !selectedText.Contains("\n")) {
static wxRegEx reUrl("https?://.*?", wxRE_ADVANCED);
if(reUrl.IsValid() && reUrl.Matches(selectText)) {
// Offer to open the URL
if(ID_OPEN_URL == wxNOT_FOUND) {
ID_OPEN_URL = ::wxNewId();
}
wxString text;
text << "Go to " << reUrl.GetMatch(selectText);
menu->PrependSeparator();
menu->Prepend(ID_OPEN_URL, text);
menu->Bind(wxEVT_MENU, &clEditor::OpenURL, this, ID_OPEN_URL);
}
}
// +++++--------------------------
// Popup the menu
// +++++--------------------------
PopupMenu(menu);
wxDELETE(menu);
m_popupIsOn = false;
event.Skip();
}
void clEditor::OnKeyDown(wxKeyEvent& event)
{
// always cancel the tip
DoCancelCodeCompletionBox();
m_prevSelectionInfo.Clear();
if(HasSelection()) {
for(int i = 0; i < GetSelections(); ++i) {
int selStart = GetSelectionNStart(i);
int selEnd = GetSelectionNEnd(i);
if(selEnd > selStart) {
m_prevSelectionInfo.AddSelection(selStart, selEnd);
} else {
m_prevSelectionInfo.Clear();
break;
}
}
m_prevSelectionInfo.Sort();
}
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.GetModifiers() == wxMOD_CONTROL;
if(keyIsControl) {
// Debugger tooltip is shown when clicking 'Control/CMD'
// while the mouse is over a word
wxPoint pt = ScreenToClient(wxGetMousePosition());
int pos = PositionFromPointClose(pt.x, pt.y);
if(pos != wxNOT_FOUND) {
wxString wordAtMouse = GetWordAtPosition(pos, false);
if(!wordAtMouse.IsEmpty()) {
// clLogMessage("Event wxEVT_DBG_EXPR_TOOLTIP is fired for string: %s", wordAtMouse);
clDebugEvent tipEvent(wxEVT_DBG_EXPR_TOOLTIP);
tipEvent.SetString(wordAtMouse);
if(EventNotifier::Get()->ProcessEvent(tipEvent)) {
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(event.GetKeyCode() == WXK_ESCAPE) {
if(GetFunctionTip()->IsActive()) {
GetFunctionTip()->Deactivate();
escapeUsed = true;
}
// If we've not already used ESC, there's a reasonable chance that the user wants to close the QuickFind bar
if(!escapeUsed) {
clMainFrame::Get()->GetMainBook()->ShowQuickBar(
false); // There's no easy way to tell if it's actually showing, so just do a Close
// In addition, if we have multiple selections, de-select them
if(GetSelections()) {
clEditorStateLocker editor(this);
ClearSelections();
}
}
}
m_context->OnKeyDown(event);
}
void clEditor::OnLeftUp(wxMouseEvent& event)
{
m_isDragging = false; // We can't still be in D'n'D, so stop disabling callticks
long value = EditorConfigST::Get()->GetInteger(wxT("QuickCodeNavigationUsesMouseMiddleButton"), 0);
if(!value) {
DoQuickJump(event, false);
}
PostCmdEvent(wxEVT_EDITOR_CLICKED);
event.Skip();
UpdateLineNumbers();
}
void clEditor::OnLeaveWindow(wxMouseEvent& event)
{
m_hyperLinkIndicatroStart = wxNOT_FOUND;
m_hyperLinkIndicatroEnd = wxNOT_FOUND;
m_hyperLinkType = wxID_NONE;
SetIndicatorCurrent(HYPERLINK_INDICATOR);
IndicatorClearRange(0, GetLength());
event.Skip();
}
void clEditor::OnFocusLost(wxFocusEvent& event)
{
m_isFocused = false;
event.Skip();
UpdateLineNumbers();
if(HasCapture()) {
CL_DEBUG("Releasing the mouse...");
ReleaseMouse();
}
}
void clEditor::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 clEditor::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 clEditor::OnLeftDown(wxMouseEvent& event)
{
HighlightWord(false);
wxDELETE(m_richTooltip);
// Clear context word highlight
SetIndicatorCurrent(MARKER_CONTEXT_WORD_HIGHLIGHT);
IndicatorClearRange(0, GetLength());
// hide completion box
DoCancelCalltip();
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();
// Destroy any floating tooltips out there
clCommandEvent destroyEvent(wxEVT_TOOLTIP_DESTROY);
EventNotifier::Get()->AddPendingEvent(destroyEvent);
// Clear any messages from the status bar
clGetManager()->GetStatusBar()->SetMessage("");
event.Skip();
}
void clEditor::OnPopupMenuUpdateUI(wxUpdateUIEvent& event)
{
// pass it to the context
m_context->ProcessEvent(event);
}
BrowseRecord clEditor::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();
record.firstLineInView = GetFirstVisibleLine();
// if the file is part of the workspace set the project name
// else, open it with empty project
record.position = GetCurrentPos();
return record;
}
void clEditor::DoBreakptContextMenu(wxPoint pt)
{
// turn the popupIsOn value to avoid annoying
// calltips from firing while our menu is popped
m_popupIsOn = true;
wxMenu menu;
// First, add/del bookmark
menu.Append(XRCID("toggle_bookmark"),
LineIsMarked(mmt_standard_bookmarks) ? 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();
menu.Append(XRCID("dbg_run_to_cursor"), _("Run to here"));
}
clContextMenuEvent event(wxEVT_CONTEXT_MENU_EDITOR_MARGIN);
event.SetMenu(&menu);
if(EventNotifier::Get()->ProcessEvent(event))
return;
PopupMenu(&menu, pt.x, pt.y);
m_popupIsOn = false;
}
void clEditor::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 clEditor::OnIgnoreBreakpoint()
{
if(ManagerST::Get()->GetBreakpointsMgr()->IgnoreByLineno(GetFileName().GetFullPath(), GetCurrentLine() + 1)) {
clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
}
}
void clEditor::OnEditBreakpoint()
{
ManagerST::Get()->GetBreakpointsMgr()->EditBreakpointByLineno(GetFileName().GetFullPath(), GetCurrentLine() + 1);
clMainFrame::Get()->GetDebuggerPane()->GetBreakpointView()->Initialize();
}
void clEditor::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 ");
}
m_mgr->GetStatusBar()->SetMessage(prefix + message);
}
}
void clEditor::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();
m_mgr->GetStatusBar()->SetMessage(_("Breakpoint successfully deleted"));
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 clEditor::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 clEditor::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);
NotifyMarkerChanged(lineno);
}
if(options.GetErrorWarningStyle() & BuildTabSettingsData::EWS_Annotate) {
// define the warning marker
AnnotationSetText(lineno, annotationText);
AnnotationSetStyle(lineno, ANNOTATION_STYLE_WARNING);
}
}
}
void clEditor::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);
NotifyMarkerChanged(lineno);
}
if(options.GetErrorWarningStyle() & BuildTabSettingsData::EWS_Annotate) {
AnnotationSetText(lineno, annotationText);
AnnotationSetStyle(lineno, ANNOTATION_STYLE_ERROR);
}
}
}
void clEditor::DelAllCompilerMarkers()
{
MarkerDeleteAll(smt_warning);
MarkerDeleteAll(smt_error);
AnnotationClearAll();
m_compilerMessagesMap.clear();
// Notify about marker changes
NotifyMarkerChanged();
}
// Maybe one day we'll display multiple bps differently
void clEditor::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);
NotifyMarkerChanged(lineno - 1);
// keep the breakpoint info vector for this marker
m_breakpointsInfo.insert(std::make_pair(markerHandle, bps));
}
void clEditor::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);
}
// Notify about marker changes
NotifyMarkerChanged();
}
void clEditor::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);
NotifyMarkerChanged(sci_line);
}
void clEditor::UnHighlightAll()
{
MarkerDeleteAll(smt_indicator); // Notify about marker changes
NotifyMarkerChanged();
}
void clEditor::AddDebuggerContextMenu(wxMenu* menu)
{
if(!ManagerST::Get()->DbgCanInteract()) {
return;
}
wxString word = GetSelectedText();
if(word.IsEmpty()) {
word = GetWordAtCaret();
if(word.IsEmpty()) {
return;
}
}
if(word.Contains("\n")) {
// Don't create massive context menu
return;
}
// Truncate the word
if(word.length() > 20) {
word = word.Mid(0, 20);
word << "...";
}
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(clEditor::OnDbgAddWatch), NULL,
this);
m_dynItems.push_back(item);
menuItemText.Clear();
menu->Prepend(XRCID("dbg_run_to_cursor"), _("Run to Caret Line"), _("Run to Caret Line"));
menu->Prepend(XRCID("dbg_jump_cursor"), _("Jump to Caret Line"), _("Jump to Caret Line"));
m_dynItems.push_back(item);
}
void clEditor::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(clEditor::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 clEditor::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 clEditor::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 clEditor::UpdateColours()
{
SetKeywordClasses("");
SetKeywordLocals("");
if(TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_COLOUR_VARS ||
TagsManagerST::Get()->GetCtagsOptions().GetFlags() & CC_COLOUR_MACRO_BLOCKS) {
m_context->OnFileSaved();
} else {
if(m_context->GetName() == wxT("C++")) {
SetKeyWords(1, wxEmptyString); // Classes
SetKeyWords(2, wxEmptyString);
SetKeyWords(3, wxEmptyString); // Locals
SetKeyWords(4, GetPreProcessorsWords());
}
}
Colourise(0, wxSTC_INVALID_POSITION);
}
int clEditor::SafeGetChar(int pos)
{
if(pos < 0 || pos >= GetLength()) {
return 0;
}
return GetCharAt(pos);
}
void clEditor::OnDragStart(wxStyledTextEvent& e)
{
m_isDragging = true; // Otherwise it sometimes obscures the desired drop zone!
e.Skip();
}
void clEditor::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 clEditor::ShowCompletionBox(const std::vector<TagEntryPtr>& tags, const wxString& word)
{
if(tags.empty()) {
return;
}
// When using this method, use an automated refresh completion box
wxCodeCompletionBoxManager::Get().ShowCompletionBox(this, tags, wxCodeCompletionBox::kRefreshOnKeyType,
wxNOT_FOUND);
}
int clEditor::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 clEditor::DoHighlightWord()
{
// Read the primary selected text
int mainSelectionStart = GetSelectionNStart(GetMainSelection());
int mainSelectionEnd = GetSelectionNEnd(GetMainSelection());
wxString word = GetTextRange(mainSelectionStart, mainSelectionEnd);
wxString selectedTextTrimmed = word;
selectedTextTrimmed.Trim().Trim(false);
if(selectedTextTrimmed.IsEmpty()) {
return;
}
// Search only the visible areas
StringHighlighterJob j;
int firstVisibleLine = GetFirstVisibleLine();
int lastDocLine = LineFromPosition(GetLength());
int offset = PositionFromLine(firstVisibleLine);
if(GetAllLinesVisible()) {
// The simple case: there aren't any folds
int lastLine = firstVisibleLine + LinesOnScreen();
if(lastLine > lastDocLine) {
lastLine = lastDocLine;
}
int lastPos = PositionFromLine(lastLine) + LineLength(lastLine);
wxString text = GetTextRange(offset, lastPos);
j.Set(text, word, offset);
j.Process();
} else {
// There are folds, so we have to process each visible section separately
firstVisibleLine = DocLineFromVisible(firstVisibleLine); // This copes with folds above the displayed lines
int lineCount(0);
int nextLineToProcess(firstVisibleLine);
int screenLines(LinesOnScreen());
while(lineCount < screenLines && nextLineToProcess <= lastDocLine) {
int offset(-1);
int line = nextLineToProcess;
// Skip over any invisible lines
while(!GetLineVisible(line) && line < lastDocLine) {
++line;
}
// EOF?
if(line >= lastDocLine)
break;
while(GetLineVisible(line) && line <= lastDocLine) {
if(offset == -1) {
offset = PositionFromLine(line); // Get offset value the first time through
}
++line;
++lineCount;
if(lineCount >= screenLines) {
break;
}
}
if(line > lastDocLine) {
line = lastDocLine;
}
nextLineToProcess = line;
int lastPos = PositionFromLine(nextLineToProcess) + LineLength(nextLineToProcess);
wxString text = GetTextRange(offset, lastPos);
j.Set(text, word, offset);
j.Process();
}
}
// Keep the first offset
m_highlightedWordInfo.Clear();
m_highlightedWordInfo.SetFirstOffset(offset);
m_highlightedWordInfo.SetWord(word);
HighlightWord((StringHighlightOutput*)&j.GetOutput());
}
void clEditor::HighlightWord(bool highlight)
{
if(highlight) {
DoHighlightWord();
} else {
SetIndicatorCurrent(MARKER_WORD_HIGHLIGHT);
IndicatorClearRange(0, GetLength());
m_highlightedWordInfo.Clear();
}
}
void clEditor::OnLeftDClick(wxStyledTextEvent& event)
{
long highlight_word = EditorConfigST::Get()->GetInteger(wxT("highlight_word"), 0);
if(GetSelectedText().IsEmpty() == false && highlight_word) {
DoHighlightWord();
}
event.Skip();
}
bool clEditor::IsCompletionBoxShown() { return wxCodeCompletionBoxManager::Get().IsShown(); }
int clEditor::GetCurrentLine()
{
// return the current line number
int pos = GetCurrentPos();
return LineFromPosition(pos);
}
void clEditor::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 clEditor::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 clEditor::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 clEditor::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));
ServiceProviderManager::Get().ProcessEvent(evt);
}
}
wxString clEditor::GetSelection() { return wxStyledTextCtrl::GetSelectedText(); }
int clEditor::GetSelectionStart() { return wxStyledTextCtrl::GetSelectionStart(); }
int clEditor::GetSelectionEnd() { return wxStyledTextCtrl::GetSelectionEnd(); }
void clEditor::ReplaceSelection(const wxString& text) { wxStyledTextCtrl::ReplaceSelection(text); }
void clEditor::ClearUserIndicators()
{
SetIndicatorCurrent(USER_INDICATOR);
IndicatorClearRange(0, GetLength());
}
int clEditor::GetUserIndicatorEnd(int pos) { return wxStyledTextCtrl::IndicatorEnd(USER_INDICATOR, pos); }
int clEditor::GetUserIndicatorStart(int pos) { return wxStyledTextCtrl::IndicatorStart(USER_INDICATOR, pos); }
void clEditor::SelectText(int startPos, int len)
{
SetSelectionStart(startPos);
SetSelectionEnd(startPos + len);
}
void clEditor::SetUserIndicator(int startPos, int len)
{
SetIndicatorCurrent(USER_INDICATOR);
IndicatorFillRange(startPos, len);
}
void clEditor::SetUserIndicatorStyleAndColour(int style, const wxColour& colour)
{
IndicatorSetForeground(USER_INDICATOR, colour);
IndicatorSetStyle(USER_INDICATOR, style);
IndicatorSetUnder(USER_INDICATOR, true);
}
int clEditor::GetLexerId() { return GetLexer(); }
int clEditor::GetStyleAtPos(int pos) { return GetStyleAt(pos); }
int clEditor::WordStartPos(int pos, bool onlyWordCharacters)
{
return wxStyledTextCtrl::WordStartPosition(pos, onlyWordCharacters);
}
int clEditor::WordEndPos(int pos, bool onlyWordCharacters)
{
return wxStyledTextCtrl::WordEndPosition(pos, onlyWordCharacters);
}
void clEditor::DoMarkHyperlink(wxMouseEvent& event, bool isMiddle)
{
if(event.m_controlDown || isMiddle) {
SetIndicatorCurrent(HYPERLINK_INDICATOR);
long pos = PositionFromPointClose(event.GetX(), event.GetY());
wxColour bgCol = StyleGetBackground(0);
if(DrawingUtils::IsDark(bgCol)) {
IndicatorSetForeground(HYPERLINK_INDICATOR, *wxWHITE);
} else {
IndicatorSetForeground(HYPERLINK_INDICATOR, *wxBLUE);
}
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 clEditor::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);
// Let the plugins handle it first
clCodeCompletionEvent event(wxEVT_CC_JUMP_HYPER_LINK);
event.SetString(GetTextRange(m_hyperLinkIndicatroStart, m_hyperLinkIndicatroEnd));
event.SetInt(m_hyperLinkIndicatroStart);
if(EventNotifier::Get()->ProcessEvent(event)) {
return;
}
// Run the default action
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 clEditor::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 clEditor::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 clEditor::DoShowCalltip(int pos, const wxString& title, const wxString& tip, bool manipulateText)
{
DoCancelCalltip();
wxPoint pt;
wxString tooltip;
tooltip << title;
tooltip.Trim().Trim(false);
if(!tooltip.IsEmpty()) {
tooltip << "\n<hr>";
}
tooltip << tip;
m_calltip = new CCBoxTipWindow(this, manipulateText, tooltip);
if(pos == wxNOT_FOUND) {
pt = ::wxGetMousePosition();
} else {
pt = PointFromPosition(pos);
}
// Place the tip on top of the mouse position, not under it
pt.y -= m_calltip->GetSize().GetHeight();
m_calltip->CallAfter(&CCBoxTipWindow::PositionAt, pt, this);
}
void clEditor::DoCancelCalltip()
{
CallTipCancel();
DoCancelCodeCompletionBox();
}
int clEditor::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('{'):
depth++;
pos = PositionBefore(pos);
break;
case wxT('}'):
depth--;
pos = PositionBefore(pos);
break;
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 clEditor::SetEOL()
{
// set the EOL mode
int eol = GetEOLByOS();
int alternate_eol = GetEOLByContent();
if(alternate_eol != wxNOT_FOUND) {
eol = alternate_eol;
}
SetEOLMode(eol);
}
void clEditor::OnChange(wxStyledTextEvent& event)
{
event.Skip();
++m_modificationCount;
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;
int newLineCount = GetLineCount();
if(m_lastLineCount != newLineCount) {
int lastWidthCount = log10(m_lastLine) + 2;
int newWidthCount = log10(newLineCount) + 2;
m_lastLine = newLineCount;
if(newWidthCount != lastWidthCount) {
UpdateLineNumberMarginWidth();
}
}
// Remove any code completion annotations if we have some...
if(m_hasCCAnnotation) {
CallAfter(&clEditor::AnnotationClearAll);
m_hasCCAnnotation = false;
}
// Notify about this editor being changed
clCommandEvent eventMod(wxEVT_EDITOR_MODIFIED);
eventMod.SetFileName(GetFileName().GetFullPath());
EventNotifier::Get()->QueueEvent(eventMod.Clone());
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(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 clEditor::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 clEditor::FindAndSelect(const wxString& pattern, const wxString& what, int pos, NavMgr* navmgr)
{
return DoFindAndSelect(pattern, what, pos, navmgr);
}
bool clEditor::SelectRange(const LSP::Range& range)
{
ClearSelections();
int startPos = PositionFromLine(range.GetStart().GetLine());
startPos += range.GetStart().GetCharacter();
int endPos = PositionFromLine(range.GetEnd().GetLine());
endPos += range.GetEnd().GetCharacter();
CenterLine(LineFromPosition(startPos), GetColumn(startPos));
SetSelectionStart(startPos);
SetSelectionEnd(endPos);
return true;
}
bool clEditor::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
ClearSelections();
SetCurrentPos(pos);
SetSelectionStart(pos);
SetSelectionEnd(pos + match_len);
res = true;
}
if(res && (line >= 0) && !again) {
SetEnsureCaretIsVisible(pos);
SetLineVisible(LineFromPosition(pos));
CenterLinePreserveSelection(LineFromPosition(pos));
}
}
} else {
// 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* clEditor::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(clEditor::OnDbgCustomWatch), NULL,
this);
m_customCmds[item->GetId()] = cmd.GetCommand();
}
return menu;
}
void clEditor::DoUpdateOptions()
{
// Start by getting the global settings
m_options = EditorConfigST::Get()->GetOptions();
// Now let any local preferences overwrite the global equivalent
if(clCxxWorkspaceST::Get()->IsOpen()) {
clCxxWorkspaceST::Get()->GetLocalWorkspace()->GetOptions(m_options, GetProject());
}
clEditorConfigEvent event(wxEVT_EDITOR_CONFIG_LOADING);
event.SetFileName(GetFileName().GetFullPath());
if(EventNotifier::Get()->ProcessEvent(event)) {
m_options->UpdateFromEditorConfig(event.GetEditorConfig());
}
}
bool clEditor::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 clEditor::SetLexerName(const wxString& lexerName) { SetSyntaxHighlight(lexerName); }
void clEditor::HighlightWord(StringHighlightOutput* highlightOutput)
{
// the search highlighter thread has completed the calculations, fetch the results and mark them in the editor
const std::vector<std::pair<int, int>>& matches = highlightOutput->matches;
SetIndicatorCurrent(MARKER_WORD_HIGHLIGHT);
// clear the old markers
IndicatorClearRange(0, GetLength());
if(!highlightOutput->matches.empty()) {
m_highlightedWordInfo.SetHasMarkers(true);
int selStart = GetSelectionStart();
for(size_t i = 0; i < matches.size(); i++) {
const std::pair<int, int>& p = matches.at(i);
// Dont highlight the current selection
if(p.first != selStart) {
IndicatorFillRange(p.first, p.second);
}
}
} else {
m_highlightedWordInfo.Clear();
}
}
void clEditor::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 clEditor::LineFromPos(int pos) { return wxStyledTextCtrl::LineFromPosition(pos); }
int clEditor::PosFromLine(int line) { return wxStyledTextCtrl::PositionFromLine(line); }
int clEditor::LineEnd(int line)
{
int pos = wxStyledTextCtrl::PositionFromLine(line);
return pos + wxStyledTextCtrl::LineLength(line);
}
wxString clEditor::GetTextRange(int startPos, int endPos) { return wxStyledTextCtrl::GetTextRange(startPos, endPos); }
void clEditor::DelayedSetActive() { CallAfter(&clEditor::SetActive); }
void clEditor::OnFocus(wxFocusEvent& event)
{
m_isFocused = true;
event.Skip();
}
bool clEditor::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 clEditor::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 clEditor::PositionAfterPos(int pos) { return wxStyledTextCtrl::PositionAfter(pos); }
int clEditor::GetCharAtPos(int pos) { return wxStyledTextCtrl::GetCharAt(pos); }
int clEditor::PositionBeforePos(int pos) { return wxStyledTextCtrl::PositionBefore(pos); }
void clEditor::GetChanges(std::vector<int>& changes) { m_deltas->GetChanges(changes); }
void clEditor::OnFindInFiles() { m_deltas->Clear(); }
void clEditor::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);
// clLogMessage("Settings buffered drawing to: %d", e.GetInt());
if(e.GetInt()) {
Refresh();
}
#endif
}
void clEditor::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 clEditor::OnKeyUp(wxKeyEvent& event)
{
event.Skip();
if(event.GetKeyCode() == WXK_CONTROL || event.GetKeyCode() == WXK_SHIFT || event.GetKeyCode() == WXK_ALT) {
// Clear hyperlink markers
SetIndicatorCurrent(HYPERLINK_INDICATOR);
IndicatorClearRange(0, GetLength());
m_hyperLinkType = wxID_NONE;
// Clear debugger marker
SetIndicatorCurrent(DEBUGGER_INDICATOR);
IndicatorClearRange(0, GetLength());
}
UpdateLineNumbers();
}
size_t clEditor::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_ALT;
return mod;
}
void clEditor::OnFileFormatDone(wxCommandEvent& e)
{
if(e.GetString() != GetFileName().GetFullPath()) {
// not this file
e.Skip();
return;
}
// Restore the markers
DoRestoreMarkers();
}
void clEditor::OnFileFormatStarting(wxCommandEvent& e)
{
if(e.GetString() != GetFileName().GetFullPath()) {
// not this file
e.Skip();
return;
}
DoSaveMarkers();
}
void clEditor::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();
NotifyMarkerChanged();
}
void clEditor::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 clEditor::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 clEditor::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 clEditor::IsDetached() const
{
const wxWindow* tlw = ::wxGetTopLevelParent(const_cast<clEditor*>(this));
return (tlw && (clMainFrame::Get() != tlw));
}
void clEditor::GetWordAtMousePointer(wxString& word, wxRect& wordRect)
{
word.clear();
wordRect = wxRect();
long start = wxNOT_FOUND;
long end = wxNOT_FOUND;
if(GetSelectedText().IsEmpty()) {
wxPoint mousePtInScreenCoord = ::wxGetMousePosition();
wxPoint clientPt = ScreenToClient(mousePtInScreenCoord);
int pos = PositionFromPoint(clientPt);
if(pos != wxNOT_FOUND) {
start = WordStartPosition(pos, true);
end = WordEndPosition(pos, true);
}
} else {
start = GetSelectionStart();
end = GetSelectionEnd();
}
wxFont font = StyleGetFont(0);
wxBitmap bmp(1, 1);
wxMemoryDC memdc(bmp);
memdc.SetFont(font);
wxSize sz = memdc.GetTextExtent(GetTextRange(start, end));
wxPoint ptStart = PointFromPosition(start);
wxRect rr(ptStart, sz);
word = GetTextRange(start, end);
wordRect = rr;
}
void clEditor::ShowRichTooltip(const wxString& tip, const wxString& title, int pos)
{
if(m_richTooltip)
return;
wxUnusedVar(pos);
wxString word;
wxRect rect;
GetWordAtMousePointer(word, rect);
m_richTooltip = new wxRichToolTip(title, tip);
m_richTooltip->ShowFor(this, &rect);
}
wxString clEditor::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 clEditor::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);
}
}
void clEditor::DoWrapPrevSelectionWithChars(wxChar first, wxChar last)
{
// Undo the previous action
BeginUndoAction();
// Restore the previous selection
Undo();
ClearSelections();
int charsAdded(0);
std::vector<std::pair<int, int>> selections;
for(size_t i = 0; i < m_prevSelectionInfo.GetCount(); ++i) {
int startPos, endPos;
m_prevSelectionInfo.At(i, startPos, endPos);
// insert the wrappers characters
// Each time we add character into the document, we move the insertion
// point by 1 (this is why charsAdded is used)
startPos += charsAdded;
InsertText(startPos, first);
++charsAdded;
endPos += charsAdded;
InsertText(endPos, last);
++charsAdded;
selections.push_back(std::make_pair(startPos + 1, endPos));
}
// And select it
for(size_t i = 0; i < selections.size(); ++i) {
const std::pair<int, int>& range = selections.at(i);
if(i == 0) {
SetSelection(range.first, range.second);
} else {
AddSelection(range.first, range.second);
}
}
EndUndoAction();
}
void clEditor::OnTimer(wxTimerEvent& event)
{
event.Skip();
m_timerHighlightMarkers->Start(100, true);
if(!HasFocus())
return;
if(!HasSelection()) {
HighlightWord(false);
} else {
if(EditorConfigST::Get()->GetInteger("highlight_word") == 1) {
int pos = GetCurrentPos();
int wordStartPos = WordStartPos(pos, true);
int wordEndPos = WordEndPos(pos, true);
wxString word = GetTextRange(wordStartPos, wordEndPos);
// Read the primary selected text
int mainSelectionStart = GetSelectionNStart(GetMainSelection());
int mainSelectionEnd = GetSelectionNEnd(GetMainSelection());
wxString selectedText = GetTextRange(mainSelectionStart, mainSelectionEnd);
if(!m_highlightedWordInfo.IsValid(this)) {
// Check to see if we have marker already on
// we got a selection
bool textMatches = (selectedText == word);
if(textMatches) {
// No markers set yet
DoHighlightWord();
} else if(!textMatches) {
// clear markers if the text does not match
HighlightWord(false);
}
} else {
// we got the markers on, check that they still matches the highlighted word
if(selectedText != m_highlightedWordInfo.GetWord()) {
HighlightWord(false);
} else {
// clDEBUG1() << "Markers are valid - nothing more to be done" << clEndl;
}
}
}
}
GetContext()->ProcessIdleActions();
}
void clEditor::SplitSelection()
{
CHECK_COND_RET(HasSelection() && GetSelections() == 1);
int selLineStart = LineFromPosition(GetSelectionStart());
int selLineEnd = LineFromPosition(GetSelectionEnd());
if(selLineEnd != selLineStart) {
if(selLineStart > selLineEnd) {
// swap
std::swap(selLineEnd, selLineStart);
}
ClearSelections();
for(int i = selLineStart; i <= selLineEnd; ++i) {
int caretPos;
if(i != GetLineCount() - 1) {
// Normally use PositionBefore as LineEnd includes the EOL as well
caretPos = PositionBefore(LineEnd(i));
} else {
caretPos = LineEnd(i); // but it seems not for the last line of the doc
}
if(i == selLineStart) {
// first selection
SetSelection(caretPos, caretPos);
} else {
AddSelection(caretPos, caretPos);
}
}
}
}
void clEditor::CenterLinePreserveSelection(int line)
{
int linesOnScreen = LinesOnScreen();
// To place our line in the middle, the first visible line should be
// the: line - (linesOnScreen / 2)
int firstVisibleLine = line - (linesOnScreen / 2);
if(firstVisibleLine < 0) {
firstVisibleLine = 0;
}
EnsureVisible(firstVisibleLine);
SetFirstVisibleLine(firstVisibleLine);
}
void clEditor::CenterLine(int line, int col)
{
int linesOnScreen = LinesOnScreen();
// To place our line in the middle, the first visible line should be
// the: line - (linesOnScreen / 2)
int firstVisibleLine = line - (linesOnScreen / 2);
if(firstVisibleLine < 0) {
firstVisibleLine = 0;
}
EnsureVisible(firstVisibleLine);
SetFirstVisibleLine(firstVisibleLine);
int pos = PositionFromLine(line);
if(col != wxNOT_FOUND) {
pos += col;
}
SetCaretAt(pos);
}
void clEditor::OnEditorConfigChanged(wxCommandEvent& event)
{
event.Skip();
DoUpdateOptions();
SetProperties();
UpdateLineNumbers();
}
void clEditor::ConvertIndentToSpaces()
{
clSTCLineKeeper lk(GetCtrl());
bool useTabs = GetUseTabs();
SetUseTabs(false);
BeginUndoAction();
int lineCount = GetLineCount();
for(int i = 0; i < lineCount; ++i) {
int indentStart = PositionFromLine(i);
int indentEnd = GetLineIndentPosition(i);
int lineIndentSize = GetLineIndentation(i);
if(indentEnd > indentStart) {
// this line have indentation
// delete it
DeleteRange(indentStart, indentEnd - indentStart);
SetLineIndentation(i, lineIndentSize);
}
}
EndUndoAction();
SetUseTabs(useTabs);
}
void clEditor::ConvertIndentToTabs()
{
clSTCLineKeeper lk(GetCtrl());
bool useTabs = GetUseTabs();
SetUseTabs(true);
BeginUndoAction();
int lineCount = GetLineCount();
for(int i = 0; i < lineCount; ++i) {
int indentStart = PositionFromLine(i);
int indentEnd = GetLineIndentPosition(i);
int lineIndentSize = GetLineIndentation(i);
if(indentEnd > indentStart) {
// this line have indentation
// delete it
DeleteRange(indentStart, indentEnd - indentStart);
SetLineIndentation(i, lineIndentSize);
}
}
EndUndoAction();
SetUseTabs(useTabs);
}
void clEditor::DoCancelCodeCompletionBox()
{
if(m_calltip) {
m_calltip->Hide();
m_calltip->Destroy();
m_calltip = NULL;
}
}
void clEditor::SetCodeCompletionAnnotation(const wxString& text, int lineno)
{
AnnotationClearAll();
m_hasCCAnnotation = true;
AnnotationSetText(lineno, text);
AnnotationSetStyle(lineno, ANNOTATION_STYLE_CC_ERROR);
}
int clEditor::GetFirstSingleLineCommentPos(int from, int commentStyle)
{
int lineNu = LineFromPos(from);
int lastPos = from + LineLength(lineNu);
for(int i = from; i < lastPos; ++i) {
if(GetStyleAt(i) == commentStyle) {
return i;
}
}
return wxNOT_FOUND;
}
int clEditor::GetNumberFirstSpacesInLine(int line)
{
int start = PositionFromLine(line);
int lastPos = start + LineLength(line);
for(int i = start; i < lastPos; ++i) {
if(!isspace(GetCharAt(i))) {
return i - start;
}
}
return wxNOT_FOUND;
}
void clEditor::ToggleLineComment(const wxString& commentSymbol, int commentStyle)
{
int start = GetSelectionStart();
int end = GetSelectionEnd();
if(start > end) {
wxSwap(start, end);
}
int lineStart = LineFromPosition(start);
int lineEnd = LineFromPosition(end);
// Check if the "end" position is at the start of a line, in that case, don't
// include it. Only do this in case of a selection.
int endLineStartPos = PositionFromLine(lineEnd);
if(lineStart < lineEnd && endLineStartPos == end) {
--lineEnd;
}
bool indentedComments = GetOptions()->GetIndentedComments();
bool doingComment;
int indent = 0;
if(indentedComments) {
// Check if there is a comment in the line 'lineStart'
int startCommentPos = GetFirstSingleLineCommentPos(PositionFromLine(lineStart), commentStyle);
doingComment = (startCommentPos == wxNOT_FOUND);
if(doingComment) {
// Find the minimum indent (in whitespace characters) among all the selected lines
// The comments will be indented with the found number of characters
indent = 100000;
bool indentFound = false;
for(int i = lineStart; i <= lineEnd; i++) {
int indentThisLine = GetNumberFirstSpacesInLine(i);
if((indentThisLine != wxNOT_FOUND) && (indentThisLine < indent)) {
indent = indentThisLine;
indentFound = true;
}
}
if(!indentFound) {
// Set the indent to zero in case of selection of empty lines
indent = 0;
}
}
} else {
doingComment = (GetStyleAt(start) != commentStyle);
}
BeginUndoAction();
for(; lineStart <= lineEnd; ++lineStart) {
start = PositionFromLine(lineStart);
if(doingComment) {
if(indentedComments) {
if(indent < LineLength(lineStart)) {
// Shift the position of the comment by the 'indent' number of characters
InsertText(start + indent, commentSymbol);
}
} else {
InsertText(start, commentSymbol);
}
} else {
int firstCommentPos = GetFirstSingleLineCommentPos(start, commentStyle);
if(firstCommentPos != wxNOT_FOUND) {
if(GetStyleAt(firstCommentPos) == commentStyle) {
SetAnchor(firstCommentPos);
SetCurrentPos(PositionAfter(PositionAfter(firstCommentPos)));
DeleteBackNotLine();
}
}
}
}
EndUndoAction();
SetCaretAt(PositionFromLine(lineEnd + 1));
ChooseCaretX();
}
void clEditor::CommentBlockSelection(const wxString& commentBlockStart, const wxString& commentBlockEnd)
{
int start = GetSelectionStart();
int end = GetSelectionEnd();
if(LineFromPosition(PositionBefore(end)) != LineFromPosition(end)) {
end = PositionBefore(end);
}
if(start == end)
return;
SetCurrentPos(end);
BeginUndoAction();
InsertText(end, commentBlockEnd);
InsertText(start, commentBlockStart);
EndUndoAction();
CharRight();
CharRight();
ChooseCaretX();
}
void clEditor::QuickAddNext()
{
if(!HasSelection()) {
int start = WordStartPos(GetCurrentPos(), true);
int end = WordEndPos(GetCurrentPos(), true);
SetSelection(start, end);
return;
}
int count = GetSelections();
int start = GetSelectionNStart(count - 1);
int end = GetSelectionNEnd(count - 1);
if(GetSelections() == 1) {
ClearSelections();
SetSelection(start, end);
SetMainSelection(0);
}
// Use the find flags of the quick find bar for this
int searchFlags = clMainFrame::Get()->GetMainBook()->GetFindBar()->m_searchFlags;
clMainFrame::Get()->GetMainBook()->ShowQuickBarToolBar(true);
wxString findWhat = GetTextRange(start, end);
int where = this->FindText(end, GetLength(), findWhat, searchFlags);
if(where != wxNOT_FOUND) {
AddSelection(where + findWhat.length(), where);
CenterLineIfNeeded(LineFromPos(where));
}
wxString message;
message << _("Found and selected ") << GetSelections() << _(" matches");
clGetManager()->GetStatusBar()->SetMessage(message);
}
void clEditor::QuickFindAll()
{
if(GetSelections() != 1)
return;
int start = GetSelectionStart();
int end = GetSelectionEnd();
wxString findWhat = GetTextRange(start, end);
if(findWhat.IsEmpty())
return;
ClearSelections();
int matches(0);
int firstMatch(wxNOT_FOUND);
// Use the find flags of the quick find bar for this
int searchFlags = clMainFrame::Get()->GetMainBook()->GetFindBar()->m_searchFlags;
clMainFrame::Get()->GetMainBook()->ShowQuickBarToolBar(true);
CallAfter(&clEditor::SetFocus);
// clWordCharslocker wcl(this);
int where = this->FindText(0, GetLength(), findWhat, searchFlags);
while(where != wxNOT_FOUND) {
if(matches == 0) {
firstMatch = where;
SetSelection(where, where + findWhat.length());
SetMainSelection(0);
CenterLineIfNeeded(LineFromPos(where));
} else {
AddSelection(where + findWhat.length(), where);
}
++matches;
where = this->FindText(where + findWhat.length(), GetLength(), findWhat, searchFlags);
}
wxString message;
message << _("Found and selected ") << GetSelections() << _(" matches");
clGetManager()->GetStatusBar()->SetMessage(message);
if(firstMatch != wxNOT_FOUND) {
SetMainSelection(0);
}
}
void clEditor::CenterLineIfNeeded(int line, bool force)
{
// Center this line
int linesOnScreen = LinesOnScreen();
if(force || ((line < GetFirstVisibleLine()) || (line > (GetFirstVisibleLine() + LinesOnScreen())))) {
// To place our line in the middle, the first visible line should be
// the: line - (linesOnScreen / 2)
int firstVisibleLine = line - (linesOnScreen / 2);
if(firstVisibleLine < 0) {
firstVisibleLine = 0;
}
EnsureVisible(firstVisibleLine);
SetFirstVisibleLine(firstVisibleLine);
}
}
void clEditor::Print()
{
#if wxUSE_PRINTING_ARCHITECTURE
if(g_printData == NULL) {
g_printData = new wxPrintData();
wxPrintPaperType* paper = wxThePrintPaperDatabase->FindPaperType(wxPAPER_A4);
g_printData->SetPaperId(paper->GetId());
g_printData->SetPaperSize(paper->GetSize());
g_printData->SetOrientation(wxPORTRAIT);
g_pageSetupData = new wxPageSetupDialogData();
(*g_pageSetupData) = *g_printData;
PageSetup();
}
// Black on White print mode
SetPrintColourMode(wxSTC_PRINT_BLACKONWHITE);
// No magnifications
SetPrintMagnification(0);
wxPrintDialogData printDialogData(*g_printData);
wxPrinter printer(&printDialogData);
clPrintout printout(this, GetFileName().GetFullPath());
if(!printer.Print(this, &printout, true /*prompt*/)) {
if(wxPrinter::GetLastError() == wxPRINTER_ERROR) {
wxLogError(wxT("There was a problem printing. Perhaps your current printer is not set correctly?"));
} else {
clLogMessage(wxT("You canceled printing"));
}
} else {
(*g_printData) = printer.GetPrintDialogData().GetPrintData();
}
#endif // wxUSE_PRINTING_ARCHITECTURE
}
void clEditor::PageSetup()
{
#if wxUSE_PRINTING_ARCHITECTURE
if(g_printData == NULL) {
g_printData = new wxPrintData();
wxPrintPaperType* paper = wxThePrintPaperDatabase->FindPaperType(wxPAPER_A4);
g_printData->SetPaperId(paper->GetId());
g_printData->SetPaperSize(paper->GetSize());
g_printData->SetOrientation(wxPORTRAIT);
g_pageSetupData = new wxPageSetupDialogData();
(*g_pageSetupData) = *g_printData;
}
wxPageSetupDialog pageSetupDialog(this, g_pageSetupData);
pageSetupDialog.ShowModal();
(*g_printData) = pageSetupDialog.GetPageSetupData().GetPrintData();
(*g_pageSetupData) = pageSetupDialog.GetPageSetupData();
#endif // wxUSE_PRINTING_ARCHITECTURE
}
void clEditor::OnMouseWheel(wxMouseEvent& event)
{
event.Skip();
if(::wxGetKeyState(WXK_CONTROL) && !GetOptions()->IsMouseZoomEnabled()) {
event.Skip(false);
return;
} else if(IsCompletionBoxShown()) {
event.Skip(false);
// wxCodeCompletionBoxManager::Get().GetCCWindow()->DoMouseScroll(event);
}
}
void clEditor::ClearCCAnnotations()
{
if(IsHasCCAnnotation()) {
AnnotationClearAll();
}
}
void clEditor::ApplyEditorConfig() { SetProperties(); }
void clEditor::OpenURL(wxCommandEvent& event)
{
wxString url = GetSelectedText();
::wxLaunchDefaultBrowser(url);
}
void clEditor::ReloadFromDisk(bool keepUndoHistory)
{
wxWindowUpdateLocker locker(this);
SetReloadingFile(true);
DoCancelCalltip();
GetFunctionTip()->Deactivate();
if(m_fileName.GetFullPath().IsEmpty() == true || !m_fileName.FileExists()) {
SetEOLMode(GetEOLByOS());
SetReloadingFile(false);
return;
}
clEditorStateLocker stateLocker(GetCtrl());
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);
Colourise(0, wxNOT_FOUND);
m_modifyTime = GetFileLastModifiedTime();
SetSavePoint();
if(!keepUndoHistory) {
EmptyUndoBuffer();
GetCommandsProcessor().Reset();
}
SetReloadingFile(false);
// Notify about file-reload
clCommandEvent e(wxEVT_FILE_LOADED);
e.SetFileName(GetFileName().GetFullPath());
EventNotifier::Get()->AddPendingEvent(e);
}
void clEditor::PreferencesChanged()
{
m_statusBarFields = 0;
if(clConfig::Get().Read(kConfigStatusbarShowLine, true)) {
m_statusBarFields |= kShowLine;
}
if(clConfig::Get().Read(kConfigStatusbarShowColumn, true)) {
m_statusBarFields |= kShowColumn;
}
if(clConfig::Get().Read(kConfigStatusbarShowPosition, false)) {
m_statusBarFields |= kShowPosition;
}
if(clConfig::Get().Read(kConfigStatusbarShowLength, false)) {
m_statusBarFields |= kShowLen;
}
if(clConfig::Get().Read(kConfigStatusbarShowSelectedChars, true)) {
m_statusBarFields |= kShowSelectedChars;
}
}
void clEditor::NotifyMarkerChanged(int lineNumber)
{
// Notify about marker changes
clCommandEvent eventMarker(wxEVT_MARKER_CHANGED);
eventMarker.SetFileName(GetFileName().GetFullPath());
if(lineNumber != wxNOT_FOUND) {
eventMarker.SetLineNumber(lineNumber);
}
EventNotifier::Get()->AddPendingEvent(eventMarker);
}
wxString clEditor::GetWordAtPosition(int pos, bool wordCharsOnly)
{
// Get the partial word that we have
if(wordCharsOnly) {
long start = WordStartPosition(pos, true);
long end = WordEndPosition(pos, true);
return GetTextRange(start, end);
} else {
int start = pos;
int end = pos;
int where = pos;
// find the start pos
while(true) {
int p = PositionBefore(where);
if((p != wxNOT_FOUND) && IsWordChar(GetCharAt(p))) {
where = p;
if(where == 0) {
break;
}
continue;
} else {
break;
}
}
wxSwap(start, where);
end = WordEndPosition(pos, true);
return GetTextRange(start, end);
}
}
int clEditor::GetFirstNonWhitespacePos(bool backward)
{
int from = GetCurrentPos();
if(from == wxNOT_FOUND) {
return wxNOT_FOUND;
}
int pos = from;
if(backward) {
from = PositionBefore(from);
} else {
from = PositionAfter(from);
}
while(from != wxNOT_FOUND) {
wxChar ch = GetCharAt(from);
switch(ch) {
case ' ':
case '\t':
case '\n':
return pos;
default:
break;
}
// Keep the previous location
pos = from;
// Move the position
if(backward) {
from = PositionBefore(from);
} else {
from = PositionAfter(from);
}
}
return pos;
}
void clEditor::UpdateLineNumberMarginWidth()
{
int newLineCount = GetLineCount();
int newWidthCount = log10(newLineCount) + 2;
SetMarginWidth(NUMBER_MARGIN_ID, newWidthCount * TextWidth(wxSTC_STYLE_LINENUMBER, "X"));
}
void clEditor::OnZoom(wxStyledTextEvent& event)
{
event.Skip();
// When zooming, update the line number margin
UpdateLineNumberMarginWidth();
}
void clEditor::DoToggleFold(int line, const wxString& textTag)
{
#if wxCHECK_VERSION(3, 1, 0)
ToggleFoldShowText(line, GetOptions()->GetUnderlineFoldLine() ? wxString() : textTag);
#else
wxUnusedVar(textTag);
ToggleFold(line);
#endif
}
size_t clEditor::GetEditorTextRaw(std::string& text)
{
text.clear();
wxCharBuffer cb = GetTextRaw();
if(cb.length()) {
text.reserve(cb.length() + 1);
text.append(cb.data());
}
return text.length();
}
// ----------------------------------
// SelectionInfo
// ----------------------------------
struct SelectorSorter {
bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) { return a.first < b.first; }
};
void clEditor::SelectionInfo::Sort() { std::sort(this->selections.begin(), this->selections.end(), SelectorSorter()); }
|