/usr/lib/gedit/plugins/RCtrl.py is in gedit-r-plugin 0.7.1.1-Gtk3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 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 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 | ##############################################################################
# #
# Rgedit: gedit plugin for R #
# Copyright (C) 2009-2011 Dan Dediu #
# #
# 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 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
##############################################################################
##############################################################################
# This was inspired by rkward (http://sourceforge.net/projects/rkward/) #
# and Tinn-R (http://sourceforge.net/projects/tinn-r/) and aims to offer #
# a light-weight, GTK+ IDE for R in the spirit of the above applications. #
# #
# It uses a heavily modified version of Paolo Borelli's VTE terminal for #
# gedit to allow embedding of R consoles. #
# Inspiration and code from Sukimashita's Open URI Context Menu Plugin #
# #
# The most important idea is that Rgedit does not need any custom R #
# package as the whole interaction processeds through the R console. This #
# allows it to be ver light on resources and fast but also imposes a #
# number of restrictions on the "intimacy" of the interaction with R. #
# #
# Nevertheless, Rgedit offers a range of tools very useful to the heavy #
# (and professional) R user, including syntax highlighting and advanced #
# editing (thanks gedit!), execution of the current line, selection, #
# the whole file or usr-defined persistent blocks of code as well as #
# several separate R consoles. For more details, see the help file. #
# #
##############################################################################
from gi.repository import GObject, Gedit, Gtk, Gdk, GdkPixbuf, Vte, GLib, Pango, GtkSource
import os.path
import pickle
import platform
import tempfile
import glob
import sys
from xml.dom import minidom
import xml.sax.saxutils
import re
import signal
import urllib2
import webbrowser
# Menu item example, insert a new item in the Tools menu
ui_str = """<ui>
<menubar name="MenuBar">
<menu name="R" action="R">
<menuitem name="RCtrlLine" action="RCtrlLine"/>
<menuitem name="RCtrlSel" action="RCtrlSel"/>
<menuitem name="RCtrlAll" action="RCtrlAll"/>
<menuitem name="RCtrlCursor" action="RCtrlCursor"/>
<separator/>
<menuitem name="RCtrlBlock1Run" action="RCtrlBlock1Run"/>
<menuitem name="RCtrlBlock1Def" action="RCtrlBlock1Def"/>
<separator/>
<menuitem name="RCtrlBlock2Run" action="RCtrlBlock2Run"/>
<menuitem name="RCtrlBlock2Def" action="RCtrlBlock2Def"/>
<separator/>
<menuitem name="RCtrlNewTab" action="RCtrlNewTab"/>
<menuitem name="RCtrlClose" action="RCtrlClose"/>
<menuitem name="RCtrlAttach" action="RCtrlAttach"/>
<!--menuitem name="RCtrlNewTab" action="RCtrlNewTab"/-->
<!--menuitem name="RCtrlLoadWorkspace" action="RCtrlLoadWorkspace"/-->
<!--menuitem name="RCtrlSaveWorkspace" action="RCtrlSaveWorkspace"/-->
<separator/>
<menuitem name="RCtrlLandmark" action="RCtrlLandmark"/>
<menuitem name="RCtrlWizards" action="RCtrlWizards"/>
<!--menuitem name="RCtrlHelpSel" action="RCtrlHelpSel"/-->
<!--menuitem name="RCtrlShowSel" action="RCtrlShowSel"/-->
<!--menuitem name="RCtrlEditSel" action="RCtrlEditSel"/-->
<separator/>
<menuitem name="RCtrlShowHide" action="RCtrlShowHide"/>
<menuitem name="RCtrlConfig" action="RCtrlConfig"/>
<menuitem name="RCtrlUpdate" action="RCtrlUpdate"/>
<menuitem name="RCtrlHelpRCtrl" action="RCtrlHelpRCtrl"/>
<menuitem name="RCtrlAbout" action="RCtrlAbout"/>
</menu>
</menubar>
<toolbar name="ToolBar">
<separator/>
<toolitem name="RCtrlLine" action="RCtrlLine"/>
<toolitem name="RCtrlSel" action="RCtrlSel"/>
<toolitem name="RCtrlAll" action="RCtrlAll"/>
<toolitem name="RCtrlCursor" action="RCtrlCursor"/>
<toolitem name="RCtrlBlock1Run" action="RCtrlBlock1Run"/>
<toolitem name="RCtrlBlock1Def" action="RCtrlBlock1Def"/>
<toolitem name="RCtrlBlock2Run" action="RCtrlBlock2Run"/>
<toolitem name="RCtrlBlock2Def" action="RCtrlBlock2Def"/>
<toolitem name="RCtrlNewTab" action="RCtrlNewTab"/>
</toolbar>
</ui>
"""
# The special comment used to put a landmark in the R code:
landmark_comment_header = "# @@ RGEDIT LANDMARK @@:"
landmark_comment_placeholder = _(" your text goes here")
# The temporary file used to communicate with R:
R_temp_file = tempfile.mkstemp(suffix='.r',prefix='RTmpFile-',dir='/tmp/')[1]
# The shell to use (default: bash):
shell_command_name = "bash"
#######################################################
# GtkBuilder vs Glade #
#######################################################
# Is Gtk version new enough to use GtkBuilder or Glade?
def use_GtkBuilder_or_Glade():
return (Gtk.get_major_version(),Gtk.get_minor_version()) >= (2,12)
# Conditionally import glade:
if not use_GtkBuilder_or_Glade():
print "Using glade..."
import Gtk.glade
# Generic wrappers for creating a UI and accessing widgets using either GtkBuilder or Glade:
def create_UI_from_file_GtkBuilder_or_Glade(glade_file,gtkbuilder_file):
if use_GtkBuilder_or_Glade():
# Using GtkBuilder:
ui = Gtk.Builder()
ui.add_from_file(gtkbuilder_file)
else:
# Using Glade:
ui = Gtk.glade.XML(glade_file)
return ui
def get_widget_from_ui_GtkBuilder_or_Glade(ui,widget_name):
if use_GtkBuilder_or_Glade():
# Using GtkBuilder:
widget_from_ui = ui.get_object(widget_name)
else:
# Using Glade:
widget_from_ui = ui.get_widget(widget_name)
return widget_from_ui
def connect_signals_for_ui_GtkBuilder_or_Glade(ui,signals_dictionary):
if use_GtkBuilder_or_Glade():
# Using GtkBuilder:
ui.connect_signals(signals_dictionary)
else:
# Using Glade:
ui.signal_autoconnect(signals_dictionary)
def gtk_gdk_Color_to_string(gtk_gdk_Color):
# Convert manually a Gdk.Color to a string of the form #rrggbb:
rr = hex(gtk_gdk_Color.red)[2:]
rr = '0'*(4-len(rr)) + rr
gg = hex(gtk_gdk_Color.green)[2:]
gg = '0'*(4-len(gg)) + gg
bb = hex(gtk_gdk_Color.blue)[2:]
bb = '0'*(4-len(bb)) + bb
return '#' + rr + gg + bb
########################################################
# From GeditTerminal #
########################################################
try:
gettext.bindtextdomain(GETTEXT_PACKAGE, GP_LOCALEDIR)
_ = lambda s: gettext.dgettext(GETTEXT_PACKAGE, s);
except:
_ = lambda s: s
class RGeditTerminal(Gtk.HBox):
__gsignals__ = {
"populate-popup": (
GObject.SignalFlags.RUN_LAST,
None,
(GObject.TYPE_OBJECT,)
)
}
def __init__(self,plugin):
GObject.GObject.__init__(self) #, False, 4)
self._plugin = plugin
self.vteTabs = Gtk.Notebook()
self.vteTabs.set_tab_pos(self._plugin.prefs['R_console_tab_pos'])
self.vteTabs.set_show_tabs(self._plugin.prefs['R_console_always_show_tabs'])
self.vteTabs.show()
# A maximum of 3 tabs: keep track of tabs 2 and 3 (1 is always open):
self._vte2 = None
self._vte3 = None
self._vte2_page_number = -1 # _vte2's page index (can be 1 or 2)
self._vte3_page_number = -1 # _vte3's page index (can be 1 or 2)
# And their names:
self.tab_names = ["1","2","3"]
# And the shell PIDs for each:
self._vte1_shell_PID = -1;
self._vte2_shell_PID = -1;
self._vte3_shell_PID = -1;
self._vteTab1 = Gtk.HBox()
self._vte = Vte.Terminal()
self.reconfigure_vte(self._vte,1)
self._vte.set_size(self._vte.get_column_count(), 5)
self._vte.set_size_request(200, 50)
self._vte.show()
self._vteTab1.pack_start(self._vte, True, True, 0)
self._vteTab1.show()
self.vteTabs.append_page(self._vteTab1,Gtk.Label(label=self.get_tab_name(1)))
self.pack_start(self.vteTabs, True, True, 0)
self._scrollbar = Gtk.VScrollbar()
self._scrollbar.set_adjustment(self._vte.adjustment)
self._scrollbar.show()
self._vteTab1.pack_start(self._scrollbar, False, False, 0)
self._vte.connect("key-press-event", self.on_vte_key_press)
self._vte.connect("key-release-event", self.on_vte_key_release)
self._vte.connect("button-press-event", self.on_vte_button_press)
self._vte.connect("popup-menu", self.on_vte_popup_menu)
self._vte.connect("child-exited", self.vte1_child_exited)
#self._vte.connect("commit", self.on_vte_committed)
self._vte1_shell_PID = self._vte.fork_command_full( Vte.PtyFlags.DEFAULT, None, [shell_command_name], None, GLib.SpawnFlags.CHILD_INHERITS_STDIN | GLib.SpawnFlags.SEARCH_PATH, None, None )[1]
# Is it a special Ctrl+C (used to implement the Ctrl+Q/ESC key in the R console):
self.special_ctrl_c = False
def run_gedit_helper_script(self,vte):
# Run the gedit helper script
vte.feed_child(_("# Run misc stuff required by rgedit...\n"),-1)
vte.feed_child("source(\""+self._plugin.get_data_dir()+"/rgedit-helper-script.r\",echo=FALSE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1)
def show_messages_and_warnings(self,vte):
# Show a warning on the R console:
if self._plugin.prefs['show_messages_and_warnings'] == False:
return
message_file = open(self._plugin.get_data_dir()+"/messages_and_warnings.txt","r")
if not message_file:
print _("Error reading the messages and warnings file\n")
return
vte.feed_child( _("\n############################ rgedit messages #################################\n"),-1 )
for line in message_file:
vte.feed_child( "# " + line,-1 );
vte.feed_child( "################################################################################\n\n",-1 )
def vte1_child_exited(self,event):
self._vte1_shell_PID = self._vte.fork_command_full( Vte.PtyFlags.DEFAULT, None, [shell_command_name], None, GLib.SpawnFlags.CHILD_INHERITS_STDIN | GLib.SpawnFlags.SEARCH_PATH, None, None )[1]
def on_vte_committed(self,vterm,text,textlen):
#print text, textlen
return true
def do_grab_focus(self):
self._vte.grab_focus()
def reconfigure_vte(self,_vteN,tab_number):
# Fonts
font_name = self._plugin.prefs['font_name']
try:
_vteN.set_font(Pango.FontDescription(font_name))
except:
pass
# colors
_vteN.ensure_style()
style = _vteN.get_style()
if self._plugin.prefs['foreground'+str(tab_number)] == None:
fg = style.text[Gtk.StateType.NORMAL]
else:
fg = Gdk.color_parse(self._plugin.prefs['foreground'+str(tab_number)])
if self._plugin.prefs['background'+str(tab_number)] == None:
bg = style.base[Gtk.StateType.NORMAL]
else:
bg = Gdk.color_parse(self._plugin.prefs['background'+str(tab_number)])
palette = []
if isinstance(fg,tuple):
fg = fg[1]
if isinstance(bg,tuple):
bg = bg[1]
_vteN.set_colors(fg, bg, palette)
# cursor blink
try:
if self._plugin.prefs['cursor_blink'] == "system":
blink = vte.CURSOR_BLINK_SYSTEM
elif self._plugin.prefs['cursor_blink'] == "on":
blink = vte.CURSOR_BLINK_ON
elif self._plugin.prefs['cursor_blink'] == "off":
blink = vte.CURSOR_BLINK_OFF
else:
blink = vte.CURSOR_BLINK_SYSTEM
_vteN.set_cursor_blink_mode(blink)
except:
pass
# cursor shape
try:
if self._plugin.prefs['cursor_shape'] == "block":
shape = vte.CURSOR_SHAPE_BLOCK
elif self._plugin.prefs['cursor_shape'] == "ibeam":
shape = vte.CURSOR_SHAPE_IBEAM
elif self._plugin.prefs['cursor_shape'] == "underline":
shape = vte.CURSOR_SHAPE_UNDERLINE
else:
shape = vte.CURSOR_SHAPE_BLOCK
_vteN.set_cursor_shape(shape)
except:
pass
_vteN.set_audible_bell(not self._plugin.prefs['audible_bell'])
_vteN.set_scrollback_lines(self._plugin.prefs['scrollback_lines'])
_vteN.set_allow_bold(self._plugin.prefs['allow_bold'])
_vteN.set_scroll_on_keystroke(self._plugin.prefs['scroll_on_keystroke'])
_vteN.set_scroll_on_output(self._plugin.prefs['scroll_on_output'])
_vteN.set_word_chars(self._plugin.prefs['word_chars'])
_vteN.set_emulation(self._plugin.prefs['emulation'])
_vteN.set_visible_bell(self._plugin.prefs['visible_bell'])
def on_vte_key_press(self, term, event):
if event.get_state() is None:
return False
modifiers = event.get_state() & Gtk.accelerator_get_default_mod_mask()
key_name = Gdk.keyval_name(event.keyval)
if key_name in ("v", "V") and modifiers == Gdk.ModifierType.CONTROL_MASK:
# Ctrl+V detected:
self.paste_clipboard()
return True
if key_name in ("c", "C") and modifiers == Gdk.ModifierType.CONTROL_MASK and not self.special_ctrl_c and self._plugin.prefs['R_console_Ctrl_C_4_copy']:
# Ctrl+C detected:
self.copy_clipboard()
return True
if key_name in ("x", "X") and modifiers == Gdk.ModifierType.CONTROL_MASK:
# Ctrl+X detected:
self.copy_clipboard()
return True
if (key_name in ("q", "Q") and modifiers == Gdk.ModifierType.CONTROL_MASK and self._plugin.prefs['R_console_Ctrl_Q_break']) or (key_name == "Escape" and self._plugin.prefs['R_console_Escape_break']):
# Ctrl+Q or ESC detected: simulate a Ctrl+C instead:
self.break_R_computation(event)
return True
elif key_name == "Tab" and modifiers == Gdk.EventMask.CONTROL_MASK:
# Ctrl+Tab detected:
current_view = self._window.get_active_view()
if current_view != None:
current_view.grab_focus()
return True
elif key_name in ("k", "K") and modifiers == Gdk.ModifierType.CONTROL_MASK:
# Copy the current line to the clipboard:
self.copy_last_line_to_clipboard()
return True
elif key_name in ("k", "K") and modifiers == (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK):
# Copy the current line to the clipboard and paste it into gedit:
self.copy_last_line_to_clipboard()
return True
return False
def on_vte_key_release(self, term, event):
modifiers = event.get_state() & Gtk.accelerator_get_default_mod_mask()
key_name = Gdk.keyval_name(event.keyval)
if key_name in ("k", "K") and modifiers == (Gdk.EventMask.ModifierType | Gdk.EventMask.ModifierType):
# Paste the previously copied line into gedit:
self.paste_last_line_from_clipboard_to_gedit()
return True
return False
def break_R_computation(self,original_event):
# Send a "hidden" Ctrl+C to the R process:
vte = None
if self.vteTabs.get_current_page() == 0:
vte= self._vte
elif self.vteTabs.get_current_page() == self._vte2_page_number:
vte= self._vte2
elif self.vteTabs.get_current_page() == self._vte3_page_number:
vte= self._vte3
else:
print( _("Unknown R tab!") )
event = Gdk.Event(Gdk.EventType.KEY_PRESS)
event.window = self.get_window() #vte.get_window() #vte.window
event.send_event = True
event.time = 0
event.state = Gdk.ModifierType.CONTROL_MASK
event.keyval = int(Gdk.keyval_from_name('c'))
#event.string = "Ctrl+C"
event.hardware_keycode = 0
event.group = 0
self.special_ctrl_c = True
#vte.emit("key-press-event", event)
#event.put();
#while Gtk.events_pending():
# Gtk.main_iteration()
#self.emit("key-press-event", event)
#vte.event(event)
#Gtk.main_do_event(event)
self.special_ctrl_c = False
def on_vte_button_press(self, term, event):
if event.button == 3:
self._vte.grab_focus()
self.do_popup(event)
return True
def on_vte_popup_menu(self, term):
self.do_popup()
def create_popup_menu(self):
menu = Gtk.Menu()
item = Gtk.ImageMenuItem()
item.set_label(Gtk.STOCK_COPY)
item.set_use_stock(True)
item.connect("activate", lambda menu_item: self.copy_clipboard())
if self.vteTabs.get_current_page() == 0:
item.set_sensitive(self._vte.get_has_selection())
elif self.vteTabs.get_current_page() == self._vte2_page_number:
item.set_sensitive(self._vte2.get_has_selection())
elif self.vteTabs.get_current_page() == self._vte3_page_number:
item.set_sensitive(self._vte3.get_has_selection())
else:
print( _("Unknown R tab!") )
menu.append(item)
item = Gtk.ImageMenuItem()
item.set_label(Gtk.STOCK_PASTE)
item.set_use_stock(True)
item.connect("activate", lambda menu_item: self.paste_clipboard())
menu.append(item)
item = Gtk.SeparatorMenuItem()
menu.append(item)
item = Gtk.MenuItem()
item.set_label(_("Change tab name"))
item.connect("activate", lambda menu_item: self.change_tab_name())
menu.append(item)
item = Gtk.CheckMenuItem()
item.set_label(_("Always show tabs?"))
item.set_active(self._plugin.prefs['R_console_always_show_tabs'])
item.connect("activate", lambda menu_item: self.always_show_tabs())
menu.append(item)
item = Gtk.MenuItem()
item.set_label(_("Show tabs on"))
menu.append(item)
show_tabs_submenu = Gtk.Menu()
tabs_top = Gtk.CheckMenuItem()
tabs_top.set_label(_("top"))
tabs_top.set_draw_as_radio(True)
tabs_top.set_active(self._plugin.prefs['R_console_tab_pos'] == Gtk.PositionType.TOP)
tabs_top.connect("activate", lambda menu_item: self.show_tabs_top())
tabs_left = Gtk.CheckMenuItem()
tabs_left.set_label(_("left"))
tabs_left.set_draw_as_radio(True)
tabs_left.set_active(self._plugin.prefs['R_console_tab_pos'] == Gtk.PositionType.LEFT)
tabs_left.connect("activate", lambda menu_item: self.show_tabs_left())
tabs_right = Gtk.CheckMenuItem()
tabs_right.set_label(_("right"))
tabs_right.set_draw_as_radio(True)
tabs_right.set_active(self._plugin.prefs['R_console_tab_pos'] == Gtk.PositionType.RIGHT)
tabs_right.connect("activate", lambda menu_item: self.show_tabs_right())
tabs_bottom = Gtk.CheckMenuItem()
tabs_bottom.set_label(_("bottom"))
tabs_bottom.set_draw_as_radio(True)
tabs_bottom.set_active(self._plugin.prefs['R_console_tab_pos'] == Gtk.PositionType.BOTTOM)
tabs_bottom.connect("activate", lambda menu_item: self.show_tabs_bottom())
show_tabs_submenu.attach(tabs_top,0,1,0,1)
show_tabs_submenu.attach(tabs_left,0,1,1,2)
show_tabs_submenu.attach(tabs_right,0,1,2,3)
show_tabs_submenu.attach(tabs_bottom,0,1,3,4)
item.set_submenu(show_tabs_submenu)
item = Gtk.MenuItem()
item.set_label(_("Close tab"))
item.connect("activate", lambda menu_item: self.close_tab())
if self.vteTabs.get_current_page() == 0:
item.set_sensitive(False)
menu.append(item)
item = Gtk.MenuItem()
item.set_label(_("Start R"))
item.connect("activate", lambda menu_item: self.start_R())
menu.append(item)
item = Gtk.MenuItem()
item.set_label(_("Restart R"))
item.connect("activate", lambda menu_item: self.restart_R())
menu.append(item)
item = Gtk.SeparatorMenuItem()
menu.append(item)
item = Gtk.MenuItem()
item.set_label(_("Change R's working folder"))
item.connect("activate", lambda menu_item: self.change_R_working_dir())
menu.append(item)
item = Gtk.MenuItem()
item.set_label(_("Use document's folder"))
item.connect("activate", lambda menu_item: self.change_R_working_dir_to_the_document())
menu.append(item)
item = Gtk.ImageMenuItem()
item.set_label(_("Load R workspace"))
item_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self._plugin.get_data_dir()+"/load_workspace.png" , 24, 24)
item_icon.set_from_pixbuf(pixbuf)
item_icon.show()
item.set_image(item_icon)
item.connect("activate", lambda menu_item: self.on_R_load_workspace())
menu.append(item)
item = Gtk.ImageMenuItem()
item.set_label(_("Save R workspace"))
item_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self._plugin.get_data_dir()+"/save_workspace.png" , 24, 24)
item_icon.set_from_pixbuf(pixbuf)
item_icon.show()
item.set_image(item_icon)
item.connect("activate", lambda menu_item: self.on_R_save_workspace())
menu.append(item)
menu.attach_to_widget(self,None)
self.emit("populate-popup", menu)
menu.show_all()
return menu
def do_popup(self, event = None):
menu = self.create_popup_menu()
if event is not None:
menu.popup(None, None, None, None, event.button, event.time)
else:
menu.popup(None, None, None,
#lambda m: Gedit.utils.menu_position_under_widget(m, self),
None, 0, Gtk.get_current_event_time())
menu.select_first(False)
def copy_clipboard(self):
if self.vteTabs.get_current_page() == 0:
self._vte.copy_clipboard()
self._vte.grab_focus()
elif self.vteTabs.get_current_page() == self._vte2_page_number:
self._vte2.copy_clipboard()
self._vte2.grab_focus()
elif self.vteTabs.get_current_page() == self._vte3_page_number:
self._vte3.copy_clipboard()
self._vte3.grab_focus()
else:
print( _("Unknown R tab!") )
def paste_clipboard(self):
if self.vteTabs.get_current_page() == 0:
self._vte.paste_clipboard()
self._vte.grab_focus()
elif self.vteTabs.get_current_page() == self._vte2_page_number:
self._vte2.paste_clipboard()
self._vte2.grab_focus()
elif self.vteTabs.get_current_page() == self._vte3_page_number:
self._vte3.paste_clipboard()
self._vte3.grab_focus()
else:
print( _("Unknown R tab!") )
def copy_last_line_to_clipboard(self):
# Copy the current line to the clipboard by invoking the .rgedit.lastline2clipboard function from the helper script:
clipboard_command = '.rgedit.lastline2clipboard()\n'
if self.vteTabs.get_current_page() == 0:
self._vte.feed_child(clipboard_command,-1)
self._vte.grab_focus()
elif self.vteTabs.get_current_page() == self._vte2_page_number:
self._vte2.feed_child(clipboard_command,-1)
self._vte2.grab_focus()
elif self.vteTabs.get_current_page() == self._vte3_page_number:
self._vte3.feed_child(clipboard_command,-1)
self._vte3.grab_focus()
else:
print( _("Unknown R tab!") )
def paste_last_line_from_clipboard_to_gedit(self):
# Paste the previously copied line into gedit:
app = gedit.app_get_default()
win = app.get_active_window()
doc = win.get_active_document()
#doc = self._plugin.get_active_window().get_active_document()
if not doc:
return
#doc.insert_at_cursor("KUK\n");
doc.paste_clipboard(Gtk.clipboard_get(selection="CLIPBOARD"),None,True)
#fake_clipboard = Gtk.Clipboard(Gdk.Display.get_default(),"_rgedit_fake_clipboard")
#fake_clipboard.set_text("\n")
#doc.paste_clipboard(fake_clipboard,None,True)
def change_directory(self, path):
path = path.replace('\\', '\\\\').replace('"', '\\"')
self._vte.feed_child('cd "%s"\n' % path,-1)
self._vte.grab_focus()
def send_command(self,string):
if self.vteTabs.get_current_page() == 0:
self._vte.feed_child(string,-1)
elif self.vteTabs.get_current_page() == self._vte2_page_number:
self._vte2.feed_child(string,-1)
elif self.vteTabs.get_current_page() == self._vte3_page_number:
self._vte3.feed_child(string,-1)
else:
print( _("Unknown R tab!") )
print( self.vteTabs.get_current_page() )
print( self._vte2_page_number )
print( self._vte3_page_number )
def create_new_R_tab(self):
if self._vte2 == None:
# _vte2 is free:
self._vteTab2 = Gtk.HBox()
self._vte2 = Vte.Terminal()
self.reconfigure_vte(self._vte2,2)
self._vte2.set_size(self._vte2.get_column_count(), 5)
self._vte2.set_size_request(200, 50)
self._vte2.show()
self._vteTab2.pack_start(self._vte2, True, True, 0)
self._vteTab2.show()
self.vteTabs.append_page(self._vteTab2,Gtk.Label(label=self.get_tab_name(2)))
self.vteTabs.set_show_tabs(True)
self._vte2_page_number = self.vteTabs.get_n_pages()-1
self._scrollbar2 = Gtk.VScrollbar()
self._scrollbar2.set_adjustment(self._vte2.adjustment)
self._scrollbar2.show()
self._vteTab2.pack_start(self._scrollbar2, False, False, 0)
self._vte2.connect("key-press-event", self.on_vte_key_press)
self._vte2.connect("button-press-event", self.on_vte_button_press)
self._vte2.connect("popup-menu", self.on_vte_popup_menu)
self._vte2.connect("child-exited", self.on_vte2_exited)
self._vte2_shell_PID = self._vte2.fork_command_full( Vte.PtyFlags.DEFAULT, None, [shell_command_name], None, GLib.SpawnFlags.CHILD_INHERITS_STDIN | GLib.SpawnFlags.SEARCH_PATH, None, None )[1]
self._vte2.feed_child("R --no-save --no-restore \n",-1) # open R
self.run_gedit_helper_script(self._vte2)
if self._plugin.prefs['HTML_help'] == True:
self._vte2.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte2.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color2'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte2.feed_child(self._plugin.prompt_string(2,self.get_tab_name(2)),-1) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self._vte2.feed_child("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1) # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.change_vte_R_working_dir_to_the_document(self._vte2)
self.show_messages_and_warnings(self._vte2)
if self._vte3 != None:
# All 3 tabs are active:
manager = self._window.get_ui_manager()
manager.get_action("/ToolBar/RCtrlNewTab").set_sensitive(False)
elif self._vte3 == None:
# _vte3 is free:
self._vteTab3 = Gtk.HBox()
self._vte3 = Vte.Terminal()
self.reconfigure_vte(self._vte3,3)
self._vte3.set_size(self._vte3.get_column_count(), 5)
self._vte3.set_size_request(200, 50)
self._vte3.show()
self._vteTab3.pack_start(self._vte3, True, True, 0)
self._vteTab3.show()
self.vteTabs.append_page(self._vteTab3,Gtk.Label(label=self.get_tab_name(3)))
self.vteTabs.set_show_tabs(True)
self._vte3_page_number = self.vteTabs.get_n_pages()-1
self._scrollbar3 = Gtk.VScrollbar()
self._scrollbar3.set_adjustment(self._vte3.adjustment)
self._scrollbar3.show()
self._vteTab3.pack_start(self._scrollbar3, False, False, 0)
self._vte3.connect("key-press-event", self.on_vte_key_press)
self._vte3.connect("button-press-event", self.on_vte_button_press)
self._vte3.connect("popup-menu", self.on_vte_popup_menu)
self._vte3.connect("child-exited", self.on_vte3_exited)
self._vte3_shell_PID = self._vte3.fork_command_full( Vte.PtyFlags.DEFAULT, None, [shell_command_name], None, GLib.SpawnFlags.CHILD_INHERITS_STDIN | GLib.SpawnFlags.SEARCH_PATH, None, None )[1]
self._vte3.feed_child("R --no-save --no-restore \n",-1) # open R
self.run_gedit_helper_script(self._vte3)
if self._plugin.prefs['HTML_help'] == True:
self._vte3.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte3.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color3'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte3.feed_child(self._plugin.prompt_string(3,self.get_tab_name(3)),-1) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self._vte3.feed_child("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1) # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.change_vte_R_working_dir_to_the_document(self._vte3)
self.show_messages_and_warnings(self._vte3)
if self._vte2 != None:
# All 3 tabs are active:
manager = self._window.get_ui_manager()
manager.get_action("/ToolBar/RCtrlNewTab").set_sensitive(False)
def kill_shell_process(self,PID):
# Kill the shell process with the given PID
#return # Not really working...
if PID > 0:
print "Kill " + str(PID)
os.kill(PID,signal.SIGHUP)
def on_vte2_exited(self,event):
# destroy the _vte2:
self.vteTabs.remove_page(self.vteTabs.get_current_page())
if self.vteTabs.get_n_pages() == 1:
self.vteTabs.set_show_tabs(False)
self._vte2 = None
self._vte2_page_number = -1
manager = self._window.get_ui_manager()
manager.get_action("/ToolBar/RCtrlNewTab").set_sensitive(True)
#self.kill_shell_process(self._vte2_shell_PID)
#self._vte2_shell_PID = -1
def on_vte3_exited(self,event):
# destroy the _vte3:
self.vteTabs.remove_page(self.vteTabs.get_current_page())
if self.vteTabs.get_n_pages() == 1:
self.vteTabs.set_show_tabs(False)
self._vte3 = None
self._vte3_page_number = -1
manager = self._window.get_ui_manager()
manager.get_action("/ToolBar/RCtrlNewTab").set_sensitive(True)
#self.kill_shell_process(self._vte3_shell_PID)
#self._vte3_shell_PID = -1
def change_tab_name(self):
tab_number = -1
active_vte = None
if self.vteTabs.get_current_page() == 0:
tab_number = 1
elif self.vteTabs.get_current_page() == self._vte2_page_number:
tab_number = self._vte2_page_number+1
elif self.vteTabs.get_current_page() == self._vte3_page_number:
tab_number = self._vte3_page_number+1
else:
print( _("Unknown R tab!") )
ChangeTabNameDialog_ui = create_UI_from_file_GtkBuilder_or_Glade(self._plugin.get_data_dir()+"/ChangeTabNameDialog.glade",self._plugin.get_data_dir()+"/ChangeTabNameDialog.ui")
# Init the controls accordingly with the current options:
label_tab_number = get_widget_from_ui_GtkBuilder_or_Glade(ChangeTabNameDialog_ui,"TabNumber")
label_tab_number.set_text(str(tab_number))
edit_tab_name = get_widget_from_ui_GtkBuilder_or_Glade(ChangeTabNameDialog_ui,"TabName")
edit_tab_name.set_text(self.tab_names[tab_number-1])
dialog = get_widget_from_ui_GtkBuilder_or_Glade(ChangeTabNameDialog_ui,"ChangeTabNameDialog")
#Create our dictionay and connect it
response = dialog.run()
if response == -2: #OK button
self.tab_names[tab_number-1] = edit_tab_name.get_text()
self.vteTabs.set_tab_label(self.vteTabs.get_nth_page(tab_number-1),Gtk.Label(label=self.get_tab_name(tab_number)))
vte1_console_changed = False
vte2_console_changed = False
vte3_console_changed = False
vte1_R_options_changed = False
vte2_R_options_changed = False
vte3_R_options_changed = False
if self._plugin.prefs['tab_name_in_prompt'] == True:
vte1_R_options_changed = (tab_number == 1)
vte2_R_options_changed = (tab_number == self._vte2_page_number+1)
vte3_R_options_changed = (tab_number == self._vte3_page_number+1)
self.reconfigure_vtes(vte1_console_changed,vte2_console_changed,vte3_console_changed,vte1_R_options_changed,vte2_R_options_changed,vte3_R_options_changed)
dialog.destroy()
def always_show_tabs(self):
# Toggle the showing of R tabs:
self._plugin.prefs['R_console_always_show_tabs'] = not self._plugin.prefs['R_console_always_show_tabs']
self.vteTabs.set_show_tabs(self._plugin.prefs['R_console_always_show_tabs'])
def show_tabs_right(self):
# Toggle the showing of R tabs to the right:
self._plugin.prefs['R_console_tab_pos'] = int(Gtk.PositionType.RIGHT)
self.vteTabs.set_tab_pos(self._plugin.prefs['R_console_tab_pos'])
def show_tabs_left(self):
# Toggle the showing of R tabs to the left:
self._plugin.prefs['R_console_tab_pos'] = int(Gtk.PositionType.LEFT)
self.vteTabs.set_tab_pos(self._plugin.prefs['R_console_tab_pos'])
def show_tabs_top(self):
# Toggle the showing of R tabs to the top:
self._plugin.prefs['R_console_tab_pos'] = int(Gtk.PositionType.TOP)
self.vteTabs.set_tab_pos(self._plugin.prefs['R_console_tab_pos'])
def show_tabs_bottom(self):
# Toggle the showing of R tabs to the bottom:
self._plugin.prefs['R_console_tab_pos'] = int(Gtk.PositionType.BOTTOM)
self.vteTabs.set_tab_pos(self._plugin.prefs['R_console_tab_pos'])
def reconfigure_vtes(self,vte1_console_changed,vte2_console_changed,vte3_console_changed,vte1_R_options_changed,vte2_R_options_changed,vte3_R_options_changed):
if vte1_console_changed == True:
self.reconfigure_vte(self._vte,1)
if vte1_R_options_changed == True:
if self._plugin.prefs['HTML_help'] == True:
self._vte.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color1'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte.feed_child(self._plugin.prompt_string(1,self.get_tab_name(1)),-1) # and set the prompt accordingly...
if self._vte2 != None:
if vte2_console_changed == True:
self.reconfigure_vte(self._vte2,2)
if vte2_R_options_changed == True:
if self._plugin.prefs['HTML_help'] == True:
self._vte2.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte2.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color2'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte2.feed_child(self._plugin.prompt_string(2,self.get_tab_name(2)),-1) # and set the prompt accordingly...
if self._vte3 != None:
if vte3_console_changed == True:
self.reconfigure_vte(self._vte3,3)
if vte3_R_options_changed == True:
if self._plugin.prefs['HTML_help'] == True:
self._vte3.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte3.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color3'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte3.feed_child(self._plugin.prompt_string(3,self.get_tab_name(3)),-1) # and set the prompt accordingly...
def get_tab_name(self,tab_number):
# Return the tab name:
return self.tab_names[tab_number-1]
def close_tab(self):
if self.vteTabs.get_current_page() == self._vte2_page_number:
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, "Are you sure you want to close this tab?" )
response = question_dialog.run()
question_dialog.destroy()
if response == Gtk.ResponseType.YES:
self.kill_shell_process(self._vte2_shell_PID)
self._vte2_shell_PID = -1
elif self.vteTabs.get_current_page() == self._vte3_page_number:
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, "Are you sure you want to close this tab?" )
response = question_dialog.run()
question_dialog.destroy()
if response == Gtk.ResponseType.YES:
self.kill_shell_process(self._vte3_shell_PID)
self._vte3_shell_PID = -1
def restart_R(self):
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, "Are you sure you want to restart R?\nYou must be at the old R session prompt for this..." )
response = question_dialog.run()
question_dialog.destroy()
if response == Gtk.ResponseType.YES:
if self.vteTabs.get_current_page() == 0:
self._vte.feed_child("q()\n",-1)
self._vte.feed_child("R --no-save --no-restore \n",-1) # open R
self.run_gedit_helper_script(self._vte)
if self._plugin.prefs['HTML_help'] == True:
self._vte.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color1'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte.feed_child(self._plugin.prompt_string(1,self.get_tab_name(1)),-1) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self._vte.feed_child("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1) # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.change_vte_R_working_dir_to_the_document(self._vte)
self.show_messages_and_warnings(self._vte)
elif self.vteTabs.get_current_page() == self._vte2_page_number:
self._vte2.feed_child("q()\n",-1)
self._vte2.feed_child("R --no-save --no-restore \n",-1) # open R
self.run_gedit_helper_script(self._vte2)
if self._plugin.prefs['HTML_help'] == True:
self._vte2.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte2.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color2'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte2.feed_child(self._plugin.prompt_string(2,self.get_tab_name(2)),-1) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self._vte2.feed_child("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1) # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.change_vte_R_working_dir_to_the_document(self._vte2)
self.show_messages_and_warnings(self._vte2)
elif self.vteTabs.get_current_page() == self._vte3_page_number:
self._vte3.feed_child("q()\n",-1)
self._vte3.feed_child("R --no-save --no-restore \n",-1) # open R
self.run_gedit_helper_script(self._vte3)
if self._plugin.prefs['HTML_help'] == True:
self._vte3.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte3.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color3'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte3.feed_child(self._plugin.prompt_string(3,self.get_tab_name(3)),-1) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self._vte3.feed_child("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1) # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.change_vte_R_working_dir_to_the_document(self._vte3)
self.show_messages_and_warnings(self._vte3)
def start_R(self):
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, "Are you sure you want to start a new R session?\nYou must be at the shell prompt for this..." )
response = question_dialog.run()
question_dialog.destroy()
if response == Gtk.ResponseType.YES:
if self.vteTabs.get_current_page() == 0:
self._vte.feed_child("R --no-save --no-restore \n",-1) # open R
self.run_gedit_helper_script(self._vte)
if self._plugin.prefs['HTML_help'] == True:
self._vte.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color1'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte.feed_child(self._plugin.prompt_string(1,self.get_tab_name(1)),-1) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self._vte.feed_child("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1) # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.change_vte_R_working_dir_to_the_document(self._vte)
self.show_messages_and_warnings(self._vte)
elif self.vteTabs.get_current_page() == self._vte2_page_number:
self._vte2.feed_child("R --no-save --no-restore \n",-1) # open R
self.run_gedit_helper_script(self._vte2)
if self._plugin.prefs['HTML_help'] == True:
self._vte2.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte2.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color2'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte2.feed_child(self._plugin.prompt_string(2,self.get_tab_name(2)),-1) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self._vte2.feed_child("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1) # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.change_vte_R_working_dir_to_the_document(self._vte2)
self.show_messages_and_warnings(self._vte2)
elif self.vteTabs.get_current_page() == self._vte3_page_number:
self._vte3.feed_child("R --no-save --no-restore \n",-1) # open R
self.run_gedit_helper_script(self._vte3)
if self._plugin.prefs['HTML_help'] == True:
self._vte3.feed_child("options(htmlhelp = TRUE,help_type='html')\n",-1) # and init the HTML help system both for pre and post R 2.10.0...
else:
self._vte3.feed_child("options(htmlhelp = FALSE,help_type='text')\n",-1) # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color3'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self._vte3.feed_child(self._plugin.prompt_string(3,self.get_tab_name(3)),-1) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self._vte3.feed_child("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n",-1) # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.change_vte_R_working_dir_to_the_document(self._vte3)
self.show_messages_and_warnings(self._vte3)
def change_R_working_dir(self):
folder_dialog = Gtk.FileChooserDialog(_("Choose R's working folder"), None, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT, Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
response = folder_dialog.run()
if response == Gtk.ResponseType.ACCEPT:
folder_name = folder_dialog.get_filename()
# Assume R is working a ready:
if self.vteTabs.get_current_page() == 0:
self._vte.feed_child("setwd(\""+folder_name+"\");\n",-1)
elif self.vteTabs.get_current_page() == self._vte2_page_number:
self._vte2.feed_child("setwd(\""+folder_name+"\");\n",-1)
elif self.vteTabs.get_current_page() == self._vte3_page_number:
self._vte3.feed_child("setwd(\""+folder_name+"\");\n",-1)
else:
print( _("Unknown R tab!") )
folder_dialog.destroy()
def change_vte_R_working_dir_to_the_document(self,vte):
# Change the given vte's R's working folder to the current document's:
if not self._plugin.window:
print _("Cannot get current window")
return
doc = self._plugin.window.get_active_document()
if not doc:
return
folder_name = doc.get_uri_for_display()
if not folder_name:
return
folder_name = os.path.dirname(folder_name)
# Assume R is working and ready:
vte.feed_child("setwd(\""+folder_name+"\");\n",-1)
def change_R_working_dir_to_the_document(self):
# Change R's working folder to the current document's:
if not self._plugin.window:
print _("Cannot get current window")
return
doc = self._plugin.window.get_active_document()
if not doc:
return
folder_name = doc.get_uri_for_display()
if not folder_name:
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, _("Current document has not been saved: cannot change R's working folder to this...") )
response = question_dialog.run()
question_dialog.destroy()
return
folder_name = os.path.dirname(folder_name)
# Assume R is working and ready:
if self.vteTabs.get_current_page() == 0:
self._vte.feed_child("setwd(\""+folder_name+"\");\n",-1)
elif self.vteTabs.get_current_page() == self._vte2_page_number:
self._vte2.feed_child("setwd(\""+folder_name+"\");\n",-1)
elif self.vteTabs.get_current_page() == self._vte3_page_number:
self._vte3.feed_child("setwd(\""+folder_name+"\");\n",-1)
else:
print( "Unknown R tab!" )
def on_R_load_workspace(self):
file_dialog = Gtk.FileChooserDialog(_("Open R Workspace"), None, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT, Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
filter = Gtk.FileFilter()
filter.set_name("R worksapce")
filter.add_pattern("*.RData")
filter.add_pattern("*.R")
file_dialog.add_filter(filter)
filter = Gtk.FileFilter()
filter.set_name("All files")
filter.add_pattern("*")
file_dialog.add_filter(filter)
response = file_dialog.run()
if response == Gtk.ResponseType.ACCEPT:
file_name = file_dialog.get_filename()
do_send_to_R( "load( \""+file_name+"\", .GlobalEnv )\n", self, False, self._plugin.prefs['max_lines_as_text'] )
file_dialog.destroy()
def on_R_save_workspace(self):
file_dialog = Gtk.FileChooserDialog(_("Save R Workspace"), None, Gtk.FileChooserAction.SAVE, (Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT, Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
filter = Gtk.FileFilter()
filter.set_name("R worksapce")
filter.add_pattern("*.RData")
filter.add_pattern("*.R")
file_dialog.add_filter(filter)
filter = Gtk.FileFilter()
filter.set_name("All files")
filter.add_pattern("*")
file_dialog.add_filter(filter)
file_dialog.set_current_name(".RData")
file_dialog.set_do_overwrite_confirmation( True )
response = file_dialog.run()
if response == Gtk.ResponseType.ACCEPT:
file_name = file_dialog.get_filename()
do_send_to_R( "save( list = ls(all=TRUE), file = \""+file_name+"\" )\n", self, False, self._plugin.prefs['max_lines_as_text'] )
file_dialog.destroy()
########################################################################
# The Panel with the R file structure
########################################################################
# This class displays the panel tab:
class RStructurePanel:
def __init__(self,rctrlwindowhelper):
# Init:
self._rctrlwindowhelper = rctrlwindowhelper
self._window = rctrlwindowhelper._window
self._plugin = rctrlwindowhelper._plugin
# Get the side panel :
self.side_panel = self._window.get_side_panel()
# The support widget is a vbox:
self.R_struct_base_vbox = Gtk.VBox()
self.R_struct_base_vbox.show()
item_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self._plugin.get_data_dir()+"/R_structure.png" , 16, 16)
item_icon.set_from_pixbuf(pixbuf)
item_icon.show()
self.side_panel.add_item( self.R_struct_base_vbox, _("R structure"), "R structure", item_icon )
# Which contains an info line and a clickable (read-only) list
self.force_refresh = Gtk.Button(stock="gtk-refresh")
self.scrolled_window = Gtk.ScrolledWindow()
self.buttons_hbox = Gtk.HBox()
self.buttons_hbox.show()
# Enable/disable it:
self.enable_info = Gtk.CheckButton(_("Enable?"),False)
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
self.enable_info.set_tooltip_text(_("Enable or disable the info concerning the structure of the R file..."))
self.enable_info.show()
self.enable_info.connect( "toggled", self.on_enable_info_toggled )
self.buttons_hbox.pack_start(self.enable_info,False, True, 0)
self.enable_info.set_active(self._plugin.prefs['R_structure_enabled'])
# Force refresh:
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
self.force_refresh.set_tooltip_text(_("Force refresh of info concerning the structure of the R file..."))
self.force_refresh.show()
self.force_refresh.connect( "clicked", self.on_force_refresh )
self.force_refresh.set_sensitive(self._plugin.prefs['R_structure_enabled'])
self.buttons_hbox.pack_end(self.force_refresh,False,True,0)
self.R_struct_base_vbox.pack_start(self.buttons_hbox,False,True,0)
# The scrollable holder:
self.scrolled_window.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
self.scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self.scrolled_window.show()
self.scrolled_window.set_sensitive(self._plugin.prefs['R_structure_enabled'])
# The possible types and associated icons:
function_definition_icon = GdkPixbuf.Pixbuf.new_from_file_at_size(self._plugin.get_data_dir()+"/function_definition.png" , 16, 16)
landmark_definition_icon = GdkPixbuf.Pixbuf.new_from_file_at_size(self._plugin.get_data_dir()+"/landmark_definition.png" , 16, 16)
dataframe_defintion_icon = GdkPixbuf.Pixbuf.new_from_file_at_size(self._plugin.get_data_dir()+"/dataframe_definition.png" , 16, 16)
self.info_types = {
'function' : function_definition_icon,
'landmark' : landmark_definition_icon,
'data.frame' : dataframe_defintion_icon
}
# The treeview holding the actual info (line no, icon_type, actual info):
#self.info_liststore = Gtk.ListStore(GObject.TYPE_INT,GdkPixbuf.Pixbuf,GObject.TYPE_STRING,GObject.TYPE_STRING)
self.info_liststore = Gtk.ListStore(str,GdkPixbuf.Pixbuf,str,str)
#self.info_liststore.append(["1",self.info_types['function'],"idem","tooltip1"])
#self.info_liststore.append(["2",self.info_types['landmark'],"x <- 1","tooltip2"])
self.info_treeview = Gtk.TreeView()
self.info_treeview.set_model(self.info_liststore)
# The columns:
rendererText = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Line", rendererText, text=0)
column.set_resizable(True)
#column.set_sort_column_id(0)
self.info_treeview.append_column(column)
rendererPixbuf = Gtk.CellRendererPixbuf()
column = Gtk.TreeViewColumn("Type", rendererPixbuf, pixbuf=1)
#column.set_min_width(25)
column.set_resizable(True)
#column.set_sort_column_id(0)
self.info_treeview.append_column(column)
rendererText = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Info", rendererText, text=2)
column.set_resizable(True)
#column.set_sort_column_id(0)
self.info_treeview.append_column(column)
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
self.info_treeview.set_tooltip_column(3)
self.info_treeview.set_headers_visible(True)
self.info_treeview.set_headers_clickable(False)
self.info_treeview.set_reorderable(False)
self.info_treeview.set_enable_search(True)
self.info_treeview.set_search_column(2)
self.info_treeview.show()
self.scrolled_window.add(self.info_treeview)
self.R_struct_base_vbox.pack_start(self.scrolled_window,True,True,0)
self.info_treeview.connect("row-activated", self.on_inforow_activated)
# The regular expression matcher:
self.create_pattern_matcher()
#self._pattern_matcher = re.compile( r"[ \t]*"+landmark_comment_header + # a landmark comment
# r"|" + # or
# r"function\(" # a function defintion
# )
def create_pattern_matcher(self):
# Create the appriate pattern matcher given the options:
pattern_definition = r""
if self._plugin.prefs['R_structure_landmarks']:
pattern_definition += r"[ \t]*"+landmark_comment_header
if self._plugin.prefs['R_structure_functions']:
pattern_definition += (r"|",r"")[len(pattern_definition) == 0] + r"function\("
if self._plugin.prefs['R_structure_dataframes']:
pattern_definition += (r"|",r"")[len(pattern_definition) ==0 ] + r"data\.frame\("
self._pattern_matcher = re.compile(pattern_definition)
def on_enable_info_toggled(self,checkbutton):
# The enable R info checkbutton has been toggled:
self._plugin.prefs['R_structure_enabled'] = checkbutton.get_active()
self._plugin.save_prefs()
self.force_refresh.set_sensitive(self._plugin.prefs['R_structure_enabled'])
self.scrolled_window.set_sensitive(self._plugin.prefs['R_structure_enabled'])
# Frce a refresh:
if self._plugin.prefs['R_structure_enabled']:
doc = self._window.get_active_document()
if not doc:
return
self.parse_R_document_for_landmarks(doc)
def on_force_refresh(self,button):
# Force a refresh of the structure:
doc = self._window.get_active_document()
if not doc:
return
self.parse_R_document_for_landmarks(doc)
def on_inforow_activated(self,widget, row, col):
# The row has been activated by the user:
model = widget.get_model()
doc = self._window.get_active_document()
if not doc:
return
view = self._window.get_active_view()
if not view:
return
try:
line_no = int(model[row][0])
except:
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _('The line number "') + model[row][0] + _('" is illegal!') )
error_dialog.run()
error_dialog.destroy()
return
if line_no < 0 or line_no > doc.get_line_count():
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("The line number must be a positive integer smaller than the number of lines in the document!") )
error_dialog.run()
error_dialog.destroy()
return
goal_line = doc.get_iter_at_line(line_no-1)
doc.place_cursor(goal_line)
#view.scroll_mark_onscreen(doc.get_insert())
view.scroll_to_mark(doc.get_insert(),0.25,True,0.0,0.5)
view.grab_focus()
def parse_landmark_text(self,text,type):
# Parse the landmark text (get rid of the trailing standardized header of a comment landmark:
if type != "function(" and type != "data.frame(":
# Landmark comment:
return text[len(landmark_comment_header):].strip()
else:
return text
def parse_R_document_for_landmarks(self,doc):
if not self._plugin.prefs['R_structure_enabled']:
# Widget disabled:
return
if not self._plugin.is_document_R_source_file(doc):
# Currently displaying a non-R file:
self.info_liststore.clear() # clear the listview of the old items
return
# Parse the R document held by doc for landmarks or function defintions and update the listview accordingly
# Save the current selection (if any):
self.selection = self.info_treeview.get_selection().get_selected_rows()[1]
self.info_liststore.clear() # clear the listview of the old items
# Get the whole text:
whole_text = doc.get_text(doc.get_start_iter(),doc.get_end_iter(),False)
# Search it for function defintions and landmark comments:
#start_time = time.clock() # timing for debug
matches = self._pattern_matcher.finditer(whole_text)
for match in matches:
# Get the corresponding position in the document for the match:
line_no = doc.get_iter_at_offset(match.start()).get_line()
start = doc.get_iter_at_line(line_no)
end = start.copy()
end.forward_line()
line_text = doc.get_text(start,end,False).strip()
# Add this info to the list:
self.info_liststore.append([str(line_no+1),(self.info_types['function'],(self.info_types['data.frame'],self.info_types['landmark'])[match.group() != "data.frame("])[not match.group() == "function("],self.parse_landmark_text(line_text,match.group()),xml.sax.saxutils.escape(line_text)])
#print (time.clock() - start_time)*1000
# Restore the old selection, if possible:
if len(self.selection) > 0:
# There was a selection:
self.info_treeview.set_cursor_on_cell(self.selection[0],None,None,False)
else:
# There was no selection: select the first item (if any):
self.info_treeview.set_cursor_on_cell(Gtk.TreePath(),None,None,False)
return
########################################################
# End GeditTerminal #
########################################################
# Send given text to R
def do_send_to_R( text_to_send, R_widget, as_source, max_lines_direct_send=50 ):
if not R_widget:
print _("No R console open?")
return
#print R_widget._plugin.prefs['echo_commands']
if as_source | (text_to_send.count("\n") > max_lines_direct_send):
# Write the text to a temp file and call source():
R_file = open( R_temp_file, 'w' )
R_file.write( text_to_send )
R_file.close()
R_widget.send_command('source("'+R_temp_file+'",echo=' + str(R_widget._plugin.prefs['echo_commands']).upper() + ',print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n')
else:
# Pipe directly to R:
R_widget.send_command(text_to_send)
# Check is a given line is empty or just a comment:
def is_empty_comment_line( line ):
# Skip all white spaces:
line_stripped = line.strip();
return (len(line_stripped) == 0) or (line_stripped[0] == '#');
class RCtrlWindowHelper(GObject.Object):
__gtype_name__ = "RCtrlWindowHelper"
def __init__(self, plugin, window):
GObject.Object.__init__(self)
self._window = window
self._plugin = plugin
self.datadir = plugin.get_data_dir();
self.R_widget = None
self.Detached_R_Dialog = None
# Init the RWizards:
self.rwizards = RWizardEngine(self)
# Insert menu items
self._insert_menu()
# And the R structure panel tab:
self._rstructurepanel = RStructurePanel(self)
def do_deactivate(self):
# Remove any installed menu items
self._remove_menu()
self._window = None
self._plugin = None
self._action_group = None
# and delete the temp file:
os.remove(R_temp_file)
def _insert_menu(self):
# Get the GtkUIManager
manager = self._window.get_ui_manager()
R_action = Gtk.Action("R","R","R plugin commands",None)
R_action_group = Gtk.ActionGroup("R")
R_action_group.add_action(R_action)
manager.insert_action_group(R_action_group, -1)
# Create a new action group
self._action_group = Gtk.ActionGroup("RCtrlPluginActions")
self._action_group.add_actions([("RCtrlLine", None, _("Run current line through R..."),
self._plugin.prefs['shortcut_RCtrlLine'], _("Run current line through R..."),
self.on_send_line_to_R),
("RCtrlSel", None, _("Run selection through R..."),
self._plugin.prefs['shortcut_RCtrlSel'], _("Run selection through R..."),
self.on_send_selection_to_R),
("RCtrlAll", None, _("Run whole file through R..."),
self._plugin.prefs['shortcut_RCtrlAll'], _("Run whole file through R..."),
self.on_send_file_to_R),
("RCtrlCursor", None, _("Run up to current line through R..."),
self._plugin.prefs['shortcut_RCtrlCursor'], _("Run up to current line through R..."),
self.on_send_cursor_to_R),
("RCtrlBlock1Run", None, _("Run block 1 through R..."),
self._plugin.prefs['shortcut_RCtrlBlock1Run'], _("Run block 1 through R..."),
self.on_send_block1_to_R),
("RCtrlBlock1Def", None, _("Define block 1..."),
self._plugin.prefs['shortcut_RCtrlBlock1Def'], _("Define block 1..."),
self.on_define_block1),
("RCtrlBlock2Run", None, _("Run block 2 through R..."),
self._plugin.prefs['shortcut_RCtrlBlock2Run'], _("Run block 2 through R..."),
self.on_send_block2_to_R),
("RCtrlBlock2Def", None, _("Define block 2..."),
self._plugin.prefs['shortcut_RCtrlBlock2Def'], _("Define block 2..."),
self.on_define_block2),
("RCtrlNewTab", None, _("Create new R workspace tab..."),
self._plugin.prefs['shortcut_RCtrlNewTab'], _("Create new R workspace tab (max 3 tabs allowed)..."),
self.on_create_new_R_tab),
("RCtrlConfig", None, _("Configure R interface"),
self._plugin.prefs['shortcut_RCtrlConfig'], _("Configure R interface"),
self.on_R_config_dialog),
("RCtrlUpdate", None, _("Check for updates"),
None, _("Check for updates"),
self.on_check_for_updates),
#("RCtrlLoadWorkspace", None, _("Load R Workspace"),
# self._plugin.prefs['shortcut_RCtrlLoadWorkspace'], _("Load R Workspace"),
# self.on_R_load_workspace),
#("RCtrlSaveWorkspace", None, _("Save R Workspace"),
# self._plugin.prefs['shortcut_RCtrlSaveWorkspace'], _("Save R Workspace"),
# self.on_R_save_workspace),
("RCtrlLandmark", None, _("Insert Landmark Comment"),
None, _("Insert Landmark Comment"),
self.on_R_LandmarkComment),
("RCtrlWizards", None, _("Wizards"),
None, _("Wizards"),
self.on_R_wizards),
#("RCtrlHelpSel", None, _("Search selection in R help"),
# self._plugin.prefs['shortcut_RCtrlHelpSel'], _("Search selection in R help"),
# self.on_R_search_selection_in_help),
#("RCtrlShowSel", None, _("Inspect selection using showData()"),
# self._plugin.prefs['shortcut_RCtrlShowSel'], _("Inspect selection using showData()"),
# self.on_R_show_selection),
#("RCtrlEditSel", None, _("Edit selection using fix()"),
# self._plugin.prefs['shortcut_RCtrlEditSel'], _("Edit selection using fix()"),
# self.on_R_edit_selection),
("RCtrlShowHide", None, _("Show/hide toolbar"),
None, _("Show/hide toolbar"),
self.on_R_showhide),
("RCtrlAttach", None, _("Attach/detach R Console"),
self._plugin.prefs['shortcut_RCtrlAttach'], _("Attach/detach R Console"),
self.on_R_attach),
("RCtrlClose", None, _("Close R Console"),
self._plugin.prefs['shortcut_RCtrlClose'], _("Close R Console"),
self.on_R_close),
("RCtrlHelpRCtrl", None, _("Help"),
None, _("Help"),
self.on_R_help),
("RCtrlAbout", None, _("About"),
None, _("About"),
self.on_R_about)])
# Insert the action group
manager.insert_action_group(self._action_group, 0)
# Merge the UI
self._ui_id = manager.add_ui_from_string(ui_str)
# Make them insensitive and invisible, depending on the action:
manager.get_action("/ToolBar/RCtrlLine").set_sensitive(False)
manager.get_action("/ToolBar/RCtrlSel").set_sensitive(False)
manager.get_action("/ToolBar/RCtrlAll").set_sensitive(False)
manager.get_action("/ToolBar/RCtrlCursor").set_sensitive(False)
manager.get_action("/ToolBar/RCtrlNewTab").set_sensitive(True)
manager.get_action("/MenuBar/R/RCtrlBlock1Run").set_sensitive(False)
manager.get_action("/MenuBar/R/RCtrlBlock2Run").set_sensitive(False)
manager.get_action("/MenuBar/R/RCtrlAttach").set_sensitive(False)
manager.get_action("/MenuBar/R/RCtrlClose").set_sensitive(False)
# Add the icons to the toolbar items:
RCtrlLine_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/run_line.png" , 24, 24)
RCtrlLine_icon.set_from_pixbuf(pixbuf)
RCtrlLine_icon.show()
RCtrlLine_toolitem = manager.get_widget("/ToolBar/RCtrlLine")
RCtrlLine_toolitem.set_icon_widget(RCtrlLine_icon)
RCtrlLine_toolitem.show()
RCtrlLine_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/run_line.png" , 24, 24)
RCtrlLine_icon.set_from_pixbuf(pixbuf)
RCtrlLine_icon.show()
RCtrlLine_menuitem = manager.get_widget("/MenuBar/R/RCtrlLine")
RCtrlLine_menuitem.set_image(RCtrlLine_icon)
RCtrlLine_menuitem.show()
RCtrlSel_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/run_selection.png" , 24, 24)
RCtrlSel_icon.set_from_pixbuf(pixbuf)
RCtrlSel_icon.show()
RCtrlSel_toolitem = manager.get_widget("/ToolBar/RCtrlSel")
RCtrlSel_toolitem.set_icon_widget(RCtrlSel_icon)
RCtrlSel_toolitem.show()
RCtrlSel_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/run_selection.png" , 24, 24)
RCtrlSel_icon.set_from_pixbuf(pixbuf)
RCtrlSel_icon.show()
RCtrlSel_menuitem = manager.get_widget("/MenuBar/R/RCtrlSel")
RCtrlSel_menuitem.set_image(RCtrlSel_icon)
RCtrlSel_menuitem.show()
RCtrlAll_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/run_all.png" , 24, 24)
RCtrlAll_icon.set_from_pixbuf(pixbuf)
RCtrlAll_icon.show()
RCtrlAll_toolitem = manager.get_widget("/ToolBar/RCtrlAll")
RCtrlAll_toolitem.set_icon_widget(RCtrlAll_icon)
RCtrlAll_toolitem.show()
RCtrlAll_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/run_all.png" , 24, 24)
RCtrlAll_icon.set_from_pixbuf(pixbuf)
RCtrlAll_icon.show()
RCtrlAll_menuitem = manager.get_widget("/MenuBar/R/RCtrlAll")
RCtrlAll_menuitem.set_image(RCtrlAll_icon)
RCtrlAll_menuitem.show()
RCtrlCursor_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/run_cursor.png" , 24, 24)
RCtrlCursor_icon.set_from_pixbuf(pixbuf)
RCtrlCursor_icon.show()
RCtrlCursor_toolitem = manager.get_widget("/ToolBar/RCtrlCursor")
RCtrlCursor_toolitem.set_icon_widget(RCtrlCursor_icon)
RCtrlCursor_toolitem.show()
RCtrlCursor_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/run_cursor.png" , 24, 24)
RCtrlCursor_icon.set_from_pixbuf(pixbuf)
RCtrlCursor_icon.show()
RCtrlCursor_menuitem = manager.get_widget("/MenuBar/R/RCtrlCursor")
RCtrlCursor_menuitem.set_image(RCtrlCursor_icon)
RCtrlCursor_menuitem.show()
RCtrlBlock1Run_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block1_run.png" , 24, 24)
RCtrlBlock1Run_icon.set_from_pixbuf(pixbuf)
RCtrlBlock1Run_icon.show()
RCtrlBlock1Run_toolitem = manager.get_widget("/ToolBar/RCtrlBlock1Run")
RCtrlBlock1Run_toolitem.set_icon_widget(RCtrlBlock1Run_icon)
RCtrlBlock1Run_toolitem.show()
RCtrlBlock1Run_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block1_run.png" , 24, 24)
RCtrlBlock1Run_icon.set_from_pixbuf(pixbuf)
RCtrlBlock1Run_icon.show()
RCtrlBlock1Run_menuitem = manager.get_widget("/MenuBar/R/RCtrlBlock1Run")
RCtrlBlock1Run_menuitem.set_image(RCtrlBlock1Run_icon)
RCtrlBlock1Run_menuitem.show()
RCtrlBlock1Def_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block1_def.png" , 24, 24)
RCtrlBlock1Def_icon.set_from_pixbuf(pixbuf)
RCtrlBlock1Def_icon.show()
RCtrlBlock1Def_toolitem = manager.get_widget("/ToolBar/RCtrlBlock1Def")
RCtrlBlock1Def_toolitem.set_icon_widget(RCtrlBlock1Def_icon)
RCtrlBlock1Def_toolitem.show()
RCtrlBlock1Def_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block1_def.png" , 24, 24)
RCtrlBlock1Def_icon.set_from_pixbuf(pixbuf)
RCtrlBlock1Def_icon.show()
RCtrlBlock1Def_menuitem = manager.get_widget("/MenuBar/R/RCtrlBlock1Def")
RCtrlBlock1Def_menuitem.set_image(RCtrlBlock1Def_icon)
RCtrlBlock1Def_menuitem.show()
RCtrlBlock2Run_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block2_run.png" , 24, 24)
RCtrlBlock2Run_icon.set_from_pixbuf(pixbuf)
RCtrlBlock2Run_icon.show()
RCtrlBlock2Run_toolitem = manager.get_widget("/ToolBar/RCtrlBlock2Run")
RCtrlBlock2Run_toolitem.set_icon_widget(RCtrlBlock2Run_icon)
RCtrlBlock2Run_toolitem.show()
RCtrlBlock2Run_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block2_run.png" , 24, 24)
RCtrlBlock2Run_icon.set_from_pixbuf(pixbuf)
RCtrlBlock2Run_icon.show()
RCtrlBlock2Run_menuitem = manager.get_widget("/MenuBar/R/RCtrlBlock2Run")
RCtrlBlock2Run_menuitem.set_image(RCtrlBlock2Run_icon)
RCtrlBlock2Run_menuitem.show()
RCtrlBlock2Def_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block2_def.png" , 24, 24)
RCtrlBlock2Def_icon.set_from_pixbuf(pixbuf)
RCtrlBlock2Def_icon.show()
RCtrlBlock2Def_toolitem = manager.get_widget("/ToolBar/RCtrlBlock2Def")
RCtrlBlock2Def_toolitem.set_icon_widget(RCtrlBlock2Def_icon)
RCtrlBlock2Def_toolitem.show()
RCtrlBlock2Def_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block2_def.png" , 24, 24)
RCtrlBlock2Def_icon.set_from_pixbuf(pixbuf)
RCtrlBlock2Def_icon.show()
RCtrlBlock2Def_menuitem = manager.get_widget("/MenuBar/R/RCtrlBlock2Def")
RCtrlBlock2Def_menuitem.set_image(RCtrlBlock2Def_icon)
RCtrlBlock2Def_menuitem.show()
RCtrlNewTab_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/new_workspace.png" , 24, 24)
RCtrlNewTab_icon.set_from_pixbuf(pixbuf)
RCtrlNewTab_icon.show()
RCtrlNewTab_toolitem = manager.get_widget("/ToolBar/RCtrlNewTab")
RCtrlNewTab_toolitem.set_icon_widget(RCtrlNewTab_icon)
RCtrlNewTab_toolitem.show()
RCtrlNewTab_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/new_workspace.png" , 24, 24)
RCtrlNewTab_icon.set_from_pixbuf(pixbuf)
RCtrlNewTab_icon.show()
RCtrlNewTab_menuitem = manager.get_widget("/MenuBar/R/RCtrlNewTab")
RCtrlNewTab_menuitem.set_image(RCtrlNewTab_icon)
RCtrlNewTab_menuitem.show()
#RCtrlConfig_icon = Gtk.Image()
#pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/config.png" , 24, 24)
#RCtrlConfig_icon.set_from_pixbuf(pixbuf)
#RCtrlConfig_icon.show()
#RCtrlConfig_toolitem = manager.get_widget("/ToolBar/RCtrlConfig")
#RCtrlConfig_toolitem.set_icon_widget(RCtrlConfig_icon)
#RCtrlConfig_toolitem.show()
RCtrlConfig_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/config.png" , 24, 24)
RCtrlConfig_icon.set_from_pixbuf(pixbuf)
RCtrlConfig_icon.show()
RCtrlConfig_menuitem = manager.get_widget("/MenuBar/R/RCtrlConfig")
RCtrlConfig_menuitem.set_image(RCtrlConfig_icon)
RCtrlConfig_menuitem.show()
RCtrlAttach_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/attachdetach.png" , 24, 24)
RCtrlAttach_icon.set_from_pixbuf(pixbuf)
RCtrlAttach_icon.show()
RCtrlAttach_menuitem = manager.get_widget("/MenuBar/R/RCtrlAttach")
RCtrlAttach_menuitem.set_image(RCtrlAttach_icon)
RCtrlAttach_menuitem.show()
RCtrlClose_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/closeRconsole.png" , 24, 24)
RCtrlClose_icon.set_from_pixbuf(pixbuf)
RCtrlClose_icon.show()
RCtrlClose_menuitem = manager.get_widget("/MenuBar/R/RCtrlClose")
RCtrlClose_menuitem.set_image(RCtrlClose_icon)
RCtrlClose_menuitem.show()
RCtrlLandmark_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/landmark_comment.png" , 24, 24)
RCtrlLandmark_icon.set_from_pixbuf(pixbuf)
RCtrlLandmark_icon.show()
RCtrlLandmark_menuitem = manager.get_widget("/MenuBar/R/RCtrlLandmark")
RCtrlLandmark_menuitem.set_image(RCtrlLandmark_icon)
RCtrlLandmark_menuitem.show()
#RCtrlHelpSel_icon = Gtk.Image()
#pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/selection_help.png" , 24, 24)
#RCtrlHelpSel_icon.set_from_pixbuf(pixbuf)
#RCtrlHelpSel_icon.show()
#RCtrlHelpSel_menuitem = manager.get_widget("/MenuBar/R/RCtrlHelpSel")
#RCtrlHelpSel_menuitem.set_image(RCtrlHelpSel_icon)
#RCtrlHelpSel_menuitem.show()
#
#RCtrlShowSel_icon = Gtk.Image()
#pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/selection_showdata.png" , 24, 24)
#RCtrlShowSel_icon.set_from_pixbuf(pixbuf)
#RCtrlShowSel_icon.show()
#RCtrlShowSel_menuitem = manager.get_widget("/MenuBar/R/RCtrlShowSel")
#RCtrlShowSel_menuitem.set_image(RCtrlShowSel_icon)
#RCtrlShowSel_menuitem.show()
#
#RCtrlEditSel_icon = Gtk.Image()
#pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/selection_editdata.png" , 24, 24)
#RCtrlEditSel_icon.set_from_pixbuf(pixbuf)
#RCtrlEditSel_icon.show()
#RCtrlEditSel_menuitem = manager.get_widget("/MenuBar/R/RCtrlEditSel")
#RCtrlEditSel_menuitem.set_image(RCtrlEditSel_icon)
#RCtrlEditSel_menuitem.show()
RCtrlHelpRCtrl_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/help.png" , 24, 24)
RCtrlHelpRCtrl_icon.set_from_pixbuf(pixbuf)
RCtrlHelpRCtrl_icon.show()
RCtrlHelpRCtrl_menuitem = manager.get_widget("/MenuBar/R/RCtrlHelpRCtrl")
RCtrlHelpRCtrl_menuitem.set_image(RCtrlHelpRCtrl_icon)
RCtrlHelpRCtrl_menuitem.show()
RCtrlAbout_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/Rgedit-icon.png" , 24, 24)
RCtrlAbout_icon.set_from_pixbuf(pixbuf)
RCtrlAbout_icon.show()
RCtrlAbout_menuitem = manager.get_widget("/MenuBar/R/RCtrlAbout")
RCtrlAbout_menuitem.set_image(RCtrlAbout_icon)
RCtrlAbout_menuitem.show()
#RCtrlLoadWorkspace_icon = Gtk.Image()
#pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/load_workspace.png" , 24, 24)
#RCtrlLoadWorkspace_icon.set_from_pixbuf(pixbuf)
#RCtrlLoadWorkspace_icon.show()
#RCtrlLoadWorkspace_menuitem = manager.get_widget("/MenuBar/R/RCtrlLoadWorkspace")
#RCtrlLoadWorkspace_menuitem.set_image(RCtrlLoadWorkspace_icon)
#RCtrlLoadWorkspace_menuitem.show()
#
#RCtrlSaveWorkspace_icon = Gtk.Image()
#pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/save_workspace.png" , 24, 24)
#RCtrlSaveWorkspace_icon.set_from_pixbuf(pixbuf)
#RCtrlSaveWorkspace_icon.show()
#RCtrlSaveWorkspace_menuitem = manager.get_widget("/MenuBar/R/RCtrlSaveWorkspace")
#RCtrlSaveWorkspace_menuitem.set_image(RCtrlSaveWorkspace_icon)
#RCtrlSaveWorkspace_menuitem.show()
# Insert the show/hide toolitem submenu:
ShowHideMenu = manager.get_widget("/MenuBar/R/RCtrlShowHide")
ShowHideSubmenu = Gtk.Menu()
ShowRUI = Gtk.CheckMenuItem()
ShowRUI.set_label(_("Show toolbar only for R files..."))
ShowRUI.connect("toggled",self.on_toggle_ShowRUI)
ShowRUI.set_active(self._plugin.prefs['show_rgedit_UI_only_for_R_mime_types'])
ShowRUI.show()
self.on_toggle_ShowRUI(ShowRUI)
Separator = Gtk.SeparatorMenuItem()
Separator.show()
ShowHideLine = Gtk.CheckMenuItem()
ShowHideLine.set_label(_("Run current line through R..."))
ShowHideLine.connect("toggled",self.on_toggle_ShowHideLine)
ShowHideLine.set_active(self._plugin.prefs['show_run_line'])
ShowHideLine.show()
self.on_toggle_ShowHideLine(ShowHideLine)
ShowHideSel = Gtk.CheckMenuItem()
ShowHideSel.set_label(_("Run current selection through R..."))
ShowHideSel.connect("toggled",self.on_toggle_ShowHideSel)
ShowHideSel.set_active(self._plugin.prefs['show_run_sel'])
ShowHideSel.show()
self.on_toggle_ShowHideSel(ShowHideSel)
ShowHideAll = Gtk.CheckMenuItem()
ShowHideAll.set_label(_("Run whole file through R..."))
ShowHideAll.connect("toggled",self.on_toggle_ShowHideAll)
ShowHideAll.set_active(self._plugin.prefs['show_run_all'])
ShowHideAll.show()
self.on_toggle_ShowHideAll(ShowHideAll)
ShowHideCursor = Gtk.CheckMenuItem()
ShowHideCursor.set_label(_("Run up to current line through R..."))
ShowHideCursor.connect("toggled",self.on_toggle_ShowHideCursor)
ShowHideCursor.set_active(self._plugin.prefs['show_run_cursor'])
ShowHideCursor.show()
self.on_toggle_ShowHideCursor(ShowHideCursor)
ShowHideBlock1Run = Gtk.CheckMenuItem()
ShowHideBlock1Run.set_label(_("Run block 1 through R..."))
ShowHideBlock1Run.connect("toggled",self.on_toggle_ShowHideBlock1Run)
ShowHideBlock1Run.set_active(self._plugin.prefs['show_run_block1'])
ShowHideBlock1Run.show()
self.on_toggle_ShowHideBlock1Run(ShowHideBlock1Run)
ShowHideBlock1Def = Gtk.CheckMenuItem()
ShowHideBlock1Def.set_label(_("Define block 1..."))
ShowHideBlock1Def.connect("toggled",self.on_toggle_ShowHideBlock1Def)
ShowHideBlock1Def.set_active(self._plugin.prefs['show_def_block1'])
ShowHideBlock1Def.show()
self.on_toggle_ShowHideBlock1Def(ShowHideBlock1Def)
ShowHideBlock2Run = Gtk.CheckMenuItem()
ShowHideBlock2Run.set_label(_("Run block 2 through R..."))
ShowHideBlock2Run.connect("toggled",self.on_toggle_ShowHideBlock2Run)
ShowHideBlock2Run.set_active(self._plugin.prefs['show_run_block2'])
ShowHideBlock2Run.show()
self.on_toggle_ShowHideBlock2Run(ShowHideBlock2Run)
ShowHideBlock2Def = Gtk.CheckMenuItem()
ShowHideBlock2Def.set_label(_("Define block 2..."))
ShowHideBlock2Def.connect("toggled",self.on_toggle_ShowHideBlock2Def)
ShowHideBlock2Def.set_active(self._plugin.prefs['show_def_block2'])
ShowHideBlock2Def.show()
self.on_toggle_ShowHideBlock2Def(ShowHideBlock2Def)
ShowHideNewTab = Gtk.CheckMenuItem()
ShowHideNewTab.set_label(_("Create new R workspace tab..."))
ShowHideNewTab.connect("toggled",self.on_toggle_ShowHideNewTab)
ShowHideNewTab.set_active(self._plugin.prefs['show_new_tab'])
ShowHideNewTab.show()
self.on_toggle_ShowHideNewTab(ShowHideNewTab)
ShowHideSubmenu.attach(ShowHideLine,0,1,0,1)
ShowHideSubmenu.attach(ShowHideSel,0,1,1,2)
ShowHideSubmenu.attach(ShowHideAll,0,1,2,3)
ShowHideSubmenu.attach(ShowHideCursor,0,1,3,4)
ShowHideSubmenu.attach(ShowHideBlock1Run,0,1,4,5)
ShowHideSubmenu.attach(ShowHideBlock1Def,0,1,5,6)
ShowHideSubmenu.attach(ShowHideBlock2Run,0,1,6,7)
ShowHideSubmenu.attach(ShowHideBlock2Def,0,1,7,8)
ShowHideSubmenu.attach(ShowHideNewTab,0,1,8,9)
ShowHideSubmenu.attach(Separator,0,1,9,10)
ShowHideSubmenu.attach(ShowRUI,0,1,10,11)
ShowHideMenu.set_submenu(ShowHideSubmenu)
#Fill in the wizards menu:
self.fill_in_wizards_menu(manager.get_widget("/MenuBar/R/RCtrlWizards"))
# Make the attach menu a check menu:
self.RConsole_attach = not self._plugin.prefs['RConsole_start_attached']
self.on_R_attach(None)
# Also create the bottom panel widget if autostart is enabled:
if self._plugin.prefs['autostart_R_console'] == True:
self.createRGeditTerminal()
# Menu activate handlers
def on_send_line_to_R(self, action, param=None):
doc = self._window.get_active_document()
if not doc:
return
view = self._window.get_active_view()
if not view:
return
# The last line in the file:
last_line = doc.get_end_iter().get_line()
# If required so, try to send a non-empty and non-comment line,otherwise just the current line:
while True:
# Get the current line and send it:
cur_line = doc.get_iter_at_mark(doc.get_insert()).get_line()
start = doc.get_iter_at_line(cur_line)
end=start.copy()
end.forward_line()
sel_text = doc.get_text(start,end,False)
# Chek if the line is empty or a comment line:
empty_or_comment = self._plugin.prefs['skip_empty_and_comment_lines'] and is_empty_comment_line(sel_text)
if not empty_or_comment:
if len(sel_text) == 0 or sel_text[-1] != '\n' and sel_text[-1] != '\r':
sel_text = sel_text + '\n'
do_send_to_R( sel_text, self.R_widget, False ) # send always as source
# and advance to the next line:
if self._plugin.prefs['advance_to_next_line']:
doc.goto_line(cur_line+1)
view.scroll_mark_onscreen(doc.get_insert())
if (not empty_or_comment) or (cur_line >= last_line):
# That was it!
break;
def on_send_selection_to_R(self, action, param=None):
doc = self._window.get_active_document()
if not doc:
return
# See if anything is selected:
if doc.get_has_selection():
sel_bounds = doc.get_selection_bounds()
sel_text = doc.get_text(sel_bounds[0],sel_bounds[1],False)
if sel_text[-1] != '\n' and sel_text[-1] != '\r':
sel_text = sel_text + '\n'
do_send_to_R( sel_text, self.R_widget, False, self._plugin.prefs['max_lines_as_text'] )
def on_send_file_to_R(self, action, param=None):
doc = self._window.get_active_document()
if not doc:
return
sel_text = doc.get_text(doc.get_start_iter(),doc.get_end_iter(),False)
do_send_to_R( sel_text, self.R_widget, True )
def on_send_cursor_to_R(self, action, param=None):
doc = self._window.get_active_document()
if not doc:
return
cur_line = doc.get_iter_at_mark(doc.get_insert()).get_line()
end = doc.get_iter_at_line(cur_line)
end.forward_line()
sel_text = doc.get_text(doc.get_start_iter(),end,False)
do_send_to_R( sel_text, self.R_widget, True )
def on_send_block1_to_R(self, action, param=None):
doc = self._window.get_active_document()
if not doc:
return
# Get the block positions (if any):
try:
block1_start = doc.get_iter_at_mark(doc.get_mark("RBlock1Start"))
block1_end = doc.get_iter_at_mark(doc.get_mark("RBlock1End"))
block1_end.forward_line()
sel_text = doc.get_text(block1_start,block1_end,False)
do_send_to_R( sel_text, self.R_widget, True )
except:
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, _("Block 1 is not defined in the current document!") )
error_dialog.run()
error_dialog.destroy()
return
def on_define_block1(self, action, param=None):
doc = self._window.get_active_document()
if not doc:
return
# See if anything is selected:
if not doc.get_has_selection():
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, _("You need a selection in order to define a block!") )
error_dialog.run()
error_dialog.destroy()
return
# Prepare the view:
view = self._window.get_active_view()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block1_start.png" , 24, 24)
mark_attr = GtkSource.MarkAttributes()
mark_attr.set_pixbuf(pixbuf)
mark_color = Gdk.RGBA()
mark_color.parse("lightblue")
mark_attr.set_background(mark_color)
view.set_mark_attributes("RBlock1Start",mark_attr,100)
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block1_end.png" , 24, 24)
mark_attr = GtkSource.MarkAttributes()
mark_attr.set_pixbuf(pixbuf)
mark_color = Gdk.RGBA()
mark_color.parse("lightblue")
mark_attr.set_background(mark_color)
view.set_mark_attributes("RBlock1End",mark_attr,100)
try:
view.set_show_line_marks(True)
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use set_show_line_markers:
view.set_show_line_markers(True)
# Delete any previously existing:
try:
doc.remove_source_marks(doc.get_start_iter(),doc.get_end_iter(),"RBlock1Start")
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use delete_marker:
marker_to_delete = doc.get_marker("RBlock1Start")
if marker_to_delete != None:
doc.delete_marker(marker_to_delete)
try:
doc.remove_source_marks(doc.get_start_iter(),doc.get_end_iter(),"RBlock1End")
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use delete_marker:
marker_to_delete = doc.get_marker("RBlock1End")
if marker_to_delete != None:
doc.delete_marker(marker_to_delete)
# And create the new one here:
sel_bounds = doc.get_selection_bounds()
cur_line = sel_bounds[0].get_line()
start = doc.get_iter_at_line(cur_line)
try:
block_start_mark = doc.create_source_mark("RBlock1Start","RBlock1Start",start)
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use create_marker:
block_start_mark = doc.create_marker("RBlock1Start","RBlock1Start",start)
block_start_mark.set_visible(True)
cur_line = sel_bounds[1].get_line()
end = doc.get_iter_at_line(cur_line)
#end.forward_line()
try:
block_start_mark = doc.create_source_mark("RBlock1End","RBlock1End",end)
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use create_marker:
block_start_mark = doc.create_marker("RBlock1End","RBlock1End",end)
block_start_mark.set_visible(True)
def on_send_block2_to_R(self, action, param=None):
doc = self._window.get_active_document()
if not doc:
return
# Get the block positions (if any):
try:
block2_start = doc.get_iter_at_mark(doc.get_mark("RBlock2Start"))
block2_end = doc.get_iter_at_mark(doc.get_mark("RBlock2End"))
block2_end.forward_line()
sel_text = doc.get_text(block2_start,block2_end,False)
do_send_to_R( sel_text, self.R_widget, True )
except:
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, _("Block 2 is not defined in the current document!") )
error_dialog.run()
error_dialog.destroy()
return
def on_define_block2(self, action, param=None):
doc = self._window.get_active_document()
if not doc:
return
# See if anything is selected:
if not doc.get_has_selection():
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, _("You need a selection in order to define a block!") )
error_dialog.run()
error_dialog.destroy()
return
# Prepare the view:
view = self._window.get_active_view()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block2_start.png" , 24, 24)
mark_attr = GtkSource.MarkAttributes()
mark_attr.set_pixbuf(pixbuf)
mark_color = Gdk.RGBA()
mark_color.parse("gold")
mark_attr.set_background(mark_color)
view.set_mark_attributes("RBlock2Start",mark_attr,100)
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.datadir+"/block2_end.png" , 24, 24)
mark_attr = GtkSource.MarkAttributes()
mark_attr.set_pixbuf(pixbuf)
mark_color = Gdk.RGBA()
mark_color.parse("gold")
mark_attr.set_background(mark_color)
view.set_mark_attributes("RBlock2End",mark_attr,100)
try:
view.set_show_line_marks(True)
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use set_show_line_markers:
view.set_show_line_markers(True)
# Delete any previously existing:
try:
doc.remove_source_marks(doc.get_start_iter(),doc.get_end_iter(),"RBlock2Start")
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use delete_marker:
marker_to_delete = doc.get_marker("RBlock2Start")
if marker_to_delete != None:
doc.delete_marker(marker_to_delete)
try:
doc.remove_source_marks(doc.get_start_iter(),doc.get_end_iter(),"RBlock2End")
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use delete_marker:
marker_to_delete = doc.get_marker("RBlock2End")
if marker_to_delete != None:
doc.delete_marker(marker_to_delete)
# And create the new one here:
sel_bounds = doc.get_selection_bounds()
cur_line = sel_bounds[0].get_line()
start = doc.get_iter_at_line(cur_line)
try:
block_start_mark = doc.create_source_mark("RBlock2Start","RBlock2Start",start)
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use create_marker:
block_start_mark = doc.create_marker("RBlock2Start","RBlock2Start",start)
block_start_mark.set_visible(True)
cur_line = sel_bounds[1].get_line()
end = doc.get_iter_at_line(cur_line)
#end.forward_line()
try:
block_start_mark = doc.create_source_mark("RBlock2End","RBlock2End",end)
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use create_marker:
block_start_mark = doc.create_marker("RBlock2End","RBlock2End",end)
block_start_mark.set_visible(True)
def on_create_new_R_tab(self, action, param=None):
if self.R_widget == None:
self.createRGeditTerminal()
else:
self.R_widget.create_new_R_tab()
def on_R_config_dialog(self, action, param=None):
dialog = self._plugin.create_configure_dialog()
dialog.run()
dialog.destroy()
def on_check_for_updates(self, action, param=None):
# Get the current version:
about_ui = create_UI_from_file_GtkBuilder_or_Glade(self._plugin.get_data_dir()+"/About.glade",self._plugin.get_data_dir()+"/About.ui")
current_version = get_widget_from_ui_GtkBuilder_or_Glade(about_ui,'AboutDialog').get_version()
# And the current version of the official wizards pack:
wizards_pack_version_file = open( self._plugin.get_data_dir() + str("/Wizards/wizards.version"), "rt" )
wizards_current_version = wizards_pack_version_file.read()
wizards_current_version = wizards_current_version.strip()
wizards_pack_version_file.close()
# And the latest version available on the server:
try:
latest_version = urllib2.urlopen('http://rgedit.sourceforge.net/latest.version.gtk3').read()
except:
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Cannot read the latest available version from rgedit's website!\nPlease, try again later...") )
error_dialog.run()
error_dialog.destroy()
return
try:
wizards_latest_version = urllib2.urlopen('http://rgedit.sourceforge.net/wizards.latest.version').read()
except:
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Cannot read the latest available version of the wizards package from rgedit's website!\nPlease, try again later...") )
error_dialog.run()
error_dialog.destroy()
return
# Compare the two versions:
if current_version.strip().lower() == latest_version.strip().lower() and wizards_current_version.strip().lower() == wizards_latest_version.strip().lower():
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, _("You have the latest version of rgedit (") + current_version.strip() + _(") and official wizards package (") + wizards_current_version.strip() + _(") installed.") )
response = question_dialog.run()
question_dialog.destroy()
elif current_version.strip().lower() != latest_version.strip().lower() and wizards_current_version.strip().lower() != wizards_latest_version.strip().lower():
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, _("You have version ") + current_version.strip() + _(" of rgedit installed, but the newer ") + latest_version.strip() + _(" is available, and version ") + wizards_current_version.strip() + _(" of the official wizards package installed, but the newer ") + wizards_latest_version.strip() + _(" is available.\n Would you like to download them?") )
response = question_dialog.run()
question_dialog.destroy()
if response == Gtk.ResponseType.YES:
webbrowser.open("http://rgedit.sourceforge.net/")
elif current_version.strip().lower() != latest_version.strip().lower() and wizards_current_version.strip().lower() == wizards_latest_version.strip().lower():
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, _("You have version ") + current_version.strip() + _(" of rgedit installed, but the newer ") + latest_version.strip() + _(" is available.\n Would you like to download it?") )
response = question_dialog.run()
question_dialog.destroy()
if response == Gtk.ResponseType.YES:
webbrowser.open("http://rgedit.sourceforge.net/")
else:
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, _("You have version ") + wizards_current_version.strip() + _(" of the official wizards package installed, but the newer ") + wizards_latest_version.strip() + _(" is available.\n Would you like to download it?") )
response = question_dialog.run()
question_dialog.destroy()
if response == Gtk.ResponseType.YES:
webbrowser.open("http://rgedit.sourceforge.net/")
def on_R_LandmarkComment(self,action, param=None):
self._plugin.on_context_menu_landmark(None,self._window.get_active_document())
return
def on_R_wizards(self,action, param=None):
return
def on_R_showhide(self,action, param=None):
return
def on_R_attach(self,action, param=None):
self.RConsole_attach = not self.RConsole_attach
manager = self._window.get_ui_manager()
AttachMenuItem = manager.get_widget("/MenuBar/R/RCtrlAttach")
if self.RConsole_attach:
AttachMenuItem.get_child().set_label('Attach R Console')
if action != None:
self.create_R_detached_dialog()
else:
AttachMenuItem.get_child().set_label('Detach R Console')
if action != None:
self.destroy_R_detached_dialog()
#print "self.RConsole_attach is " + str(self.RConsole_attach)
def on_R_close(self,action, param=None):
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, _("Are you sure you want to completely close the R console?\nAll open tabs will also be closed!") )
response = question_dialog.run()
question_dialog.destroy()
if response == Gtk.ResponseType.YES:
manager = self._window.get_ui_manager()
# Make them insensitive and invisible, depending on the action:
manager.get_action("/ToolBar/RCtrlLine").set_sensitive(False)
manager.get_action("/ToolBar/RCtrlSel").set_sensitive(False)
manager.get_action("/ToolBar/RCtrlAll").set_sensitive(False)
manager.get_action("/ToolBar/RCtrlCursor").set_sensitive(False)
manager.get_action("/ToolBar/RCtrlNewTab").set_sensitive(True)
#manager.get_action("/ToolBar/RCtrlConfig").set_sensitive(True)
manager.get_action("/MenuBar/R/RCtrlBlock1Run").set_sensitive(False)
manager.get_action("/MenuBar/R/RCtrlBlock2Run").set_sensitive(False)
#manager.get_action("/MenuBar/R/RCtrlLoadWorkspace").set_sensitive(False)
#manager.get_action("/MenuBar/R/RCtrlSaveWorkspace").set_sensitive(False)
#manager.get_action("/MenuBar/R/RCtrlHelpSel").set_sensitive(False)
#manager.get_action("/MenuBar/R/RCtrlShowSel").set_sensitive(False)
#manager.get_action("/MenuBar/R/RCtrlEditSel").set_sensitive(False)
manager.get_action("/MenuBar/R/RCtrlAttach").set_sensitive(False)
manager.get_action("/MenuBar/R/RCtrlClose").set_sensitive(False)
# Close it!
if self.R_widget._vte != None:
self.R_widget.kill_shell_process(self.R_widget._vte1_shell_PID)
self.R_widget._vte1_shell_PID = -1
if self.R_widget._vte2 != None:
self.R_widget.kill_shell_process(self.R_widget._vte2_shell_PID)
self.R_widget._vte2_shell_PID = -1
if self.R_widget._vte3 != None:
self.R_widget.kill_shell_process(self.R_widget._vte3_shell_PID)
self.R_widget._vte3_shell_PID = -1
## Give them time to exit
#time.sleep(1)
self.R_widget.destroy()
self.R_widget = None
if self.RConsole_attach and self.Detached_R_Dialog != None:
self.Detached_R_Dialog.destroy()
self.Detached_R_Dialog = None
if not self.RConsole_attach and self.bottom_panel_dummy_hbox != None:
self._window.get_bottom_panel().remove_item(self.bottom_panel_dummy_hbox)
def update_R_consoles(self,vte1_console_changed,vte2_console_changed,vte3_console_changed,vte1_R_options_changed,vte2_R_options_changed,vte3_R_options_changed):
# Update the R consoles because some options have changed
if self.R_widget != None:
self.R_widget.reconfigure_vtes(vte1_console_changed,vte2_console_changed,vte3_console_changed,vte1_R_options_changed,vte2_R_options_changed,vte3_R_options_changed)
def on_R_help(self,action, param=None):
webbrowser.open(self.datadir+"/Help/Help.html")
def on_R_about(self,action, param=None):
about_ui = create_UI_from_file_GtkBuilder_or_Glade(self._plugin.get_data_dir()+"/About.glade",self._plugin.get_data_dir()+"/About.ui")
about_dialog = get_widget_from_ui_GtkBuilder_or_Glade(about_ui,"AboutDialog")
about_dialog.run()
about_dialog.destroy()
def on_toggle_ShowRUI(self,checkmenuitem, param=None):
self._plugin.prefs['show_rgedit_UI_only_for_R_mime_types'] = checkmenuitem.get_active()
self._plugin.show_hide_toolbar_and_friends(self._window.get_active_document())
self._plugin.save_prefs()
def on_toggle_ShowHideLine(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlLineToolitem = manager.get_widget("/ToolBar/RCtrlLine")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlLineToolitem.show()
else:
RCtrlLineToolitem.hide()
self._plugin.prefs['show_run_line'] = checkmenuitem.get_active()
self._plugin.save_prefs()
def on_toggle_ShowHideSel(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlSelToolitem = manager.get_widget("/ToolBar/RCtrlSel")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlSelToolitem.show()
else:
RCtrlSelToolitem.hide()
self._plugin.prefs['show_run_sel'] = checkmenuitem.get_active()
self._plugin.save_prefs()
def on_toggle_ShowHideAll(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlAllToolitem = manager.get_widget("/ToolBar/RCtrlAll")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlAllToolitem.show()
else:
RCtrlAllToolitem.hide()
self._plugin.prefs['show_run_all'] = checkmenuitem.get_active()
self._plugin.save_prefs()
def on_toggle_ShowHideCursor(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlCursorToolitem = manager.get_widget("/ToolBar/RCtrlCursor")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlCursorToolitem.show()
else:
RCtrlCursorToolitem.hide()
self._plugin.prefs['show_run_cursor'] = checkmenuitem.get_active()
self._plugin.save_prefs()
def on_toggle_ShowHideBlock1Run(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlBlock1RunToolitem = manager.get_widget("/ToolBar/RCtrlBlock1Run")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlBlock1RunToolitem.show()
else:
RCtrlBlock1RunToolitem.hide()
self._plugin.prefs['show_run_block1'] = checkmenuitem.get_active()
self._plugin.save_prefs()
def on_toggle_ShowHideBlock1Def(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlBlock1DefToolitem = manager.get_widget("/ToolBar/RCtrlBlock1Def")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlBlock1DefToolitem.show()
else:
RCtrlBlock1DefToolitem.hide()
self._plugin.prefs['show_def_block1'] = checkmenuitem.get_active()
self._plugin.save_prefs()
def on_toggle_ShowHideBlock2Run(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlBlock2RunToolitem = manager.get_widget("/ToolBar/RCtrlBlock2Run")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlBlock2RunToolitem.show()
else:
RCtrlBlock2RunToolitem.hide()
self._plugin.prefs['show_run_block2'] = checkmenuitem.get_active()
self._plugin.save_prefs()
def on_toggle_ShowHideBlock2Def(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlBlock2DefToolitem = manager.get_widget("/ToolBar/RCtrlBlock2Def")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlBlock2DefToolitem.show()
else:
RCtrlBlock2DefToolitem.hide()
self._plugin.prefs['show_def_block2'] = checkmenuitem.get_active()
self._plugin.save_prefs()
def on_toggle_ShowHideNewTab(self,checkmenuitem, param=None):
manager = self._window.get_ui_manager()
RCtrlNewTabToolitem = manager.get_widget("/ToolBar/RCtrlNewTab")
if checkmenuitem.get_active() and self._plugin.show_gedit_UI:
RCtrlNewTabToolitem.show()
else:
RCtrlNewTabToolitem.hide()
self._plugin.prefs['show_new_tab'] = checkmenuitem.get_active()
self._plugin.save_prefs()
#Fill in the wizards menu:
def fill_in_wizards_menu(self,WizardsMenu, param=None):
# Create a data structure which retains the menu (sub)paths and the associated menu item (to avoid menu duplications)
# This is, in fact, a dictionary having as the key the path
self.submenu_dictionary = {}
if len(self.rwizards.wizards) > 0:
WizardsSubmenu = Gtk.Menu()
# The About... menu first:
about_menu_item = Gtk.ImageMenuItem()
about_menu_item.set_label(_("About Rwizards..."))
try:
menu_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.rwizards.wizards[1]._rwizardengine.path+"wizard.png",16,16)
menu_icon.set_from_pixbuf(pixbuf)
menu_icon.show()
about_menu_item.set_image(menu_icon)
except:
pass
about_menu_item.show()
about_menu_item.connect("activate",self.on_about_rwizards,self.rwizards.wizards[1]._rwizardengine.path+"wizard.png")
WizardsSubmenu.append(about_menu_item)
# The submenus:
for wizard in self.rwizards.wizards:
# Make sure a reasonable menu path exists and return the actual menu path:
self.create_submenu_path( WizardsSubmenu, wizard.ActualMenu, wizard.Description, wizard._rwizardengine.path+wizard.ActualIcon, 1 )
WizardsMenu.set_submenu(WizardsSubmenu)
menu_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(wizard._rwizardengine.path+"wizard.png",16,16)
menu_icon.set_from_pixbuf(pixbuf)
menu_icon.show()
WizardsMenu.set_image(menu_icon)
def create_submenu_path(self,current_submenu,submenu_path,item_description,item_icon,cur_depth):
# Parse the submenu_path and keep at most max_submenu_path_depth levels:
splitted_path = submenu_path.split("/")
if cur_depth > 5 or cur_depth >= len(splitted_path):
actual_menu_item = Gtk.ImageMenuItem()
actual_menu_item.set_label(item_description)
try:
menu_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(item_icon,16,16)
menu_icon.set_from_pixbuf(pixbuf)
menu_icon.show()
actual_menu_item.set_image(menu_icon)
except:
pass
actual_menu_item.show()
actual_menu_item.connect("activate",self.on_wizard_activated,item_description)
current_submenu.append(actual_menu_item)
return
curr_item = splitted_path[cur_depth]
#print "Attempting to create wizard submenu:" + curr_item
# See if the menu path aredy exists:
cur_sub_path = "/".join(splitted_path[:(cur_depth+1)])
#print "get_widget: /MenuBar/R/RCtrlWizards"+cur_sub_path
# Recursion:
already_defined = False
if not cur_sub_path in self.submenu_dictionary:
# Create it:
submenu_item = Gtk.MenuItem()
submenu_item.set_label(curr_item)
submenu_item.show()
submenu_submenu = Gtk.Menu()
current_submenu.append(submenu_item)
self.submenu_dictionary[cur_sub_path] = submenu_submenu
else:
# Reuse it:
submenu_submenu = self.submenu_dictionary[cur_sub_path]
already_defined = True
self.create_submenu_path(submenu_submenu,submenu_path,item_description,item_icon,cur_depth+1)
if not already_defined:
submenu_item.set_submenu(submenu_submenu)
return
def on_wizard_activated(self,widget,data):
# A wizard was clicked and data contains its description:
# Identify the wizard and call it:
found = False
for wizard in self.rwizards.wizards:
if wizard.Description == data:
# Call the wizard:
wizard.run()
found = True
break
if not found:
print _("Something fishy: cannot find the wizard with description \"") + data + "\"..."
def on_about_rwizards(self,widget,icon):
# Get the current version of the official wizards pack:
wizards_pack_version_file = open( self._plugin.get_data_dir() + str("/Wizards/wizards.version"), "rt" )
wizards_current_version = wizards_pack_version_file.read()
wizards_current_version = wizards_current_version.strip()
wizards_pack_version_file.close()
# Display the About Rwizards dialog:
about_dialog = Gtk.AboutDialog()
about_dialog.set_name(_("RWizards official package"))
about_dialog.set_version(wizards_current_version)
about_dialog.set_copyright(_("(c) 2009,2010, Dan Dediu"))
about_dialog.set_comments(_("A set of predefined Rwizards"))
about_dialog.set_license(_("""
Rwizards official package: a set of wizards for rgedit
Copyright (C) 2009 Dan Dediu
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""))
about_dialog.set_website("http://sourceforge.net/projects/rgedit/")
about_dialog.set_authors("")
about_dialog.set_documenters("")
about_dialog.set_artists("")
about_dialog.set_translator_credits("")
about_dialog.set_logo(GdkPixbuf.Pixbuf.new_from_file(icon))
about_dialog.show()
about_dialog.run()
about_dialog.destroy()
def createRGeditTerminal(self):
self.R_widget = RGeditTerminal(self._plugin)
self.R_widget._window = self._window
#print self._plugin.prefs['RConsole_start_attached']
self.bottom_panel_dummy_hbox = None
if self._plugin.prefs['RConsole_start_attached'] == False:
R_icon = Gtk.Image()
R_icon.set_from_file(self.datadir+"/Rgedit-icon24.png")
self.bottom_panel_dummy_hbox = Gtk.HBox()
self.bottom_panel_dummy_hbox.show()
self.bottom_panel_dummy_hbox.pack_start(self.R_widget,True,True,True)
self.R_widget.show()
self._window.get_bottom_panel().add_item(self.bottom_panel_dummy_hbox,"R Console","R Console",R_icon)
self._window.get_bottom_panel().set_property("visible",True)
elif self.Detached_R_Dialog != None:
self.R_widget.show()
try:
self.Detached_R_Dialog.get_content_area().pack_start(self.R_widget,True,True)
except:
self.Detached_R_Dialog.get_child().pack_start(self.R_widget,True,True)
self.Detached_R_Dialog.show()
else:
# Create the dialog to embed the detached R console:
#self.Detached_R_Dialog = Gtk.Dialog( "Detached R console", self._window, Gtk.DialogFlags.DESTROY_WITH_PARENT, None );
self.Detached_R_Dialog = Gtk.Window( Gtk.WindowType.TOPLEVEL )
self.Detached_R_Dialog.set_title( "Detached R console" )
self.Detached_R_Dialog.set_destroy_with_parent( True )
self.Detached_R_Dialog.connect('delete_event', self.on_R_Dialog_close)
self.Detached_R_Dialog.connect('configure_event', self.on_R_Dialog_configure)
self.Detached_R_Dialog.set_icon(GdkPixbuf.Pixbuf.new_from_file(self.datadir+"/Rgedit-icon24.png"))
if self._plugin.prefs['RConsole_detached_x'] != -1 and self._plugin.prefs['RConsole_detached_y'] != -1:
self.Detached_R_Dialog.move(self._plugin.prefs['RConsole_detached_x'],self._plugin.prefs['RConsole_detached_y'])
if self._plugin.prefs['RConsole_detached_width'] == -1:
self._plugin.prefs['RConsole_detached_width'] = 100
if self._plugin.prefs['RConsole_detached_height'] == -1:
self._plugin.prefs['RConsole_detached_height'] = 100
self.Detached_R_Dialog.resize(self._plugin.prefs['RConsole_detached_width'],self._plugin.prefs['RConsole_detached_height'])
if self.R_widget != None:
dummyHBox = Gtk.HBox()
dummyHBox.show()
dummyHBox.pack_start(self.R_widget,True,True)
self.R_widget.show()
#try:
# self.Detached_R_Dialog.get_content_area().pack_start(dummyHBox,True,True)
#except:
# self.Detached_R_Dialog.get_child().pack_start(dummyHBox,True,True)
self.Detached_R_Dialog.add(dummyHBox)
self.Detached_R_Dialog.show()
self.R_widget.send_command("R --no-save --no-restore \n") # open R
self.R_widget.run_gedit_helper_script(self.R_widget._vte)
if self._plugin.prefs['HTML_help'] == True:
self.R_widget.send_command("options(htmlhelp = TRUE,help_type='html')\n") # and init the HTML help system both for pre and post R 2.10.0...
else:
self.R_widget.send_command("options(htmlhelp = FALSE,help_type='text')\n") # and init the TEXT help system both for pre and post R 2.10.0...
if self._plugin.prefs['prompt_color1'] != None or self._plugin.prefs['tab_name_in_prompt'] == True:
self.R_widget.send_command(self._plugin.prompt_string(1,self.R_widget.get_tab_name(1))) # and set the prompt accordingly...
if self._plugin.prefs['autostart_R_script']:
self.R_widget.send_command("source(\""+self._plugin.prefs['autostart_R_script_path']+"\",echo=TRUE,print.eval=TRUE,max.deparse.length=500000,local=TRUE);\n") # run the autostart script...
if self._plugin.prefs['use_current_document_directory']:
self.R_widget.change_vte_R_working_dir_to_the_document(self.R_widget._vte)
self.R_widget.show_messages_and_warnings(self.R_widget._vte)
# Sensitivity:
manager = self._window.get_ui_manager()
manager.get_action("/ToolBar/RCtrlLine").set_sensitive(True)
manager.get_action("/ToolBar/RCtrlSel").set_sensitive(True)
manager.get_action("/ToolBar/RCtrlAll").set_sensitive(True)
manager.get_action("/ToolBar/RCtrlCursor").set_sensitive(True)
manager.get_action("/ToolBar/RCtrlNewTab").set_sensitive(True)
#manager.get_action("/ToolBar/RCtrlConfig").set_sensitive(True)
manager.get_action("/MenuBar/R/RCtrlAttach").set_sensitive(True)
manager.get_action("/MenuBar/R/RCtrlBlock1Run").set_sensitive(True)
manager.get_action("/MenuBar/R/RCtrlBlock2Run").set_sensitive(True)
#manager.get_action("/MenuBar/R/RCtrlLoadWorkspace").set_sensitive(True)
#manager.get_action("/MenuBar/R/RCtrlSaveWorkspace").set_sensitive(True)
#manager.get_action("/MenuBar/R/RCtrlHelpSel").set_sensitive(True)
#manager.get_action("/MenuBar/R/RCtrlShowSel").set_sensitive(True)
#manager.get_action("/MenuBar/R/RCtrlEditSel").set_sensitive(True)
manager.get_action("/MenuBar/R/RCtrlClose").set_sensitive(True)
def create_R_detached_dialog(self):
# Create the dialog to embed the detached R console:
#self.Detached_R_Dialog = Gtk.Dialog( "Detached R console", self._window, Gtk.DialogFlags.DESTROY_WITH_PARENT, None );
self.Detached_R_Dialog = Gtk.Window() # Gtk.WindowType.TOPLEVEL
self.Detached_R_Dialog.set_title( _("Detached R console") )
self.Detached_R_Dialog.set_destroy_with_parent( True )
self.Detached_R_Dialog.connect('delete_event', self.on_R_Dialog_close)
self.Detached_R_Dialog.connect('configure_event', self.on_R_Dialog_configure)
self.Detached_R_Dialog.set_icon(GdkPixbuf.Pixbuf.new_from_file(self.datadir+"/Rgedit-icon24.png"))
if self._plugin.prefs['RConsole_detached_x'] != -1 and self._plugin.prefs['RConsole_detached_y'] != -1:
self.Detached_R_Dialog.move(self._plugin.prefs['RConsole_detached_x'],self._plugin.prefs['RConsole_detached_y'])
if self._plugin.prefs['RConsole_detached_width'] == -1:
self._plugin.prefs['RConsole_detached_width'] = 100
if self._plugin.prefs['RConsole_detached_height'] == -1:
self._plugin.prefs['RConsole_detached_height'] = 100
self.Detached_R_Dialog.resize(self._plugin.prefs['RConsole_detached_width'],self._plugin.prefs['RConsole_detached_height'])
if self.R_widget != None:
dummyHBox = Gtk.HBox()
dummyHBox.show()
self.R_widget.reparent(dummyHBox)
#try:
# self.Detached_R_Dialog.get_content_area().pack_start(dummyHBox,True,True)
#except:
# self.Detached_R_Dialog.get_child().pack_start(dummyHBox,True,True)
self.Detached_R_Dialog.add(dummyHBox)
self.Detached_R_Dialog.show()
if self.bottom_panel_dummy_hbox != None:
self._window.get_bottom_panel().remove_item(self.bottom_panel_dummy_hbox)
def destroy_R_detached_dialog(self):
self.on_R_Dialog_close(None,None)
# Destroy the dialog to embed the detached R console:
self.Detached_R_Dialog.destroy()
self.Detached_R_Dialog = None
def on_R_Dialog_close(self,data1,data2):
if data1 != None or data2 != None:
self.on_R_attach(None)
R_icon = Gtk.Image()
R_icon.set_from_file(self.datadir+"/Rgedit-icon24.png")
self.bottom_panel_dummy_hbox = Gtk.HBox()
self.bottom_panel_dummy_hbox.show()
self.R_widget.reparent(self.bottom_panel_dummy_hbox)
self._window.get_bottom_panel().add_item(self.bottom_panel_dummy_hbox,"R Console",_("R Console"),R_icon)
self._window.get_bottom_panel().set_property("visible",True)
self._window.get_bottom_panel().activate_item(self.bottom_panel_dummy_hbox)
def on_R_Dialog_configure(self,widget,event):
#self._plugin.prefs['RConsole_detached_x'] = event.x
#self._plugin.prefs['RConsole_detached_y'] = event.y
#self._plugin.prefs['RConsole_detached_width'] = event.width
#self._plugin.prefs['RConsole_detached_height'] = event.height
self._plugin.prefs['RConsole_detached_x'], self._plugin.prefs['RConsole_detached_y'] = self.Detached_R_Dialog.get_position()
self._plugin.prefs['RConsole_detached_width'], self._plugin.prefs['RConsole_detached_height'] = self.Detached_R_Dialog.get_size()
# Ugly hack due to the fact that for some reason I am not notified when gedit is closed...
self._plugin.save_prefs()
#print "R_Dialog_configure"
def _remove_menu(self):
# Get the GtkUIManager
manager = self._window.get_ui_manager()
# Remove the ui
manager.remove_ui(self._ui_id)
# Remove the action group
manager.remove_action_group(self._action_group)
# Make sure the manager updates
manager.ensure_update()
def update_ui(self):
self._action_group.set_sensitive(self._window.get_active_document() != None)
class RCtrlPlugin(GObject.Object, Gedit.WindowActivatable):
__gtype_name__ = "RCtrlPlugin"
window = GObject.property(type=Gedit.Window)
# The plugin preferences:
prefs = {
'autostart_R_console' : True, # should the R console in the panel start automatically?
'max_lines_as_text' : 20, # the number of lines to send selection as text
'echo_commands' : True, # should commands sent to R through source() be echoed in the R console?
'HTML_help' : True, # use HTML help?
'advance_to_next_line' : True, # advance to next line after sending current line to R?
'allow_bold' : True,
'audible_bell' : False,
'background1' : "white",
'foreground1' : "black",
'prompt_color1' : None,
'background2' : "white",
'foreground2' : "black",
'prompt_color2' : None,
'background3' : "white",
'foreground3' : "black",
'prompt_color3' : None,
'tab_name_in_prompt' : True,
'backspace_binding' : 'ascii-del',
'cursor_blink' : 'system', # system, on, off
'cursor_shape' : 'block', # block, ibeam, underline
'emulation' : 'xterm',
'font_name' : 'Monospace 8',
'scroll_on_keystroke' : True,
'scroll_on_output' : True,
'scrollback_lines' : 5000,
'visible_bell' : False,
'word_chars' : '-A-Za-z0-9,./?%&#:_',
'show_run_line' : True,
'show_run_sel' : True,
'show_run_all' : True,
'show_run_cursor' : True,
'show_run_block1' : True,
'show_def_block1' : True,
'show_run_block2' : True,
'show_def_block2' : True,
'show_new_tab' : True,
'shortcut_RCtrlLine' : '<Ctrl><Shift>R', # user-definible keyboard shortcuts
'shortcut_RCtrlSel' : '<Ctrl><Shift>E',
'shortcut_RCtrlAll' : None,
'shortcut_RCtrlCursor' : None,
'shortcut_RCtrlBlock1Run' : '<Ctrl><Shift>F1',
'shortcut_RCtrlBlock1Def' : None,
'shortcut_RCtrlBlock2Run' : '<Ctrl><Shift>F2',
'shortcut_RCtrlBlock2Def' : None,
'shortcut_RCtrlNewTab' : None,
'shortcut_RCtrlConfig' : None,
'shortcut_RCtrlLoadWorkspace' : None,
'shortcut_RCtrlSaveWorkspace' : None,
#'shortcut_RCtrlHelpSel' : '<Ctrl><Shift>H',
#'shortcut_RCtrlShowSel' : None,
#'shortcut_RCtrlEditSel' : None,
'shortcut_RCtrlAttach' : None,
'shortcut_RCtrlClose' : None,
'RConsole_start_attached' : False,
'RConsole_detached_x' : -1,
'RConsole_detached_y' : -1,
'RConsole_detached_width' : -1,
'RConsole_detached_height' : -1,
'skip_empty_and_comment_lines' : True,
'autostart_R_script' : False,
'autostart_R_script_path' : None,
'R_structure_enabled' : True,
'R_structure_landmarks' : True,
'R_structure_functions' : True,
'R_structure_dataframes' : True,
'use_current_document_directory' : True,
'R_console_tab_pos' : int(Gtk.PositionType.RIGHT),
'R_console_always_show_tabs' : False,
'R_console_Ctrl_C_4_copy' : True,
'R_console_Ctrl_Q_break' : True,
'R_console_Escape_break' : True,
'show_messages_and_warnings' : True,
'show_rgedit_UI_only_for_R_mime_types' : True,
'use_rgedit_code_folding' : True,
'code_folding_block_preference' : 'highest_block'
}
def __init__(self):
GObject.Object.__init__(self)
self.id_name = 'RCtrlPlugin'
self._instances = {}
## Localization:
#translation_stuff = gettext.translation('RCtrl', self.get_data_dir() + "/RCtrl/Translations/")
#_ = translation_stuff.lgettext
# Load the saved preferences:
try:
pref_file = open(os.path.expanduser("~/.rgedit-preferences"),"r")
saved_prefs = pickle.load(pref_file)
for i in list(self.prefs.keys()):
if i in saved_prefs:
self.prefs[i] = saved_prefs[i]
close(pref_file)
except:
pass
# Checks:
if self.prefs['autostart_R_script_path'] == None:
self.prefs['autostart_R_script'] = False
# There are some special shortcuts of potential interest, esp. modifiers of ENTER:
self.check_special_shortcuts()
## Context menu stuff:
#self.window = None
# rgedit-specific UI elements:
self.show_gedit_UI = True
# code folding engine:
self.code_folding_engine = RCodeFolding(self.get_data_dir(),self,self.prefs['use_rgedit_code_folding'])
def check_special_shortcuts(self):
# There are some special shortcuts of potential interest, esp. modifiers of ENTER,
# for runing the current line, block, all files, etc...
self.special_shortcut_RCtrlLine = [None,None]
self.special_shortcut_RCtrlSel = [None,None]
self.special_shortcut_RCtrlAll = [None,None]
self.special_shortcut_RCtrlCursor = [None,None]
self.special_shortcut_RCtrlBlock1Run = [None,None]
self.special_shortcut_RCtrlBlock2Run = [None,None]
# Set the possible modifiers (Control Shift and Alt):
self.possible_modifiers = (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK | Gdk.ModifierType.MOD1_MASK)
key, modifier = Gtk.accelerator_parse(str(self.prefs['shortcut_RCtrlLine']))
if key != 0 and Gdk.keyval_name(key).lower() == "return":
self.special_shortcut_RCtrlLine = ["return",modifier]
key, modifier = Gtk.accelerator_parse(str(self.prefs['shortcut_RCtrlSel']))
if key != 0 and Gdk.keyval_name(key).lower() == "return":
self.special_shortcut_RCtrlSel = ["return",modifier]
key, modifier = Gtk.accelerator_parse(str(self.prefs['shortcut_RCtrlAll']))
if key != 0 and Gdk.keyval_name(key).lower() == "return":
self.special_shortcut_RCtrlAll = ["return",modifier]
key, modifier = Gtk.accelerator_parse(str(self.prefs['shortcut_RCtrlCursor']))
if key != 0 and Gdk.keyval_name(key).lower() == "return":
self.special_shortcut_RCtrlCursor = ["return",modifier]
key, modifier = Gtk.accelerator_parse(str(self.prefs['shortcut_RCtrlBlock1Run']))
if key != 0 and Gdk.keyval_name(key).lower() == "return":
self.special_shortcut_RCtrlBlock1Run = ["return",modifier]
key, modifier = Gtk.accelerator_parse(self.prefs['shortcut_RCtrlBlock2Run'])
if Gdk.keyval_name(key).lower() == "return":
self.special_shortcut_RCtrlBlock2Run = ["return",modifier]
def get_data_dir(self):
try:
return gedit.Plugin.get_data_dir(self)
except:
return self.get_data_directory()
def get_data_directory(self):
if platform.platform() == 'Windows':
return os.path.expanduser('~/gedit/plugins/RCtrl')
else:
return os.path.expanduser('/usr/share/gedit/plugins/RCtrl')
def do_activate(self):
self._instances[self.window] = RCtrlWindowHelper(self, self.window)
handler_ids = []
for signal in ('tab-added', 'tab-removed', 'active-tab-changed'):
method = getattr(self, 'on_window_' + signal.replace('-', '_'))
handler_ids.append(self.window.connect(signal, method))
self.window.set_data(self.id_name, handler_ids)
for view in self.window.get_views():
self.connect_view(view,self._instances[self.window])
for doc in self.window.get_documents():
self.connect_document(doc,self.window)
def do_deactivate(self):
pass
def do_update_state(self):
pass
def connect_view(self, view, rctrlwindowhelper):
handler_id = view.connect('populate-popup', self.on_view_populate_popup, rctrlwindowhelper)
view.set_data(self.id_name, [handler_id])
# Key press dispatcher for processing the shortcuts:
handler_id = view.connect('key_press_event', self.on_view_key_press_event, rctrlwindowhelper)
# Tooltips within the view:
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = True
view.connect("query-tooltip", self.query_tooltip_text_view) #, tag)
def on_window_tab_added(self, window, tab):
self.connect_view(tab.get_view(),self._instances[window])
doc = tab.get_document()
handler_id = doc.get_data(self.id_name)
if handler_id is None:
self.connect_document(doc,window)
def on_window_active_tab_changed(self, window, tab):
#self._instances[window]._rstructurepanel.on_force_refresh(None)
self.show_hide_toolbar_and_friends(tab.get_document())
def on_window_tab_removed(self, window, tab):
pass
def is_document_R_source_file(self,doc):
# Decide if this document is indeed an R source file:
if not self.prefs['show_rgedit_UI_only_for_R_mime_types']:
return True
else:
doc_language = doc.get_language()
return (doc_language != None and doc_language.get_name().upper() == "R")
def show_hide_toolbar_and_friends(self,doc):
# Show/hide the rgedit-specific UI elements given the current document's mimetype:
if doc == None:
return
self.show_gedit_UI = False
# Decide if this document is indeed an R source file:
if self.is_document_R_source_file(doc):
self.show_gedit_UI = True
# Show or hide the rgedit UI stuff as required:
# Get the GtkUIManager
manager = self.window.get_ui_manager()
if manager == None:
return
RCtrlLine_toolitem = manager.get_widget("/ToolBar/RCtrlLine")
RCtrlSel_toolitem = manager.get_widget("/ToolBar/RCtrlSel")
RCtrlAll_toolitem = manager.get_widget("/ToolBar/RCtrlAll")
RCtrlCursor_toolitem = manager.get_widget("/ToolBar/RCtrlCursor")
RCtrlBlock1Run_toolitem = manager.get_widget("/ToolBar/RCtrlBlock1Run")
RCtrlBlock1Def_toolitem = manager.get_widget("/ToolBar/RCtrlBlock1Def")
RCtrlBlock2Run_toolitem = manager.get_widget("/ToolBar/RCtrlBlock2Run")
RCtrlBlock2Def_toolitem = manager.get_widget("/ToolBar/RCtrlBlock2Def")
RCtrlNewTab_toolitem = manager.get_widget("/ToolBar/RCtrlNewTab")
if self.show_gedit_UI == False:
# Go hide them all:
RCtrlLine_toolitem.hide()
RCtrlSel_toolitem.hide()
RCtrlAll_toolitem.hide()
RCtrlCursor_toolitem.hide()
RCtrlBlock1Run_toolitem.hide()
RCtrlBlock1Def_toolitem.hide()
RCtrlBlock2Run_toolitem.hide()
RCtrlBlock2Def_toolitem.hide()
RCtrlNewTab_toolitem.hide()
else:
# Restore the UI elements as defined by the user:
if self.prefs['show_run_line']:
RCtrlLine_toolitem.show()
if self.prefs['show_run_sel']:
RCtrlSel_toolitem.show()
if self.prefs['show_run_all']:
RCtrlAll_toolitem.show()
if self.prefs['show_run_cursor']:
RCtrlCursor_toolitem.show()
if self.prefs['show_run_block1']:
RCtrlBlock1Run_toolitem.show()
if self.prefs['show_def_block1']:
RCtrlBlock1Def_toolitem.show()
if self.prefs['show_run_block2']:
RCtrlBlock2Run_toolitem.show()
if self.prefs['show_def_block2']:
RCtrlBlock2Def_toolitem.show()
if self.prefs['show_new_tab']:
RCtrlNewTab_toolitem.show()
def save_prefs(self):
try:
pref_file = open(os.path.expanduser("~/.rgedit-preferences"),"w")
pickle.dump(self.prefs,pref_file)
pref_file.close()
except:
print "Error saving preferences..."
pass
def prompt_string(self,tab_number,tab_name):
# Given the prompt settings, produce the appropriate R commands
prompt_string = ""
continue_string = ""
xterm_color = self.xterm_16_color_from_string(self.prefs['prompt_color'+str(tab_number)])
if xterm_color != "":
# Add the color bits:
prompt_string = prompt_string + "\\x1b" + xterm_color
continue_string = continue_string + "\\x1b" + xterm_color
if self.prefs['tab_name_in_prompt'] == True:
# Add an extra character at the begining of the prompt to make it more obvious:
prompt_string = prompt_string + tab_name
continue_string = continue_string + tab_name
# Add the middle of the prompt:
prompt_string = prompt_string + "> "
continue_string = continue_string + "+ "
# and the final part (if any):
if xterm_color != "":
prompt_string = prompt_string + "\\x1b[33;0m"
continue_string = continue_string + "\\x1b[33;0m"
# Concate all these to get the full R code:
return "options( prompt=\"" + prompt_string + "\", continue=\"" + continue_string + "\" )\n"
def xterm_16_color_from_string(self,color_name):
# Get the appropriate xterm escape sequence for the named color (if any):
xterm_colors = {
'black' : '[1;30m',
'red' : '[1;31m',
'green' : '[1;32m',
'yellow' : '[1;33m',
'blue' : '[1;34m',
'magenta' : '[1;35m',
'cyan' : '[1;36m',
'white' : '[1;37m'
}
if color_name in xterm_colors:
return xterm_colors[color_name]
else:
return ""
def xterm_color_to_index(self,color_name):
# Get the appropriate xterm escape sequence for the named color (if any):
xterm_colors = {
'black' : 0,
'red' : 1,
'green' : 2,
'yellow' : 3,
'blue' : 4,
'magenta' : 5,
'cyan' : 6,
'white' : 7
}
if color_name == None:
return 0
elif color_name in xterm_colors:
return xterm_colors[color_name]+1
else:
return -1
def xterm_color_from_index(self,color_index):
# Get the appropriate xterm escape sequence for the named color (if any):
xterm_colors = {
0 :'black',
1 :'red',
2 :'green',
3 :'yellow',
4 :'blue',
5 :'magenta',
6 :'cyan',
7 :'white'
}
if color_index == 0:
return None
elif color_index in xterm_colors:
return xterm_colors[color_index-1]
else:
return None
def on_view_populate_popup(self, view, menu, rctrlwindowhelper):
doc = view.get_buffer()
if doc == None:
return False
# Get the iterator where the right click happened in the view:
x, y = view.get_pointer()
x, y = view.window_to_buffer_coords(Gtk.TextWindowType.WIDGET, x, y)
cur_pos_iterator = view.get_iter_at_location(x, y)
# The Wizards context menu:
wizardmenu = Gtk.ImageMenuItem()
wizardmenu.set_label(_("Wizards"))
#wizardmenu.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.MENU))
wizardmenu.connect('activate', self.on_context_menu_wizard);
wizardmenu.show();
rctrlwindowhelper.fill_in_wizards_menu( wizardmenu )
# The Landmark Comment menu entry:
landmarkmenu = Gtk.ImageMenuItem()
landmarkmenu.set_label(_("Insert Landmark Comment"))
menu_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.get_data_dir()+"/landmark_comment.png",16,16)
menu_icon.set_from_pixbuf(pixbuf)
menu_icon.show()
landmarkmenu.set_image(menu_icon)
landmarkmenu.connect('activate', self.on_context_menu_landmark, doc);
landmarkmenu.show();
separator = Gtk.SeparatorMenuItem()
separator.show();
# The code folding menu entries:
if self.prefs['use_rgedit_code_folding']:
if self.code_folding_engine.is_folded(doc,cur_pos_iterator):
menu_name = _("Unfold code on current line")
menu_handler = self.on_context_menu_unfold_code
else:
menu_name = _("Fold block containg current line")
menu_handler = self.on_context_menu_fold_containing_block
curlinefoldingmenu = Gtk.ImageMenuItem()
curlinefoldingmenu.set_label(menu_name)
menu_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.get_data_dir()+"/folded_code.png",16,16)
menu_icon.set_from_pixbuf(pixbuf)
menu_icon.show()
curlinefoldingmenu.set_image(menu_icon)
curlinefoldingmenu.connect('activate', menu_handler, doc, view, cur_pos_iterator);
curlinefoldingmenu.show();
inspectfoldedcodemenu = None
if self.code_folding_engine.is_folded(doc,cur_pos_iterator):
menu_name = _("Inspect folded code...")
menu_handler = self.on_context_menu_inspect_folded_code
inspectfoldedcodemenu = Gtk.ImageMenuItem(menu_name)
menu_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.get_data_dir()+"/folded_code.png",16,16)
menu_icon.set_from_pixbuf(pixbuf)
menu_icon.show()
inspectfoldedcodemenu.set_image(menu_icon)
inspectfoldedcodemenu.connect('activate', menu_handler, doc, view, cur_pos_iterator);
inspectfoldedcodemenu.show();
selectionfoldingmenu = None
if self.code_folding_engine.is_selection(doc):
selectionfoldingmenu = Gtk.ImageMenuItem(_("Fold current selection"))
menu_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.get_data_dir()+"/folded_code.png",16,16)
menu_icon.set_from_pixbuf(pixbuf)
menu_icon.show()
selectionfoldingmenu.set_image(menu_icon)
selectionfoldingmenu.connect('activate', self.on_context_menu_fold_selection, doc, view);
selectionfoldingmenu.show();
unfoldallgmenu = Gtk.ImageMenuItem()
unfoldallgmenu.set_label(_("Unfold all folded code"))
menu_icon = Gtk.Image()
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.get_data_dir()+"/folded_code.png",16,16)
menu_icon.set_from_pixbuf(pixbuf)
menu_icon.show()
unfoldallgmenu.set_image(menu_icon)
unfoldallgmenu.connect('activate', self.on_context_menu_unfold_all, doc, view);
unfoldallgmenu.show();
separator2 = Gtk.SeparatorMenuItem()
separator2.show();
menu.prepend(separator2)
menu.prepend(unfoldallgmenu)
if selectionfoldingmenu:
menu.prepend(selectionfoldingmenu)
if inspectfoldedcodemenu:
menu.prepend(inspectfoldedcodemenu)
menu.prepend(curlinefoldingmenu)
menu.prepend(separator)
menu.prepend(wizardmenu)
menu.prepend(landmarkmenu)
return True
def on_view_key_press_event(self, widget, event, rctrlwindowhelper):
# Process the special shortcuts (if any) before gedit has any chance:
event_key = Gdk.keyval_name(event.keyval).lower()
if event_key != "return":
return False
event_modifiers = (event.get_state() & self.possible_modifiers)
if (self.special_shortcut_RCtrlLine[0] == event_key) and (event_modifiers == self.special_shortcut_RCtrlLine[1]):
rctrlwindowhelper.on_send_line_to_R(None,None)
return True
if (self.special_shortcut_RCtrlSel[0] == event_key) and (event_modifiers == self.special_shortcut_RCtrlSel[1]):
rctrlwindowhelper.on_send_selection_to_R(None)
return True
if (self.special_shortcut_RCtrlAll[0] == event_key) and (event_modifiers == self.special_shortcut_RCtrlAll[1]):
rctrlwindowhelper.on_send_file_to_R(None)
return True
if (self.special_shortcut_RCtrlCursor[0] == event_key) and (event_modifiers == self.special_shortcut_RCtrlCursor[1]):
rctrlwindowhelper.on_send_cursor_to_R(None)
return True
if (self.special_shortcut_RCtrlBlock1Run[0] == event_key) and (event_modifiers == self.special_shortcut_RCtrlBlock1Run[1]):
rctrlwindowhelper.on_send_block1_to_R(None)
return True
if (self.special_shortcut_RCtrlBlock2Run[0] == event_key) and (event_modifiers == self.special_shortcut_RCtrlBlock2Run[1]):
rctrlwindowhelper.on_send_block2_to_R(None)
return True
return False
def query_tooltip_text_view(self, view, x, y, keyboard_tip, tooltip):
# DEBUG
return False
if not view.props.has_tooltip:
return False
if keyboard_tip:
offset = view.props.buffer.cursor_position
position_iter = view.props.buffer.get_iter_at_offset(offset)
else:
coords = view.window_to_buffer_coords(Gtk.TextWindowType.TEXT, x, y)
position_iter = view.get_iter_at_location(coords[0], coords[1])
# Ask the code folding engine to provide some tooltip for this position (if any):
do_tooltip,tooltip_text = self.code_folding_engine.get_tooltip(view, view.props.buffer, position_iter)
if do_tooltip == True:
tooltip.set_text(tooltip_text)
return True
return False
def connect_document(self, doc, window):
handler_id = doc.connect("saved", self.on_document_saved, window)
handler_id = doc.connect("loaded", self.on_document_loaded, window)
doc.set_data(self.id_name, [handler_id])
def on_window_tab_added(self, window, tab):
self.connect_view(tab.get_view(),self._instances[window])
doc = tab.get_document()
handler_id = doc.get_data(self.id_name)
if handler_id is None:
self.connect_document(doc,window)
def on_window_active_tab_changed(self, window, tab):
self._instances[window]._rstructurepanel.on_force_refresh(None)
self.show_hide_toolbar_and_friends(tab.get_document())
def on_window_tab_removed(self, window, tab):
pass
def on_document_saved(self, doc, ignore1, window):
self._instances[window]._rstructurepanel.on_force_refresh(None)
self.show_hide_toolbar_and_friends(doc)
def on_document_loaded(self, doc, ignore1, window):
self._instances[window]._rstructurepanel.on_force_refresh(None)
self.show_hide_toolbar_and_friends(doc)
def on_context_menu_unfold_all(self, menu_item, doc, view):
self.code_folding_engine.unfold_all(doc,view)
return True
def on_context_menu_unfold_code(self, menu_item, doc, view, cur_pos_iterator):
self.code_folding_engine.unfold(doc,view,cur_pos_iterator)
return True
def on_context_menu_inspect_folded_code(self, menu_item, doc, view, cur_pos_iterator):
self.code_folding_engine.inspect_folded_code(doc,view,cur_pos_iterator)
return True
def on_context_menu_fold_containing_block(self, menu_item, doc, view, cur_pos_iterator):
self.code_folding_engine.fold_containing_block(doc,view,cur_pos_iterator)
return True
def on_context_menu_fold_selection(self, menu_item, doc, view):
self.code_folding_engine.fold_selection(doc,view)
return True
def on_context_menu_wizard(self, menu_item):
#print "Wirzad from context menu!"
return True
def on_context_menu_landmark(self, menu_item, doc):
# Insert the landmark special comment at the beginning of the next line:
if doc == None:
# Nothing to do!
return True
# Get the cursor's location:
cursor_iter = doc.get_iter_at_mark(doc.get_insert())
# and go to the end of the line:
if not cursor_iter.ends_line():
cursor_iter.forward_to_line_end()
# then insert a newline and the comment text:
doc.insert(cursor_iter,str("\n")+landmark_comment_header+landmark_comment_placeholder)
return True
def create_configure_dialog(self):
self.ui = create_UI_from_file_GtkBuilder_or_Glade(self.get_data_dir()+"/ConfigDialog.glade",self.get_data_dir()+"/ConfigDialog.ui")
# Init the controls accordingly with the current options:
check_box_autostart_R = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AutostartR")
check_box_autostart_R.set_active(self.prefs['autostart_R_console'])
check_box_use_doc_dir = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"UseDocDirectory")
check_box_use_doc_dir.set_active(self.prefs['use_current_document_directory'])
check_box_show_message = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ShowMessageCheck")
check_box_show_message.set_active(self.prefs['show_messages_and_warnings'])
check_box_attached_R = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"StartRAttached")
check_box_attached_R.set_active(self.prefs['RConsole_start_attached'])
check_box_autostart_script = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AutostartScriptCheck")
check_box_autostart_script.set_active(self.prefs['autostart_R_script'])
if self.prefs['autostart_R_script_path'] != None:
file_chooser_autostart_script = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AutorunScriptPath")
file_chooser_autostart_script.set_filename(self.prefs['autostart_R_script_path'])
spin_max_lines_as_text = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"MaxLinesToSendSpin")
spin_max_lines_as_text.set_range(0,50)
spin_max_lines_as_text.set_increments(1,5)
spin_max_lines_as_text.set_value(self.prefs['max_lines_as_text'])
check_box_HTML_help = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"HTMLHelpCheck")
check_box_HTML_help.set_active(self.prefs['HTML_help'])
check_box_echo_commands = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"EchoPipedCommandsCheck")
check_box_echo_commands.set_active(self.prefs['echo_commands'])
check_box_advance_line = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AdvanceLineCheck")
check_box_advance_line.set_active(self.prefs['advance_to_next_line'])
check_box_skip_empty_and_comment = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"SkipEmptyAndCommentCheck")
check_box_skip_empty_and_comment.set_active(self.prefs['skip_empty_and_comment_lines'])
check_box_audible_bell = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AudibleBell")
check_box_audible_bell.set_active(self.prefs['audible_bell'])
check_box_visible_bell = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"VisibleBell")
check_box_visible_bell.set_active(self.prefs['visible_bell'])
check_box_scroll_on_keystroke = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ScrollOnKeystroke")
check_box_scroll_on_keystroke.set_active(self.prefs['scroll_on_keystroke'])
check_box_scroll_on_output = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ScrollOnOutput")
check_box_scroll_on_output.set_active(self.prefs['scroll_on_output'])
edit_scrollback_lines = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ScrollbackLines")
edit_scrollback_lines.set_text(str(self.prefs['scrollback_lines']))
if self.prefs['cursor_blink'] == "system":
radio_button_cursor_blink = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BlinkSystem")
radio_button_cursor_blink.set_active(True)
elif self.prefs['cursor_blink'] == "on":
radio_button_cursor_blink = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BlinkOn")
radio_button_cursor_blink.set_active(True)
elif self.prefs['cursor_blink'] == "off":
radio_button_cursor_blink = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BlinkOff")
radio_button_cursor_blink.set_active(True)
if self.prefs['cursor_shape'] == "block":
radio_button_cursor_shape = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ShapeBlock")
radio_button_cursor_shape.set_active(True)
elif self.prefs['cursor_shape'] == "ibeam":
radio_button_cursor_shape = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ShapeIBeam")
radio_button_cursor_shape.set_active(True)
elif self.prefs['cursor_shape'] == "underline":
radio_button_cursor_shape = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ShapeUnderline")
radio_button_cursor_shape.set_active(True)
color_button_foreground1 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ForegroundColor1")
coltmp = Gdk.color_parse(self.prefs['foreground1'])
if isinstance(coltmp,tuple):
coltmp = coltmp[1]
color_button_foreground1.set_color(coltmp)
color_button_background1 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BackgroundColor1")
coltmp = Gdk.color_parse(self.prefs['background1'])
if isinstance(coltmp,tuple):
coltmp = coltmp[1]
color_button_background1.set_color(coltmp)
combo_box_prompt_color1 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"PromptColor1")
liststore1 = Gtk.ListStore(GObject.TYPE_STRING)
dynentries = [_("None"),_("Black"),_("Red"),_("Green"),_("Yellow"),_("Blue"),_("Magenta"),_("Cyan"),_("White")]
for entry in dynentries:
liststore1.append([entry])
combo_box_prompt_color1.set_model(liststore1)
cell1 = Gtk.CellRendererText()
combo_box_prompt_color1.pack_start(cell1, True)
combo_box_prompt_color1.add_attribute(cell1, 'text', 0)
combo_box_prompt_color1.set_active(self.xterm_color_to_index(self.prefs['prompt_color1']))
color_button_foreground2 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ForegroundColor2")
coltmp = Gdk.color_parse(self.prefs['foreground2'])
if isinstance(coltmp,tuple):
coltmp = coltmp[1]
color_button_foreground2.set_color(coltmp)
color_button_background2 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BackgroundColor2")
coltmp = Gdk.color_parse(self.prefs['background2'])
if isinstance(coltmp,tuple):
coltmp = coltmp[1]
color_button_background2.set_color(coltmp)
combo_box_prompt_color2 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"PromptColor2")
liststore2 = Gtk.ListStore(GObject.TYPE_STRING)
for entry in dynentries:
liststore2.append([entry])
combo_box_prompt_color2.set_model(liststore2)
cell2 = Gtk.CellRendererText()
combo_box_prompt_color2.pack_start(cell2, True)
combo_box_prompt_color2.add_attribute(cell2, 'text', 0)
combo_box_prompt_color2.set_active(self.xterm_color_to_index(self.prefs['prompt_color2']))
color_button_foreground3 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ForegroundColor3")
coltmp = Gdk.color_parse(self.prefs['foreground3'])
if isinstance(coltmp,tuple):
coltmp = coltmp[1]
color_button_foreground3.set_color(coltmp)
color_button_background3 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BackgroundColor3")
coltmp = Gdk.color_parse(self.prefs['background3'])
if isinstance(coltmp,tuple):
coltmp = coltmp[1]
color_button_background3.set_color(coltmp)
combo_box_prompt_color3 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"PromptColor3")
liststore3 = Gtk.ListStore(GObject.TYPE_STRING)
for entry in dynentries:
liststore3.append([entry])
combo_box_prompt_color3.set_model(liststore3)
cell3 = Gtk.CellRendererText()
combo_box_prompt_color3.pack_start(cell3, True)
combo_box_prompt_color3.add_attribute(cell3, 'text', 0)
combo_box_prompt_color3.set_active(self.xterm_color_to_index(self.prefs['prompt_color3']))
check_box_tab_name_in_prompt = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"TabNameInPrompt")
check_box_tab_name_in_prompt.set_active(self.prefs['tab_name_in_prompt'])
font_button = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"CurrentFont")
font_button.set_font_name( self.prefs['font_name'] )
self.dialog = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"RConfigDialog")
#Create our dictionay and connect it
dic = { "on_ButtonOk_clicked" : self.ButtonOk_clicked,
"on_ButtonCancel_clicked" : self.ButtonCancel_clicked,
"on_ChangeShortcuts_clicked" : self.ButtonChangeShortcuts_clicked,
"on_SidePanelOptions_clicked" : self.ButtonSidePanelOptions_clicked,
"on_CodeFoldingOptions_clicked" : self.ButtonCodeFoldingOptions_clicked,
"on_MainWindow_destroy" : Gtk.main_quit }
connect_signals_for_ui_GtkBuilder_or_Glade(self.ui,dic)
return self.dialog
def ButtonOk_clicked(self,widget):
# Make a copy of the old values to see what changed:
old_prefs = self.prefs.copy()
# Did the user define a color for any of the prompts?
prompt_color_defined = False
# Retrieve the data first:
check_box_autostart_R = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AutostartR")
self.prefs['autostart_R_console'] = check_box_autostart_R.get_active()
check_box_use_doc_dir = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"UseDocDirectory")
self.prefs['use_current_document_directory'] = check_box_use_doc_dir.get_active()
check_box_show_message = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ShowMessageCheck")
self.prefs['show_messages_and_warnings'] = check_box_show_message.get_active()
check_box_attach_R = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"StartRAttached")
self.prefs['RConsole_start_attached'] = check_box_attach_R.get_active()
check_box_autostart_script = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AutostartScriptCheck")
self.prefs['autostart_R_script'] = check_box_autostart_script.get_active()
file_chooser_autostart_script = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AutorunScriptPath")
self.prefs['autostart_R_script_path'] = file_chooser_autostart_script.get_filename()
if self.prefs['autostart_R_script_path'] == None:
self.prefs['autostart_R_script'] = False
spin_max_lines_as_text = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"MaxLinesToSendSpin")
self.prefs['max_lines_as_text'] = spin_max_lines_as_text.get_value_as_int()
check_box_HTML_help = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"HTMLHelpCheck")
self.prefs['HTML_help'] = check_box_HTML_help.get_active()
check_box_echo_commands = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"EchoPipedCommandsCheck")
self.prefs['echo_commands'] = check_box_echo_commands.get_active()
check_box_advance_line = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AdvanceLineCheck")
self.prefs['advance_to_next_line'] = check_box_advance_line.get_active()
check_box_skip_empty_and_comment = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"SkipEmptyAndCommentCheck")
self.prefs['skip_empty_and_comment_lines'] = check_box_skip_empty_and_comment.get_active()
check_box_audible_bell = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"AudibleBell")
self.prefs['audible_bell'] = check_box_audible_bell.get_active()
check_box_visible_bell = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"VisibleBell")
self.prefs['visible_bell'] = check_box_visible_bell.get_active()
check_box_scroll_on_keystroke = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ScrollOnKeystroke")
self.prefs['scroll_on_keystroke'] = check_box_scroll_on_keystroke.get_active()
check_box_scroll_on_output = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ScrollOnOutput")
self.prefs['scroll_on_output'] = check_box_scroll_on_output.get_active()
edit_scrollback_lines = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ScrollbackLines")
try:
no_lines = int(edit_scrollback_lines.get_text())
except:
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("The number of scrollback lines must be a positive integer!") )
error_dialog.run()
error_dialog.destroy()
return
if no_lines < 0:
error_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("The number of scrollback lines must be a positive integer!") )
error_dialog.run()
error_dialog.destroy()
return
self.prefs['scrollback_lines'] = no_lines
radio_button_cursor_blink_system = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BlinkSystem")
radio_button_cursor_blink_on = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BlinkOn")
radio_button_cursor_blink_off = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BlinkOff")
if radio_button_cursor_blink_system.get_active():
self.prefs['cursor_blink'] = "system"
elif radio_button_cursor_blink_on.get_active():
self.prefs['cursor_blink'] = "on"
elif radio_button_cursor_blink_off.get_active():
self.prefs['cursor_blink'] = "off"
radio_button_cursor_shape_block = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ShapeBlock")
radio_button_cursor_shape_ibeam = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ShapeIBeam")
radio_button_cursor_shape_underline = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ShapeUnderline")
if radio_button_cursor_shape_block.get_active():
self.prefs['cursor_shape'] = "block"
elif radio_button_cursor_shape_ibeam.get_active():
self.prefs['cursor_shape'] = "ibeam"
elif radio_button_cursor_shape_underline.get_active():
self.prefs['cursor_shape'] = "underline"
color_button_foreground1 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ForegroundColor1")
try:
self.prefs['foreground1'] = color_button_foreground1.get_color().to_string()
except AttributeError:
# Older gtk: Gdk.Color.to_string() is not defined: use my own:
self.prefs['foreground1'] = gtk_gdk_Color_to_string(color_button_foreground1.get_color())
color_button_background1 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BackgroundColor1")
try:
self.prefs['background1'] = color_button_background1.get_color().to_string()
except AttributeError:
# Older gtk: Gdk.Color.to_string() is not defined: use my own:
self.prefs['background1'] = gtk_gdk_Color_to_string(color_button_background1.get_color())
combo_box_prompt_color1 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"PromptColor1")
self.prefs['prompt_color1'] = self.xterm_color_from_index(combo_box_prompt_color1.get_active())
color_button_foreground2 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ForegroundColor2")
try:
self.prefs['foreground2'] = color_button_foreground2.get_color().to_string()
except AttributeError:
# Older gtk: Gdk.Color.to_string() is not defined: use my own:
self.prefs['foreground2'] = gtk_gdk_Color_to_string(color_button_foreground2.get_color())
color_button_background2 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BackgroundColor2")
try:
self.prefs['background2'] = color_button_background2.get_color().to_string()
except AttributeError:
# Older gtk: Gdk.Color.to_string() is not defined: use my own:
self.prefs['background2'] = gtk_gdk_Color_to_string(color_button_background2.get_color())
combo_box_prompt_color2 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"PromptColor2")
self.prefs['prompt_color2'] = self.xterm_color_from_index(combo_box_prompt_color2.get_active())
color_button_foreground3 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"ForegroundColor3")
try:
self.prefs['foreground3'] = color_button_foreground3.get_color().to_string()
except AttributeError:
# Older gtk: Gdk.Color.to_string() is not defined: use my own:
self.prefs['foreground3'] = gtk_gdk_Color_to_string(color_button_foreground3.get_color())
color_button_background3 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"BackgroundColor3")
try:
self.prefs['background3'] = color_button_background3.get_color().to_string()
except AttributeError:
# Older gtk: Gdk.Color.to_string() is not defined: use my own:
self.prefs['background3'] = gtk_gdk_Color_to_string(color_button_background3.get_color())
combo_box_prompt_color3 = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"PromptColor3")
self.prefs['prompt_color3'] = self.xterm_color_from_index(combo_box_prompt_color3.get_active())
check_box_tab_name_in_prompt = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"TabNameInPrompt")
self.prefs['tab_name_in_prompt'] = check_box_tab_name_in_prompt.get_active()
font_button = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"CurrentFont")
self.prefs['font_name'] = font_button.get_font_name()
# Save the preferences:
self.save_prefs()
self.dialog.destroy()
# See what changed:
vte1_console_changed = False
vte1_R_options_changed = False
vte2_console_changed = False
vte2_R_options_changed = False
vte3_console_changed = False
vte3_R_options_changed = False
# The ones affecting all consoles:
if (old_prefs['audible_bell'] != self.prefs['audible_bell']) or (old_prefs['cursor_blink'] != self.prefs['cursor_blink']) or (old_prefs['cursor_shape'] != self.prefs['cursor_shape']) or (old_prefs['emulation'] != self.prefs['emulation']) or (old_prefs['font_name'] != self.prefs['font_name']) or (old_prefs['scroll_on_keystroke'] != self.prefs['scroll_on_keystroke']) or (old_prefs['scroll_on_output'] != self.prefs['scroll_on_output']) or (old_prefs['scrollback_lines'] != self.prefs['scrollback_lines']) or (old_prefs['visible_bell'] != self.prefs['visible_bell']) or (old_prefs['word_chars'] != self.prefs['word_chars']) or (old_prefs['echo_commands'] != self.prefs['echo_commands']):
vte1_console_changed = True
vte2_console_changed = True
vte3_console_changed = True
if (old_prefs['tab_name_in_prompt'] != self.prefs['tab_name_in_prompt']) or (old_prefs['HTML_help'] != self.prefs['HTML_help']):
vte1_R_options_changed = True
vte2_R_options_changed = True
vte3_R_options_changed = True
# VTE1 specifically:
if (old_prefs['background1'] != self.prefs['background1']) or (old_prefs['foreground1'] != self.prefs['foreground1']):
vte1_console_changed = True
if (old_prefs['prompt_color1'] != self.prefs['prompt_color1']):
vte1_R_options_changed = True
if self.prefs['prompt_color1'] != None:
prompt_color_defined = True
# VTE2 specifically:
if (old_prefs['background2'] != self.prefs['background2']) or (old_prefs['foreground2'] != self.prefs['foreground2']):
vte2_console_changed = True
if (old_prefs['prompt_color2'] != self.prefs['prompt_color2']):
vte2_R_options_changed = True
if self.prefs['prompt_color2'] != None:
prompt_color_defined = True
# VTE3 specifically:
if (old_prefs['background3'] != self.prefs['background3']) or (old_prefs['foreground3'] != self.prefs['foreground3']):
vte3_console_changed = True
if (old_prefs['prompt_color3'] != self.prefs['prompt_color3']):
vte3_R_options_changed = True
if self.prefs['prompt_color3'] != None:
prompt_color_defined = True
# Warn the user about the side effects of color promts!
if prompt_color_defined:
warning_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, _("Please note that using COLORED PROMPTS has a side effect when browsing R's history (keys UP and DOWN).\nPlease see the manual for details.") )
warning_dialog.run()
warning_dialog.destroy()
# Get the R prompts to update themselves:
for i in list(self._instances.keys()):
rctrlhelper = self._instances[i]
rctrlhelper.update_R_consoles(vte1_console_changed,vte2_console_changed,vte3_console_changed,vte1_R_options_changed,vte2_R_options_changed,vte2_R_options_changed)
# Update the code folding as well:
self.code_folding_engine.update_code_folding(self.window,self.prefs['use_rgedit_code_folding'])
def ButtonCancel_clicked(self,widget):
self.dialog.destroy()
def ButtonChangeShortcuts_clicked(self,widget):
self.ChangeShortcuts_ui = create_UI_from_file_GtkBuilder_or_Glade(self.get_data_dir()+"/ShortcutsDialog.glade",self.get_data_dir()+"/ShortcutsDialog.ui")
edit_RCtrlLine_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlLine_Shortcut")
edit_RCtrlLine_Shortcut.set_text(str(self.prefs['shortcut_RCtrlLine']))
edit_RCtrlSel_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlSel_Shortcut")
edit_RCtrlSel_Shortcut.set_text(str(self.prefs['shortcut_RCtrlSel']))
edit_RCtrlAll_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlAll_Shortcut")
edit_RCtrlAll_Shortcut.set_text(str(self.prefs['shortcut_RCtrlAll']))
edit_RCtrlCursor_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlCursor_Shortcut")
edit_RCtrlCursor_Shortcut.set_text(str(self.prefs['shortcut_RCtrlCursor']))
edit_RCtrlBlock1Run_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlBlock1Run_Shortcut")
edit_RCtrlBlock1Run_Shortcut.set_text(str(self.prefs['shortcut_RCtrlBlock1Run']))
edit_RCtrlBlock1Def_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlBlock1Def_Shortcut")
edit_RCtrlBlock1Def_Shortcut.set_text(str(self.prefs['shortcut_RCtrlBlock1Def']))
edit_RCtrlBlock2Run_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlBlock2Run_Shortcut")
edit_RCtrlBlock2Run_Shortcut.set_text(str(self.prefs['shortcut_RCtrlBlock2Run']))
edit_RCtrlBlock2Def_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlBlock2Def_Shortcut")
edit_RCtrlBlock2Def_Shortcut.set_text(str(self.prefs['shortcut_RCtrlBlock2Def']))
edit_RCtrlNewTab_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlNewTab_Shortcut")
edit_RCtrlNewTab_Shortcut.set_text(str(self.prefs['shortcut_RCtrlNewTab']))
edit_RCtrlConfig_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlConfig_Shortcut")
edit_RCtrlConfig_Shortcut.set_text(str(self.prefs['shortcut_RCtrlConfig']))
edit_RCtrlLoadWorkspace_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlLoadWorkspace_Shortcut")
edit_RCtrlLoadWorkspace_Shortcut.set_text(str(self.prefs['shortcut_RCtrlLoadWorkspace']))
edit_RCtrlSaveWorkspace_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlSaveWorkspace_Shortcut")
edit_RCtrlSaveWorkspace_Shortcut.set_text(str(self.prefs['shortcut_RCtrlSaveWorkspace']))
edit_RCtrlAttach_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlAttach_Shortcut")
edit_RCtrlAttach_Shortcut.set_text(str(self.prefs['shortcut_RCtrlAttach']))
edit_RCtrlClose_Shortcut = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlClose_Shortcut")
edit_RCtrlClose_Shortcut.set_text(str(self.prefs['shortcut_RCtrlClose']))
check_CtrlC_4_Copy = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"CtrlC_4_Copy")
check_CtrlC_4_Copy.set_active(self.prefs['R_console_Ctrl_C_4_copy'])
check_CtrlC_4_Copy.set_sensitive(False)
check_CtrlQ_break = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"CtrlQ_break")
check_CtrlQ_break.set_active(self.prefs['R_console_Ctrl_Q_break'])
check_Escape_break = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"Escape_break")
check_Escape_break.set_active(self.prefs['R_console_Escape_break'])
ChangeShortcuts_dialog = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"EditKeyboardShortcuts")
malformed_data = True
while malformed_data == True:
malformed_data = False
response = ChangeShortcuts_dialog.run()
if response == -2: #OK button
# Collect the data:
shortcut_RCtrlLine = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlLine_Shortcut").get_text()
shortcut_RCtrlSel = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlSel_Shortcut").get_text()
shortcut_RCtrlAll = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlAll_Shortcut").get_text()
shortcut_RCtrlCursor = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlCursor_Shortcut").get_text()
shortcut_RCtrlBlock1Run = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlBlock1Run_Shortcut").get_text()
shortcut_RCtrlBlock1Def = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlBlock1Def_Shortcut").get_text()
shortcut_RCtrlBlock2Run = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlBlock2Run_Shortcut").get_text()
shortcut_RCtrlBlock2Def = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlBlock2Def_Shortcut").get_text()
shortcut_RCtrlNewTab = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlNewTab_Shortcut").get_text()
shortcut_RCtrlConfig = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlConfig_Shortcut").get_text()
shortcut_RCtrlLoadWorkspace = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlLoadWorkspace_Shortcut").get_text()
shortcut_RCtrlSaveWorkspace = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlSaveWorkspace_Shortcut").get_text()
shortcut_RCtrlAttach = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlAttach_Shortcut").get_text()
shortcut_RCtrlClose = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"RCtrlClose_Shortcut").get_text()
check_CtrlC_4_Copy = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"CtrlC_4_Copy").get_active()
check_CtrlQ_break = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"CtrlQ_break").get_active()
check_Escape_break = get_widget_from_ui_GtkBuilder_or_Glade(self.ChangeShortcuts_ui,"Escape_break").get_active()
# Check the data:
if shortcut_RCtrlLine == 'None':
shortcut_RCtrlLine = None
elif Gtk.accelerator_parse(shortcut_RCtrlLine) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Run current line' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlLine_Shortcut").grab_focus()
if shortcut_RCtrlSel == 'None':
shortcut_RCtrlSel = None
elif Gtk.accelerator_parse(shortcut_RCtrlSel) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Run selection' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlSel_Shortcut").grab_focus()
if shortcut_RCtrlAll == 'None':
shortcut_RCtrlAll = None
elif Gtk.accelerator_parse(shortcut_RCtrlAll) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Run whole file' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlAll_Shortcut").grab_focus()
if shortcut_RCtrlCursor == 'None':
shortcut_RCtrlCursor = None
elif Gtk.accelerator_parse(shortcut_RCtrlCursor) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Run to current line' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlCursor_Shortcut").grab_focus()
if shortcut_RCtrlBlock1Run == 'None':
shortcut_RCtrlBlock1Run = None
elif Gtk.accelerator_parse(shortcut_RCtrlBlock1Run) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Run block 1' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlBlock1Run_Shortcut").grab_focus()
if shortcut_RCtrlBlock1Def == 'None':
shortcut_RCtrlBlock1Def = None
elif Gtk.accelerator_parse(shortcut_RCtrlBlock1Def) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Define block 1' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlBlock1Def_Shortcut").grab_focus()
if shortcut_RCtrlBlock2Run == 'None':
shortcut_RCtrlBlock2Run = None
elif Gtk.accelerator_parse(shortcut_RCtrlBlock2Run) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Run block 2' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlBlock2Run_Shortcut").grab_focus()
if shortcut_RCtrlBlock2Def == 'None':
shortcut_RCtrlBlock2Def = None
elif Gtk.accelerator_parse(shortcut_RCtrlBlock2Def) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Define block 2' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlBlock2Def_Shortcut").grab_focus()
if shortcut_RCtrlNewTab == 'None':
shortcut_RCtrlNewTab = None
elif Gtk.accelerator_parse(shortcut_RCtrlNewTab) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Create new R tab' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlNewTab_Shortcut").grab_focus()
if shortcut_RCtrlConfig == 'None':
shortcut_RCtrlConfig = None
elif Gtk.accelerator_parse(shortcut_RCtrlConfig) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Configure R interface' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlConfig_Shortcut").grab_focus()
if shortcut_RCtrlLoadWorkspace == 'None':
shortcut_RCtrlLoadWorkspace = None
elif Gtk.accelerator_parse(shortcut_RCtrlLoadWorkspace) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Load R Workspace' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlLoadWorkspace_Shortcut").grab_focus()
if shortcut_RCtrlSaveWorkspace == 'None':
shortcut_RCtrlSaveWorkspace = None
elif Gtk.accelerator_parse(shortcut_RCtrlSaveWorkspace) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Save R Workspace' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlSaveWorkspace_Shortcut").grab_focus()
if shortcut_RCtrlAttach == 'None':
shortcut_RCtrlAttach = None
elif Gtk.accelerator_parse(shortcut_RCtrlAttach) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Attach/detach R console' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlAttach_Shortcut").grab_focus()
if shortcut_RCtrlClose == 'None':
shortcut_RCtrlClose = None
elif Gtk.accelerator_parse(shortcut_RCtrlClose) == (0,0):
malformed_data = True
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Key shortcut for 'Close R console' is malformed!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
ChangeShortcuts_ui.get_widget("RCtrlClose_Shortcut").grab_focus()
# See if the data has changed:
#if shortcut_RCtrlLine != self.prefs['shortcut_RCtrlLine'] or shortcut_RCtrlSel != self.prefs['shortcut_RCtrlSel'] or shortcut_RCtrlAll != self.prefs['shortcut_RCtrlAll'] or shortcut_RCtrlBlock1Run != self.prefs['shortcut_RCtrlBlock1Run'] or shortcut_RCtrlBlock1Def != self.prefs['shortcut_RCtrlBlock1Def'] or shortcut_RCtrlBlock2Run != self.prefs['shortcut_RCtrlBlock2Run'] or shortcut_RCtrlBlock2Def != self.prefs['shortcut_RCtrlBlock2Def'] or shortcut_RCtrlNewTab != self.prefs['shortcut_RCtrlNewTab'] or shortcut_RCtrlConfig != self.prefs['shortcut_RCtrlConfig'] or shortcut_RCtrlLoadWorkspace != self.prefs['shortcut_RCtrlLoadWorkspace'] or shortcut_RCtrlSaveWorkspace != self.prefs['shortcut_RCtrlSaveWorkspace'] or shortcut_RCtrlHelpSel != self.prefs['shortcut_RCtrlHelpSel'] or shortcut_RCtrlShowSel != self.prefs['shortcut_RCtrlShowSel'] or shortcut_RCtrlEditSel != self.prefs['shortcut_RCtrlEditSel'] or shortcut_RCtrlAttach != self.prefs['shortcut_RCtrlAttach'] or shortcut_RCtrlClose != self.prefs['shortcut_RCtrlClose']:
if shortcut_RCtrlLine != self.prefs['shortcut_RCtrlLine'] or shortcut_RCtrlSel != self.prefs['shortcut_RCtrlSel'] or shortcut_RCtrlAll != self.prefs['shortcut_RCtrlAll'] or shortcut_RCtrlCursor != self.prefs['shortcut_RCtrlCursor'] or shortcut_RCtrlBlock1Run != self.prefs['shortcut_RCtrlBlock1Run'] or shortcut_RCtrlBlock1Def != self.prefs['shortcut_RCtrlBlock1Def'] or shortcut_RCtrlBlock2Run != self.prefs['shortcut_RCtrlBlock2Run'] or shortcut_RCtrlBlock2Def != self.prefs['shortcut_RCtrlBlock2Def'] or shortcut_RCtrlNewTab != self.prefs['shortcut_RCtrlNewTab'] or shortcut_RCtrlConfig != self.prefs['shortcut_RCtrlConfig'] or shortcut_RCtrlLoadWorkspace != self.prefs['shortcut_RCtrlLoadWorkspace'] or shortcut_RCtrlSaveWorkspace != self.prefs['shortcut_RCtrlSaveWorkspace'] or shortcut_RCtrlAttach != self.prefs['shortcut_RCtrlAttach'] or shortcut_RCtrlClose != self.prefs['shortcut_RCtrlClose'] or check_CtrlC_4_Copy != self.prefs['R_console_Ctrl_C_4_copy'] or check_CtrlQ_break != self.prefs['R_console_Ctrl_Q_break'] or check_Escape_break != self.prefs['R_console_Escape_break']:
shortcut_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, _("Key shortcuts have changed:\nplease restart gedit for changed to become effective!") )
shortcut_dialog.run()
shortcut_dialog.destroy()
self.prefs['shortcut_RCtrlLine'] = shortcut_RCtrlLine
self.prefs['shortcut_RCtrlSel'] = shortcut_RCtrlSel
self.prefs['shortcut_RCtrlAll'] = shortcut_RCtrlAll
self.prefs['shortcut_RCtrlCursor'] = shortcut_RCtrlCursor
self.prefs['shortcut_RCtrlBlock1Run'] = shortcut_RCtrlBlock1Run
self.prefs['shortcut_RCtrlBlock1Def'] = shortcut_RCtrlBlock1Def
self.prefs['shortcut_RCtrlBlock2Run'] = shortcut_RCtrlBlock2Run
self.prefs['shortcut_RCtrlBlock2Def'] = shortcut_RCtrlBlock2Def
self.prefs['shortcut_RCtrlNewTab'] = shortcut_RCtrlNewTab
self.prefs['shortcut_RCtrlConfig'] = shortcut_RCtrlConfig
self.prefs['shortcut_RCtrlLoadWorkspace'] = shortcut_RCtrlLoadWorkspace
self.prefs['shortcut_RCtrlSaveWorkspace'] = shortcut_RCtrlSaveWorkspace
self.prefs['shortcut_RCtrlAttach'] = shortcut_RCtrlAttach
self.prefs['shortcut_RCtrlClose'] = shortcut_RCtrlClose
self.prefs['R_console_Ctrl_C_4_copy'] = check_CtrlC_4_Copy
self.prefs['R_console_Ctrl_Q_break'] = check_CtrlQ_break
self.prefs['R_console_Escape_break'] = check_Escape_break
ChangeShortcuts_dialog.destroy()
def ButtonSidePanelOptions_clicked(self,widget):
self.SidePanelOptions_ui = create_UI_from_file_GtkBuilder_or_Glade(self.get_data_dir()+"/SidePanelOptions.glade",self.get_data_dir()+"/SidePanelOptions.ui")
check_IncludeLandmarksCheck = get_widget_from_ui_GtkBuilder_or_Glade(self.SidePanelOptions_ui,"IncludeLandmarksCheck")
check_IncludeLandmarksCheck.set_active(self.prefs['R_structure_landmarks'])
check_IncludeFunctionsCheck = get_widget_from_ui_GtkBuilder_or_Glade(self.SidePanelOptions_ui,"IncludeFunctionsCheck")
check_IncludeFunctionsCheck.set_active(self.prefs['R_structure_functions'])
check_IncludeDataframesCheck = get_widget_from_ui_GtkBuilder_or_Glade(self.SidePanelOptions_ui,"IncludeDataframesCheck")
check_IncludeDataframesCheck.set_active(self.prefs['R_structure_dataframes'])
SidePanelOptions_dialog = get_widget_from_ui_GtkBuilder_or_Glade(self.SidePanelOptions_ui,"SidePanelOptionsDialog")
response = SidePanelOptions_dialog.run()
if response == -2: #OK button
# Collect the data: save the info and update the side panel:
self.prefs['R_structure_landmarks'] = check_IncludeLandmarksCheck.get_active()
self.prefs['R_structure_functions'] = check_IncludeFunctionsCheck.get_active()
self.prefs['R_structure_dataframes'] = check_IncludeDataframesCheck.get_active()
# Update the panels of all windows:
for window in self._instances.keys():
self._instances[window]._rstructurepanel.create_pattern_matcher()
self._instances[window]._rstructurepanel.on_force_refresh(None)
SidePanelOptions_dialog.destroy()
def ButtonCodeFoldingOptions_clicked(self,widget):
self.CodeFoldingOptions_ui = create_UI_from_file_GtkBuilder_or_Glade(self.get_data_dir()+"/CodeFoldingOptions.glade",self.get_data_dir()+"/CodeFoldingOptions.ui")
check_UseRgeditCodeFoldingCheck = get_widget_from_ui_GtkBuilder_or_Glade(self.CodeFoldingOptions_ui,"UseRgeditCodeFoldingCheck")
check_UseRgeditCodeFoldingCheck.set_active(self.prefs['use_rgedit_code_folding'])
radio_PreferHighestBlockRadio = get_widget_from_ui_GtkBuilder_or_Glade(self.CodeFoldingOptions_ui,"PreferHighestBlockRadio")
radio_PreferLowestBlockRadio = get_widget_from_ui_GtkBuilder_or_Glade(self.CodeFoldingOptions_ui,"PreferLowestBlockRadio")
radio_PreferHighestFunctionRadio = get_widget_from_ui_GtkBuilder_or_Glade(self.CodeFoldingOptions_ui,"PreferHighestFunctionRadio")
radio_PreferLowestFunctionRadio = get_widget_from_ui_GtkBuilder_or_Glade(self.CodeFoldingOptions_ui,"PreferLowestFunctionRadio")
if self.prefs['code_folding_block_preference'] == 'highest_block':
radio_PreferHighestBlockRadio.set_active(True)
elif self.prefs['code_folding_block_preference'] == 'lowest_block':
radio_PreferLowestBlockRadio.set_active(True)
elif self.prefs['code_folding_block_preference'] == 'highest_function':
radio_PreferHighestFunctionRadio.set_active(True)
elif self.prefs['code_folding_block_preference'] == 'lowest_function':
radio_PreferLowestFunctionRadio.set_active(True)
else:
print "Unknown block preference option '" + str(self.prefs['code_folding_block_preference']) + "'!"
radio_PreferHighestBlockRadio.set_active(True)
CodeFoldingOptions_dialog = get_widget_from_ui_GtkBuilder_or_Glade(self.CodeFoldingOptions_ui,"CodeFoldingOptionsDialog")
response = CodeFoldingOptions_dialog.run()
if response == -2: #OK button
# Collect the data: save the info and update the side panel:
self.prefs['use_rgedit_code_folding'] = check_UseRgeditCodeFoldingCheck.get_active()
if radio_PreferHighestBlockRadio.get_active():
self.prefs['code_folding_block_preference'] = 'highest_block'
elif radio_PreferLowestBlockRadio.get_active():
self.prefs['code_folding_block_preference'] = 'lowest_block'
elif radio_PreferHighestFunctionRadio.get_active():
self.prefs['code_folding_block_preference'] = 'highest_function'
elif radio_PreferLowestFunctionRadio.get_active():
self.prefs['code_folding_block_preference'] = 'lowest_function'
else:
# default:
self.prefs['code_folding_block_preference'] = 'highest_block'
# Update the folding:
if not self.prefs['use_rgedit_code_folding']:
# Unfold everything:
for window in self._instances.keys():
for view in window.get_views():
self.code_folding_engine.unfold_all(view.get_buffer(),view)
CodeFoldingOptions_dialog.destroy()
########################################################################
# The Wizard stuff
########################################################################
# Get the text from collection of XML nodes:
def getText_from_XML(nodelist):
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc
# Class implementing the wizard-wide about box:
class RWizard_AboutBox:
def __init__(self):
# Init:
self.path = None # the path used for finding icons and stuff
self.name = None
self.version = None
self.copyright = None
self.comments = None
self.license = None
self.website = None
self.authors = None
self.documenters = None
self.artists = None
self.translator_credits = None
self.logo_icon_name = None
def do_process_about(self,xml_node):
# Get the about info:
if xml_node.hasAttribute("name"):
self.name = xml_node.getAttribute("name")
if xml_node.hasAttribute("version"):
self.version = xml_node.getAttribute("version")
if xml_node.hasAttribute("copyright"):
self.copyright = xml_node.getAttribute("copyright")
if xml_node.hasAttribute("comments"):
self.comments = xml_node.getAttribute("comments")
if xml_node.hasAttribute("license"):
self.license = xml_node.getAttribute("license")
if xml_node.hasAttribute("website"):
self.website = xml_node.getAttribute("website")
if xml_node.hasAttribute("authors"):
self.authors = xml_node.getAttribute("authors").split(",")
if xml_node.hasAttribute("documenters"):
self.documenters = xml_node.getAttribute("documenters")
if xml_node.hasAttribute("artists"):
self.artists = xml_node.getAttribute("artists")
if xml_node.hasAttribute("translator_credits"):
self.translator_credits = xml_node.getAttribute("translator_credits")
if xml_node.hasAttribute("logo_icon_name"):
self.logo_icon_name = self.path + xml_node.getAttribute("logo_icon_name")
return True
def show(self):
# Display the about info:
about_dialog = Gtk.AboutDialog()
about_dialog.set_name(self.name)
about_dialog.set_version(self.version)
about_dialog.set_copyright(self.copyright)
about_dialog.set_comments(self.comments)
about_dialog.set_license(self.license)
about_dialog.set_website(self.website)
about_dialog.set_authors(self.authors)
about_dialog.set_documenters(self.documenters)
about_dialog.set_artists(self.artists)
about_dialog.set_translator_credits(self.translator_credits)
about_dialog.set_logo(GdkPixbuf.Pixbuf.new_from_file(self.logo_icon_name))
about_dialog.show()
about_dialog.run()
about_dialog.destroy()
# Class implementing a template:
class RWizard_Template:
def __init__(self):
# Init:
self.RawText = None
def do_process_template(self,xml_node):
# Get the node's text (i.e., the raw template):
self.RawText = getText_from_XML(xml_node.childNodes)
return True
def update(self,variables):
# Update the template using the variable values in the given dictionary:
new_template = self.RawText
# Process the $[Python ... $] python directives:
new_template = self.process_directives(new_template,variables)
if new_template == None:
# Some error has occured:
return None
# Replace the ${xxx} with xxx's value:
for variable in variables:
new_template = new_template.replace( "${" + variable + "}", str(variables[variable]) )
return new_template
def process_directives(self,template,variables):
# Process the $[ ... $] directives:
# For now, only Python scripting executed:
python_directive_start = template.find("$[Python")
while python_directive_start != -1:
# Found a directive: get the whole expression
python_directive_end = template.find("$]",python_directive_start)
if python_directive_end == -1:
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Python directives must end with $]....") )
response = question_dialog.run()
question_dialog.destroy()
return None
# Evaluate the condition:
python_directive = template[(python_directive_start+len("$[Python")):python_directive_end]
#print python_directive
for variable in variables:
python_directive = python_directive.replace( "${" + variable + "}", str(variables[variable]) )
python_directive = eval(python_directive,__builtins__)
#python_directive = eval(python_directive, {"__builtins__":None}, {})
# And replace the result appropriately
if python_directive == None:
python_directive = ""
else:
python_directive = str(python_directive)
template = template.replace( template[python_directive_start:(python_directive_end+len("$]"))], python_directive )
# Search for the next directive:
python_directive_start = template.find("$[Python")
return template
# Debug printing:
def print_debug(self):
print "Template: " + str(self.RawText)
# Class implementing a varibale within the block:
class RWizard_Variable:
def __init__(self):
# Init:
self.Name = None
self.Description = False
self.Required = False
self.Type = None
self.Default = None
self.Singlechoice = True
self.ToolTip = None
self.ListValues = []
self.GtkControl = None # the associated Gtk control (if any)
self.ValueDefined = False # has the variable's value been already defined?
self.Value = None # and the actual value (if any)
def get_value(self):
# Return the value adjusted for final usage (e.g., for comboboxes return the actually selected string):
if self.Type.lower() == "list":
return self.ListValues[self.Value]
else:
return self.Value
def do_process_variable(self,xml_node):
# Read the attributes:
if xml_node.hasAttribute("name"):
self.Name = xml_node.getAttribute("name")
else:
print _("A variable must have a name!")
return False
if xml_node.hasAttribute("description"):
self.Description = xml_node.getAttribute("description")
else:
print _("A variable must have a description!")
return False
if xml_node.hasAttribute("required"):
self.Required = (xml_node.getAttribute("required").lower() == "true")
if xml_node.hasAttribute("type"):
self.Type = xml_node.getAttribute("type")
else:
print _("A variable must have a type!")
return False
if xml_node.hasAttribute("default"):
self.Default = xml_node.getAttribute("default")
if xml_node.hasAttribute("singlechoice"):
self.Singlechoice = xml_node.getAttribute("singlechoice")
if xml_node.hasAttribute("tooltip"):
self.ToolTip = xml_node.getAttribute("tooltip")
if self.Type == "list":
# Try to get the values:
values_nodes = xml_node.getElementsByTagName("value")
if values_nodes == None and len(values_nodes) == 0:
print _("Variables of type \"list\" must have at least one value defined!")
return False
else:
# Get the values:
for value_node in values_nodes:
if value_node.hasAttribute("name"):
self.ListValues = self.ListValues + [value_node.getAttribute("name")]
if len(self.ListValues) == 0:
print _("Variables of type \"list\" must have at least one value defined!")
elif self.Type == "editablelist":
# Try to get the values:
values_nodes = xml_node.getElementsByTagName("value")
if values_nodes == None and len(values_nodes) == 0:
print _("Variables of type \"editablelist\" must have at least one value defined!")
return False
else:
# Get the values:
for value_node in values_nodes:
if value_node.hasAttribute("name"):
self.ListValues = self.ListValues + [value_node.getAttribute("name")]
if len(self.ListValues) == 0:
print _("Variables of type \"editablelist\" must have at least one value defined!")
return True
# Debug printing:
def print_debug(self):
print "Variable: " + str(self.Name) + " [" + str(self.Description) + " type=" + str(self.Type) + " default=" + str(self.Default) + "]"
if str(self.Type) == "list":
print " Values: " + str(self.ListValues)
# Class implementing a block within the vars:
class RWizard_Block:
def __init__(self):
# Init:
self.Title = None
self.Rselector = False
self.Layout = "vertical" # can be "vertical", "horizontal" or "grid"
self.Variables = [] # the list of variables
# Dialog params;
self.max_initial_width = 600
self.max_initial_height = 300
def do_process_block(self,xml_node):
# Get the title:
if xml_node.hasAttribute("title"):
self.Title = xml_node.getAttribute("title")
# and the other optional attributes:
if xml_node.hasAttribute("rselector"):
self.Rselector = xml_node.getAttribute("rselector")
if xml_node.hasAttribute("layout"):
self.Layout = xml_node.getAttribute("layout")
# Parse the variables within this block:
variables_node = xml_node.getElementsByTagName("variable")
if variables_node == None or len(variables_node) == 0:
print "Blocks must have at least one variable!"
return False
for variable_node in variables_node:
variable = RWizard_Variable()
if not variable.do_process_variable(variable_node):
return False
else:
self.Variables = self.Variables + [variable]
if len(self.Variables) == 0:
print _("There must be at least one variable defined for each block!")
return False
return True
# Debug printing:
def print_debug(self):
print "Block: " + str(self.Title) + "[rselector=" + str(self.Rselector) + " layout=" + str(self.Layout) + "]"
for variable in self.Variables:
variable.print_debug()
def run(self,wizard,is_previous,is_next,is_last,selection_as,selection_text):
# Construct and display the wizard block and collect user input:
# Return the following codes: 0 = cancel, -1 = previous, 1 = next/OK, 2 = OK & just run the data
label = Gtk.Label(label=self.Title)
dialog = Gtk.Dialog(wizard.Description,
None,
Gtk.DialogFlags.DESTROY_WITH_PARENT,)
#dialog.vbox.pack_start(label, True, True, 0)
dialog.get_content_area().pack_start(label, True, True, 0)
label.show()
## Embed the controls in a scrollable area, just in case they tend to be bigger than the available screen space:
#holder_scrollable = Gtk.ScrolledWindow()
#holder_scrollable.set_policy(Gtk.PolicyType.AUTOMATIC,Gtk.PolicyType.AUTOMATIC)
#holder_scrollable.show()
#holder_layout = Gtk.Layout()
#holder_layout.show()
# Start adding the required widgets for each variable:
container_vbox = Gtk.VBox()
container_vbox.show()
for variable in self.Variables:
self.add_widgets_for_variable(container_vbox,variable,selection_as,selection_text)
#holder_layout.put(container_vbox,0,0)
# And adjust the size accordingly
#holder_layout.set_size(self.max_width,self.max_height)
#holder_scrollable.add(holder_layout)
#dialog.vbox.pack_start(holder_scrollable, True, True, 0)
dialog.get_content_area().pack_start(container_vbox, True, True, 0)
# The buttons:
about_button = dialog.add_button(_("About"), 1303 ) # About the wizard
about_button.set_sensitive( wizard.AboutInfo != None )
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
about_button.set_tooltip_text(_("About the wizard..."))
help_button = dialog.add_button(_("Help"), 1304 ) # Help on the dialog
help_button.set_sensitive( wizard.Help != None )
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
help_button.set_tooltip_text("Wizard's help info...")
#dialog.action_area.add(Gtk.HSeparator())
back_button = dialog.add_button(_("Back"), 1299 ) # Going back
back_button.set_sensitive( is_previous )
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
back_button.set_tooltip_text(_("Go to previous block..."))
if is_last:
ok_button = dialog.add_button(_("Inspect code"), 1302 ) # OK and end
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
ok_button.set_tooltip_text(_("Inspect the generated R code..."))
run_button = dialog.add_button(_("Run code!"), 1305 ) # Ok and just run
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
run_button.set_tooltip_text(_("I trust the wizard: go ahead and run the generated R code..."))
else:
next_button = dialog.add_button(_("Next"), 1301 ) # Next
next_button.set_sensitive( is_next )
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
next_button.set_tooltip_text(_("Continue to next block..."))
cancel_button = dialog.add_button(_("Cancel"), 1300 ) # Cancel
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
cancel_button.set_tooltip_text(_("Cancel the wizard..."))
# The initial dialog size:
initial_size = dialog.get_size()
if initial_size[0] > self.max_initial_width:
initial_width = self.max_initial_width
else:
initial_width = initial_size[0]
if initial_size[1] > self.max_initial_height:
initial_height = self.max_initial_height
else:
initial_height = initial_size[1]
dialog.resize( initial_width, initial_height )
ret_val = 999
while ret_val == 999:
# Allow the user to interact with it and collect the response;
response = dialog.run()
# Process the user response value:
if response == 1300:
# Aborted: don't collect the data!
ret_val = 0
elif response == 1301 or response == 1302:
# Forward or OK: collect the data!
if not self.collect_data(dialog):
ret_val = 999 # don't close the dialog!!!
else:
ret_val = 1
elif response == 1299:
# Back: collect the data!
self.collect_data(dialog)
ret_val = -1
elif response == 1303:
# Display the about info:
wizard.AboutInfo.show()
ret_val = 999 # don't close the dialog!!!
elif response == 1304:
# Display the help info:
if wizard.Help:
if wizard.Help[0] == "?":
# R entity:
do_send_to_R(wizard.Help[1:]+"\n",wizard._rwizardengine._rctrlwindowhelper.R_widget,False)
else:
webbrowser.open(wizard.Help)
ret_val = 999 # don't close the dialog!!!
elif response == 1305:
# Just run the code!
if not self.collect_data(dialog):
ret_val = 999 # don't close the dialog!!!
else:
ret_val = 2
else:
# Aborted: don't collect the data!
ret_val = 0
# Destroy the dialog and return the value:
dialog.destroy()
return ret_val
def add_widgets_for_variable(self,container_vbox,variable,selection_as,selection_text):
# Add the appropriate widgets for the variable in the holder_layout at the positions given by self.current_x and self.current_y (and update them appropriately):
container_hbox = Gtk.HBox()
container_hbox.show()
var_text = ("<b>*</b>","")[not variable.Required] + variable.Description + str(" (<b><tt>") + variable.Name + str("</tt></b>): ")
if variable.Type.lower() == "text":
# text widget:
var_label = Gtk.Label()
var_label.set_markup(var_text)
if variable.ToolTip and use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
var_label.set_tooltip_markup(variable.ToolTip)
var_label.show()
container_hbox.add(var_label)
var_edit = Gtk.Entry()
var_edit.set_has_frame(True)
if variable.ToolTip and use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
var_edit.set_tooltip_markup(variable.ToolTip)
var_edit.show()
container_hbox.add(var_edit)
variable.GtkControl = var_edit
if variable.Default:
var_edit.set_text(variable.Default)
if variable.ValueDefined:
var_edit.set_text(variable.Value)
elif selection_as != None and selection_as.lower() == variable.Name.lower() and selection_text != None:
var_edit.set_text(selection_text)
elif variable.Type.lower() == "list":
# list widget:
if variable.Singlechoice.lower() == "true":
# it's a combobox!
var_label = Gtk.Label()
var_label.set_markup(var_text)
if variable.ToolTip and use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
var_label.set_tooltip_markup(variable.ToolTip)
var_label.show()
container_hbox.add(var_label)
var_combo = Gtk.ComboBoxText()
for value in variable.ListValues:
var_combo.append_text(value)
default_choice = -1
try:
default_choice = int(variable.Default)
except ValueError:
default_choice = -1
var_combo.set_active(default_choice)
if variable.ToolTip and use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
var_combo.set_tooltip_markup(variable.ToolTip)
var_combo.show()
container_hbox.add(var_combo)
variable.GtkControl = var_combo
if variable.ValueDefined:
var_combo.set_active(variable.Value)
elif variable.Type.lower() == "editablelist":
# editablelist widget:
if variable.Singlechoice.lower() == "true":
# it's a comboboxentry!
var_label = Gtk.Label()
var_label.set_markup(var_text)
if variable.ToolTip and use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
var_label.set_tooltip_markup(variable.ToolTip)
var_label.show()
container_hbox.add(var_label)
var_combo_edit = Gtk.combo_box_entry_new_text()
for value in variable.ListValues:
var_combo_edit.append_text(value)
var_combo_edit.get_child().set_text(variable.Default)
if variable.ToolTip and use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
var_combo_edit.set_tooltip_markup(variable.ToolTip)
var_combo_edit.show()
container_hbox.add(var_combo_edit)
variable.GtkControl = var_combo_edit
if variable.ValueDefined:
var_combo_edit.get_child().set_text(variable.Value)
elif variable.Type.lower() == "bool":
# checkbox:
var_label = Gtk.Label()
var_label.set_markup(var_text)
if variable.ToolTip and use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
var_label.set_tooltip_markup(variable.ToolTip)
var_label.show()
container_hbox.add(var_label)
var_check = Gtk.CheckButton()
if variable.ToolTip and use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
var_check.set_tooltip_markup(variable.ToolTip)
var_check.show()
container_hbox.add(var_check)
variable.GtkControl = var_check
if variable.Default:
var_check.set_active(variable.Default.lower() == "true")
if variable.ValueDefined:
var_check.set_active(variable.Value)
# add this row to the dialog:
container_vbox.add(container_hbox)
def collect_data(self,dialog):
# Collect the user-introduced data and save it in the appropriate places: return True if all required variables are defined
for variable in self.Variables:
self.collect_data_for_variable(variable)
if variable.Required and not variable.ValueDefined:
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _('Required variable "') + variable.Name + _('" is undefined!') )
response = question_dialog.run()
question_dialog.destroy()
return False
return True
def collect_data_for_variable(self,variable):
if variable.GtkControl == None:
print _("Error: variable.GtkControl should have been defined!")
variable.Value = None
variable.ValueDefined = False
return
if variable.Type.lower() == "text":
# Gtk.Entry:
variable.Value = variable.GtkControl.get_text()
variable.ValueDefined = (variable.Value.strip() != "")
elif variable.Type.lower() == "list":
# list widget:
if variable.Singlechoice.lower() == "true":
# Gtk.ComboBoxText():
variable.Value = variable.GtkControl.get_active()
variable.ValueDefined = True
elif variable.Type.lower() == "editablelist":
# list widget:
if variable.Singlechoice.lower() == "true":
# Gtk.ComboBoxText():
variable.Value = variable.GtkControl.get_child().get_text()
variable.ValueDefined = True
elif variable.Type.lower() == "bool":
# Gtk.CheckButton()
variable.Value = variable.GtkControl.get_active()
variable.ValueDefined = True
else:
variable.Value = None
variable.ValueDefined = False
# This class implements a single wizard:
class RWizard:
def __init__(self,_rwizardengine):
# Init the wizard:
self._rwizardengine = _rwizardengine
self.Name = None
self.Description = None
# The desired (i.e., suggested by the rwizard itself) menu, icon, toolbar status and keyboard shortuct:
self.DesiredMenu = None
self.DesiredIcon = None
self.DesiredToolbar = None
self.DesiredShortcut = None
# ... and the actual (i.e., taking into account the user preferences and default rules) ones:
self.ActualMenu = None
self.ActualIcon = None
self.ActualToolbar = None
self.ActualShortcut = None
# The list of blocks and the template:
self.Blocks = []
self.Template = None
# About info and help:
self.AboutInfo = None
self.Help = None
# Default button:
self.DefaultButton = 0 # 0 = Just paste, 1 = Just run, 2 = Paste & run
self.SelectionAs = None
self.SelectedText = None # the selection text (if any) when the dialog is fired (to be used as instructed by SelectionAs)
return
# Try to load and create a wizard from the given file description and return True inf successful, False otherwise
def load(self,file_name):
# Open the file for reading:
try:
wizard_doc = minidom.parse( file_name )
except:
print _("Error opening & parsing wizard file \"") + file_name + "\": ", sys.exc_info()[1]
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Error opening & parsing wizard file \"") + file_name + "\":\n" + str(sys.exc_info()[1]) + _("\n\nRgedit plugin cannot continue! Please fix the problem...") )
response = question_dialog.run()
question_dialog.destroy()
return False
# Proceed through the DOM and get the relevant stuff:
root_node = wizard_doc.documentElement;
if root_node.nodeName.lower() != 'rwizard':
print _("Error: rwizard xml expected, and instead got \"") + root_node.nodeName.lower() + "\"..."
wizard_doc.unlink()
return False;
# Get the name and description:
if not root_node.hasAttribute("name"):
print _("Error: rwizard must have a name!")
wizard_doc.unlink()
return False;
self.Name = root_node.getAttribute("name")
if root_node.hasAttribute("description"):
self.Description = root_node.getAttribute("description")
else:
self.Description = self.Name
if root_node.hasAttribute("menu"):
self.DesiredMenu = root_node.getAttribute("menu")
else:
self.DesiredMenu = self.Name
if root_node.hasAttribute("icon"):
self.DesiredIcon = root_node.getAttribute("icon")
else:
self.DesiredIcon = self.Name
if root_node.hasAttribute("toolbar"):
self.DesiredToolbar = root_node.getAttribute("toolbar")
else:
self.DesiredToolbar = self.Name
if root_node.hasAttribute("shortcut"):
self.DesiredShortcut = root_node.getAttribute("shortcut")
else:
self.DesiredShortcut = self.Name
if root_node.hasAttribute("defaultbutton"):
if root_node.getAttribute("defaultbutton").lower() == "paste":
self.DefaultButton = 0
elif root_node.getAttribute("defaultbutton").lower() == "run":
self.DefaultButton = 1
elif root_node.getAttribute("defaultbutton").lower() == "paste and run":
self.DefaultButton = 2
else:
print _("Unknown value for the defaultbutton attribute :") + root_node.getAttribute("defaultbutton")
if root_node.hasAttribute("selectionas"):
self.SelectionAs = root_node.getAttribute("selectionas")
# Process the about info:
about_node = root_node.getElementsByTagName("about")
if about_node != None:
if len(about_node) == 1:
if not self.do_process_about( about_node[0] ):
wizard_doc.unlink()
return False
elif len(about_node) > 1:
print _("There must at most one \"about\" node inside a \"rwizard\"")
wizard_doc.unlink()
return False
# Process the help file, url or R entiry:
help_node = root_node.getElementsByTagName("help")
if help_node != None:
if len(help_node) == 1:
if not self.do_process_help( help_node[0] ):
wizard_doc.unlink()
return False
elif len(help_node) > 1:
print _("There must at most one \"help\" node inside a \"rwizard\"")
wizard_doc.unlink()
return False
# Process the variables:
vars_node = root_node.getElementsByTagName("vars")
if vars_node != None and len(vars_node) == 1:
if not self.do_process_vars( vars_node[0] ):
wizard_doc.unlink()
return False
else:
print _("There must a single \"vars\" node inside a \"rwizard\"")
wizard_doc.unlink()
return False
# Process the script:
script_node = root_node.getElementsByTagName("script")
if script_node != None:
if len(script_node) == 1:
if not self.do_process_script( script_node[0] ):
wizard_doc.unlink()
return False
elif len(script_node) > 1:
print _("There must at most one \"script\" node inside a \"rwizard\"")
wizard_doc.unlink()
return False
# Process the template:
template_node = root_node.getElementsByTagName("template")
if template_node != None and len(template_node) == 1:
if not self.do_process_template( template_node[0] ):
wizard_doc.unlink()
return False
else:
print _("There must a single \"template\" node inside a \"rwizard\"")
wizard_doc.unlink()
return False
# Reconcile the options requested by the izard with those defined by the user and the default ones:
if self.DesiredMenu != None:
self.ActualMenu = self.DesiredMenu
else:
self.ActualMenu = self._rwizardengine.get_menu(self.Name)
if self.DesiredIcon != None:
self.ActualIcon = self.DesiredIcon
else:
self.ActualIcon = self._rwizardengine.get_icon(self.Name)
if self.DesiredToolbar != None:
self.ActualToolbar = self.DesiredToolbar
else:
self.ActualToolbar = self._rwizardengine.get_toolbar(self.Name)
if self.DesiredShortcut != None:
self.ActualShortcut = self.DesiredShortcut
else:
self.ActualShortcut = self._rwizardengine.get_shortcut(self.Name)
# Everything's ok:
wizard_doc.unlink()
return True
def do_process_vars(self,xml_node):
# Process the blocks inside this vars element:
block_nodes = xml_node.getElementsByTagName("block")
for block_node in block_nodes:
if not self.do_process_block( block_node ):
return False
#if len(self.Blocks) == 0:
# print "There must be at least one block defined!"
# return False
return True
def do_process_about(self,xml_node):
# Create the about dialog:
self.AboutInfo = RWizard_AboutBox()
self.AboutInfo.Name = self.Description
self.AboutInfo.path = self._rwizardengine.path
# Parse it!
return self.AboutInfo.do_process_about(xml_node)
def do_process_help(self,xml_node):
# Try to get the help file:
if xml_node.hasAttribute("file"):
self.Help = "file://" + self._rwizardengine.path + xml_node.getAttribute("file")
elif xml_node.hasAttribute("url"):
self.Help = xml_node.getAttribute("url")
elif xml_node.hasAttribute("rhelp"):
self.Help = "?" + xml_node.getAttribute("rhelp")
return True
def do_process_block(self,xml_node):
# Create a new block and read its contents:
block = RWizard_Block()
# Parse it!
if not block.do_process_block(xml_node):
return False
# Add it to the blocks list:
self.Blocks = self.Blocks + [block]
return True
def do_process_script(self,xml_node):
# Process the script node:
print _("Processing script...")
return True
def do_process_template(self,xml_node):
# Process the template node:
self.Template = RWizard_Template()
if not self.Template.do_process_template(xml_node):
return False
return True
# Debug printing:
def print_debug(self):
print "Wizard: " + " " + str(self.Name) + " [" + str(self.Description) + "]" + ": " + str(self.ActualMenu) + " " + str(self.ActualIcon) + " " + str(self.ActualToolbar) + " " + str(self.ActualShortcut)
for block in self.Blocks:
block.print_debug()
self.Template.print_debug()
# Run this wizard!
def run(self):
#print "Running wizard " + self.Description + " ..."
# Let each block display itself and depending on the user response continue or abort:
if len(self.Blocks) > 0:
# Check if the selection is to be used:
self.SelectedText = None
if self.SelectionAs != None:
# Then try to get it so that it can be used for the requested variable:
doc = self._rwizardengine._window.get_active_document()
if not doc:
return
# See if anything is selected:
if doc.get_has_selection():
sel_bounds = doc.get_selection_bounds()
self.SelectedText = doc.get_text(sel_bounds[0],sel_bounds[1])
i = 0
# Cycle in order to allow back from R code dialog:
while True:
finished_OK = False
user_action = +2
while i < len(self.Blocks):
user_action = self.Blocks[i].run( self, i>0, i<(len(self.Blocks)-1), i==(len(self.Blocks)-1), self.SelectionAs, self.SelectedText )
if user_action == 0:
# Abort the whole wizard...
finished_OK = False
return
elif user_action == -1:
# Go back one step:
if i > 0:
i = i-1
else:
i = 0
elif user_action == +1:
# Go forward one step or stop the process with OK:
if i < (len(self.Blocks)-1):
i = i+1
else:
finished_OK = True
break
elif user_action == +2:
# Ok & just run the code!
finished_OK = True
break
else:
print _("Unknown block-level user action ") + user_action + "!"
return
if finished_OK or (len(self.Blocks) == 0):
updated_template = self.update_template()
if updated_template != None:
# Everything's ok; beautify the R source code:
# 1. Get rid of the empty lins at the begining and end (if any):
self.beautified_template = ""
lines = updated_template.split('\n')
from_top = 0
while from_top < len(lines):
if not lines[from_top].strip():
from_top += 1
else:
break
if from_top == len(lines):
# Empty text: nothing to do!
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, _("The resulting R code is empty...") )
response = question_dialog.run()
question_dialog.destroy()
return
from_bottom = len(lines)-1
while from_bottom >= 0:
if not lines[from_bottom].strip():
from_bottom -= 1
else:
break
if from_bottom == 0:
# Empty text: nothing to do!
question_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, _("The resulting R code is empty...") )
response = question_dialog.run()
question_dialog.destroy()
return
for i in range(from_top,from_bottom+1):
self.beautified_template += lines[i] + '\n'
if user_action == +2:
# Simply run the resulting code:
self.resulting_template = self.beautified_template
response = 1301
else:
# Ask the user what they wants to do with the resulting template:
self.ui = create_UI_from_file_GtkBuilder_or_Glade(self._rwizardengine._plugin.get_data_dir()+"/WizardActions.glade",self._rwizardengine._plugin.get_data_dir()+"/WizardActions.ui")
self.dialog = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"WiardsActionsDialog")
self.source_buffer = Gtk.TextBuffer()
self.source_buffer.set_text(self.beautified_template)
self.source_view = get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"SourceView")
self.source_view.set_buffer(self.source_buffer)
self.source_view.modify_font(Pango.FontDescription('Monospace 10'))
# Event handlers:
dic = { "on_InsertCommentCheck_toggled" : self.on_InsertCommentCheck_toggled }
# "on_IndentSpin_value_changed" : self.on_IndentSpin_value_changed,
# "on_IndentComboBox_changed" : self.on_IndentComboBox_changed }
connect_signals_for_ui_GtkBuilder_or_Glade(self.ui,dic)
# Initial settings:
get_widget_from_ui_GtkBuilder_or_Glade(self.ui,"InsertCommentCheck").set_active(True)
#self.ui.get_widget("IndentComboBox").set_active(0) # Tabs initially
response = self.dialog.run()
self.resulting_template = self.source_buffer.get_text(self.source_buffer.get_start_iter(),self.source_buffer.get_end_iter(),False)
self.dialog.destroy()
# Process the response appropriately:
if response == 1299:
# Back: let the cycle resume from the last block:
i = len(self.Blocks)-1
elif response == 1300:
# Paste & run:
self.do_paste_R_code()
self.do_run_R_code()
return
elif response == 1301:
# Just run:
self.do_run_R_code()
return
elif response == 1302:
# Just paste:
self.do_paste_R_code()
return
else:
# Cancel:
return
else:
# Abort required:
return
#print self.beautified_template
def do_paste_R_code(self):
# Paste the R code at the cursor position:
doc = self._rwizardengine._window.get_active_document()
if not doc:
return
doc.insert_at_cursor(self.resulting_template)
def do_run_R_code(self):
# Run the R code through the current console (if any):
if self._rwizardengine._rctrlwindowhelper.R_widget != None:
do_send_to_R(self.resulting_template,self._rwizardengine._rctrlwindowhelper.R_widget,False)
def on_InsertCommentCheck_toggled(self,widget):
self.add_comment_to_R_code(widget.get_active())
def add_comment_to_R_code(self,insert_comment):
comment_id = "# RWizard "
if insert_comment:
# Insert the comment as the first line:
comment = comment_id + '"' + self.Description + '" on ' + datetime.datetime.now().strftime("%A, %d %B %Y @ %H:%M:%S") + "\n"
self.source_buffer.insert(self.source_buffer.get_start_iter(),comment)
return comment
else:
# Try to remove the comment (should be the first line starting with "# RWizard "):
first_line = self.source_buffer.get_text(self.source_buffer.get_iter_at_line_offset(0,0),self.source_buffer.get_iter_at_line_offset(1,0)).strip()
if comment_id == first_line[:len(comment_id)]:
# Remove the first line:
self.source_buffer.delete(self.source_buffer.get_iter_at_line_offset(0,0),self.source_buffer.get_iter_at_line_offset(1,0))
return None
#def on_IndentSpin_value_changed(self,widget):
# if self.ui.get_widget("IndentRCodeCheckButton").get_active():
# self.indent_R_code(widget.get_value_as_int(),self.ui.get_widget("IndentComboBox").get_active()==0)
#
#def on_IndentComboBox_changed(self,widget):
# if self.ui.get_widget("IndentRCodeCheckButton").get_active():
# self.indent_R_code(self.ui.get_widget("IndentSpin").get_value_as_int(),widget.get_active()==0)
#
#def indent_R_code(self,indent,use_tabs):
# self.beautified_template = ""
# indent_text = ("\t" if use_tabs else " ")*indent
# lines = self.beautified_template_original.split('\n')
# comment = self.add_comment_to_R_code(self.ui.get_widget("InsertCommentCheck").get_active())
# if comment != None:
# lines = [comment.split('\n')[0]] + lines
# for line in lines:
# self.beautified_template += indent_text + line + "\n"
# self.source_buffer.set_text(self.beautified_template)
def update_template(self):
# Use the user input the complete the script template:
#print "Filling in the script template:"
#self.Template.print_debug()
# First, create the list of variables with their values:
variables = {} # use a dictionary of variables indexed by name
for block in self.Blocks:
for variable in block.Variables:
if variable.ValueDefined:
variables[variable.Name] = variable.get_value()
# And then ask the template to update itself using these variables and return the resulting text:
updated_template = self.Template.update(variables)
# Return the updated template for further use:
return updated_template
# Class implementing an item within prefs:
class Userprefs_Item:
def __init__(self):
# Init:
self.Rwizard = None
self.Menu = None
self.Icon = None
self.Toolbar = False
self.Shortcut = None
# Debug printing:
def print_debug(self):
print "Item: " + " " + str(self.Rwizard) + " " + str(self.Menu) + " " + str(self.Icon) + " " + str(self.Toolbar) + " " + str(self.Shortcut)
# This class implements the wizards manager:
class RWizardEngine:
def __init__(self,rctrlwindowhelper):
# Init the wizards:
self._rctrlwindowhelper = rctrlwindowhelper
self._plugin = rctrlwindowhelper._plugin
self._window = rctrlwindowhelper._window
self.path = self._plugin.get_data_dir()+"/Wizards/"
# Global defaults:
self.RootMenuEntry = "Wizards"
self.ShowOnToolbar = False
self.ShortcutsActive = False
# And specific, user-defined preferences:
self.userprefs = []
# Load the user preferences for wizards:
self.load_user_prefs()
# Load the wizards:
self.wizards = self.load_wizards()
# Sort them alphabetically by menu entry:
if len(self.wizards) > 1:
self.wizards.sort(key=lambda x: x.ActualMenu)
# Debug print:
#self.print_debug()
# Try to read and load the defined wizards:
def load_wizards(self):
wizard_files = glob.glob(self.path+"*.xml")
wizards = []
for wizard_file in wizard_files:
if not wizard_file.lower().endswith("userprefs.xml"): # ignore the userprefs.xml file
wizards = wizards + [self.load_wizard(wizard_file)]
return wizards
# Try to load and create a wizard from the given file description:
def load_wizard(self,file_name):
#print "load_wizard: " + file_name
rwizard = RWizard(self)
if rwizard.load(file_name):
# Debug print:
#rwizard.print_debug()
return rwizard
else:
# Debug print:
#rwizard.print_debug()
return None
# Load the wizard user preferences:
def load_user_prefs(self):
# Open the file for reading:
try:
prefs_doc = minidom.parse( self.path + "userprefs.xml" )
except:
print _("Error opening userprefs.xml!")
return False
# Proceed through the DOM and get the relevant stuff:
root_node = prefs_doc.documentElement;
if root_node.nodeName.lower() != 'rwizardsuserprefs':
print _("Error: rwizardsuserprefs xml expected, and instead got \"") + root_node.nodeName.lower() + "\"..."
wizard_doc.unlink()
return False;
# Get the global attributes:
if root_node.hasAttribute("rootmenuentry"):
self.RootMenuEntry = root_node.getAttribute("rootmenuentry")
if root_node.hasAttribute("showontoolbar"):
self.ShowOnToolbar = root_node.getAttribute("showontoolbar").lower() == "true"
if root_node.hasAttribute("shortcutsactive"):
self.ShortcutsActive = root_node.getAttribute("shortcutsactive").lower() == "true"
# Process the prefs:
prefs_node = root_node.getElementsByTagName("prefs")
if prefs_node != None and len(prefs_node) == 1:
if not self.do_process_prefs( prefs_node[0] ):
prefs_doc.unlink()
return False
else:
print _("There must a single \"prefs\" node inside a \"rwizardsuserprefs\"")
prefs_doc.unlink()
return False
# Everything seems ok:
prefs_doc.unlink()
return True
def do_process_prefs(self,xml_node):
item_nodes = xml_node.getElementsByTagName("item")
for item_node in item_nodes:
# Proces this item:
item_info = Userprefs_Item()
if item_node.hasAttribute("rwizard"):
item_info.Rwizard = item_node.getAttribute("rwizard")
if item_node.hasAttribute("menu"):
item_info.Menu = item_node.getAttribute("menu")
if item_node.hasAttribute("icon"):
item_info.Icon = item_node.getAttribute("icon")
if item_node.hasAttribute("toolbar"):
item_info.Toolbar = item_node.getAttribute("toolbar").lower() == "true"
if item_node.hasAttribute("shortcut"):
item_info.Shortcut = item_node.getAttribute("shortcut")
# Add it to the list:
self.userprefs = self.userprefs + [item_info]
return True
# Getters for a particular rwizard, allowing the reconciliation of user defined and default preferences:
def get_menu(self,name):
for item_info in self.userprefs:
if item_info.Rwizard == name:
if item_info.Menu != None:
return item_info.Menu
else:
return self.RootMenuEntry
return self.RootMenuEntry
def get_icon(self,name):
for item_info in self.userprefs:
if item_info.Rwizard == name:
if item_info.Icon != None:
return item_info.Icon
else:
return None
return None
def get_toolbar(self,name):
for item_info in self.userprefs:
if item_info.Rwizard == name:
if item_info.Toolbar != None:
return item_info.Toolbar
else:
return self.ShowOnToolbar
return self.ShowOnToolbar
def get_shortcut(self,name):
for item_info in self.userprefs:
if item_info.Rwizard == name:
if item_info.Shortcut != None:
return item_info.Shortcut
else:
return self.ShortcutsActive
return self.ShortcutsActive
# Debug printing:
def print_debug(self):
print "RWizardEngine: " + " " + str(self.RootMenuEntry) + " " + str(self.ShowOnToolbar) + " " + str(self.ShortcutsActive)
for item_info in self.userprefs:
item_info.print_debug()
for wizard in self.wizards:
wizard.print_debug()
####################################################################################################
# #
# Code Folding #
# #
# Heavily inspired by and based on code of Kawaikunee's (http://kawaikunee.blogspot.com/) #
# 2009 folding gedit plugin (http://code.google.com/p/gedit-folding/) #
# #
# All the credit for the idea and implementation goes to Kawaikunee!!! #
# #
# I just adapted it for R's syntax, rgedit, fixed some bugs and made it look pretty :) #
# #
####################################################################################################
# This class is basically a container of the folding engine (to be applied to a given document):
class RCodeFolding:
def __init__(self,_data_dir,_plugin,activate_code_folding=True):
# Init:
self.data_dir = _data_dir
self._plugin = _plugin
self.activate_code_folding = activate_code_folding
self.create_pattern_matcher()
return
def update_code_folding(self,window,activate_code_folding):
# DEBUG:
return
# Update the status of this custom code folding engine:
if not activate_code_folding:
# Hide and undo all code fodling that might exist:
for view in window.get_views():
self.unfold_all(view.get_buffer(),view)
self.activate_code_folding = activate_code_folding
# Check is current line contains folded code (return True if it does):
def is_folded(self,doc,cur_pos_iterator):
# DEBUG:
return False
if not self.activate_code_folding:
return False
if not doc:
print _("Code folding: there must be a document for text to be (un)folded!")
return False
if not cur_pos_iterator:
return False
cur_line = cur_pos_iterator #doc.get_iter_at_mark(doc.get_insert())
# Create the folding markers for this document and view, if not already created:
tags_table = doc.get_tag_table()
self.folded_tag = tags_table.lookup('FoldedRCode')
if self.folded_tag == None:
# Clearly not folded :)
return False
elif cur_line.has_tag(self.folded_tag):
# Yes, seems so:
return True
else:
# Nope!
return False
# Is there a selection in the document (True is there is one):
def is_selection(self,doc):
# DEBUG:
return False
if not self.activate_code_folding:
return False
if not doc:
print _("Code folding: there must be a document for text to be (un)folded!")
return False
return (len(doc.get_selection_bounds()) == 2)
# Check and possibly create the folding tags:
def check_create_folding_tags(self,doc,view):
# DEBUG:
return
if not self.activate_code_folding:
return
# Create the folding markers for this document and view, if not already created:
tags_table = doc.get_tag_table()
self.folded_tag = tags_table.lookup('FoldedRCode')
if self.folded_tag == None:
# Create this tag:
self.folded_tag = doc.create_tag('FoldedRCode', foreground="green", paragraph_background="lightyellow", style=Pango.Style.ITALIC, weight=Pango.Weight.BOLD, editable=False)
# and the associated visual mark
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(self.data_dir+"/folded_code.png" , 24, 24)
# create the GtkSourceMarkAttributes:
source_mark_attr = GtkSource.MarkAttributes()
source_mark_color = Gdk.RGBA()
source_mark_color.parse("lightyellow")
source_mark_attr.set_background(source_mark_color)
source_mark_attr.set_pixbuf(pixbuf)
try:
view.set_show_line_marks(True)
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use set_show_line_markers:
view.set_show_line_markers(True)
self.folded_invisible_tag=tags_table.lookup('FoldedRCode_Invisible')
if self.folded_invisible_tag == None:
# Create this tag:
self.folded_invisible_tag = doc.create_tag('FoldedRCode_Invisible',invisible=True)
# The tooltip function for the folded code:
def folded_code_tooltip(self,mark):
return None
# Show folding icon mark next to folded code:
def show_folding_icon(self,doc,view,sel_start):
# DEBUG:
return
if not self.activate_code_folding:
return
# Supposedly, all precondtions are met, so simply create the icon and show it:
try:
block_start_mark = doc.create_source_mark(None,"FoldedRCode_Folded",sel_start)
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use create_marker:
block_start_mark = doc.create_marker(None,"FoldedRCode_Folded",sel_start)
block_start_mark.set_visible(True)
# And, respectively, delete this folding icon:
def hide_folding_icon(self,doc,view,cur_line,cur_line_end):
# DEBUG:
return
if not self.activate_code_folding:
return
# Supposedly, all precondtions are met, so simply create the icon and show it:
start_block = cur_line.copy()
start_block.backward_line()
end_block = cur_line_end.copy()
end_block.forward_line()
try:
doc.remove_source_marks(start_block,end_block,"FoldedRCode_Folded")
except AttributeError:
# So it's probably an older version of GtkSourceView: try to use delete_marker:
for marker_to_delete in doc.get_markers_in_region(start_block,end_block):
if marker_to_delete.get_marker_type() == "FoldedRCode_Folded":
doc.delete_marker(marker_to_delete)
# Unfold the core on the current line:
def unfold(self,doc,view,cur_pos_iterator):
# DEBUG:
return
if not self.activate_code_folding:
return
if not doc or not view:
print _("Code folding: there must be a document and view for text to be (un)folded!")
return
if not cur_pos_iterator:
return
# Make sure the folding tags are defined:
self.check_create_folding_tags(doc,view)
# Get the current line:
cur_line = cur_pos_iterator #doc.get_iter_at_mark(doc.get_insert())
# See if the current line is actually representing some folded code:
if cur_line.has_tag(self.folded_tag):
try:
cur_line.set_line_offset(0)
cur_line_end = cur_line.copy()
cur_line_end.forward_line()
# Hide the view, disable tooltips and consume the events:
view.hide_all()
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = False
while Gtk.events_pending():
Gtk.main_iteration()
doc.remove_tag(self.folded_tag, cur_line, cur_line_end)
cur_line.forward_to_tag_toggle(self.folded_invisible_tag)
cur_line_end.forward_to_tag_toggle(self.folded_invisible_tag)
doc.remove_tag(self.folded_invisible_tag, cur_line, cur_line_end)
#print _("Code folding: removed one fold")
# Consume the events, eisable tooltips and show the view:
while Gtk.events_pending():
Gtk.main_iteration()
view.show_all()
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = True
except:
pass
print _("Could not unfold code on the current line...")
self.hide_folding_icon(doc,view,cur_line,cur_line_end)
else:
print _("Is there a current line?...")
# Unfold all folded code in this document:
def unfold_all(self,doc,view):
# DEBUG:
return
if not doc or not view:
print _("Code folding: there must be a document and view for text to be (un)folded!")
return
# Make sure the folding tags are defined:
self.check_create_folding_tags(doc,view)
# Get the current line:
start,end=doc.get_bounds()
# Hide the view, disable tooltips and consume the events:
view.hide_all()
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = False
while Gtk.events_pending():
Gtk.main_iteration()
doc.remove_tag(self.folded_tag,start,end)
doc.remove_tag(self.folded_invisible_tag,start,end)
self.hide_folding_icon(doc,view,start,end)
# Consume the events, eisable tooltips and show the view:
while Gtk.events_pending():
Gtk.main_iteration()
view.show_all()
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = True
# Fold the current selection:
def fold_selection(self,doc,view):
# DEBUG:
return
if not self.activate_code_folding:
return
if not doc or not view:
print _("Code folding: there must be a document and view for text to be (un)folded!")
return
# Make sure the folding tags are defined:
self.check_create_folding_tags(doc,view)
# If there's a selection to fold, fold it!
if len(doc.get_selection_bounds()) == 2:
# Hide the view, disable tooltips and consume the events:
view.hide_all()
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = False
while Gtk.events_pending():
Gtk.main_iteration()
sel_start,sel_end = doc.get_selection_bounds()
sel_start_end = sel_start.copy()
sel_start.set_line_offset(0)
sel_start_end.forward_line()
sel_end.forward_line()
doc.apply_tag(self.folded_tag, sel_start, sel_start_end)
doc.remove_tag(self.folded_tag, sel_start_end, sel_end)
doc.remove_tag(self.folded_invisible_tag, sel_start_end, sel_end)
doc.apply_tag(self.folded_invisible_tag, sel_start_end, sel_end)
# and remove selection:
doc.select_range(sel_start,sel_start)
# and place the cursor at the begining of the folded code line:
doc.place_cursor(sel_start)
self.show_folding_icon(doc,view,sel_start)
# Consume the events, eisable tooltips and show the view:
while Gtk.events_pending():
Gtk.main_iteration()
view.show_all()
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = True
else:
print _("There's no selection to fold...")
# Fold the smallest containing block for the current line:
def fold_containing_block(self,doc,view,cur_pos_iterator):
# DEBUG:
return
if not self.activate_code_folding:
return
if not doc or not view:
print _("Code folding: there must be a document and view for text to be (un)folded!")
return
if not cur_pos_iterator:
return
# Make sure the folding tags are defined:
self.check_create_folding_tags(doc,view)
# Get the current line:
cur_line = cur_pos_iterator.get_line() #doc.get_iter_at_mark(doc.get_insert()).get_line()
# Find the containing block, where a "block" can be:
# 1. function(...) { BLOCK }
# 2. for(...){ BLOCK }
# 3. if(...) { BLOCK } [else {BLOCK} ]
# 4. repeat { BLOCK }
# 5. while(...) { BLOCK }
# The main difficulty is not being fooled by strings containing { or } !
# To make thigs easier, get the whole text file:
whole_text = doc.get_text(doc.get_start_iter(),doc.get_end_iter()).decode('utf-8') # textbuffer uses UTF-8
#print whole_text
# First, find all comments and strings in this document:
comments_in_doc = self._pattern_matcher_comments.finditer(whole_text)
strings_in_doc = self._pattern_matcher_strings.finditer(whole_text)
# Create a list of potential block heads:
actual_block_heads = []
# Check which of potential block heads are inside comments or strings:
for head in self._pattern_matcher_block_heads.finditer(whole_text):
# Check if it's inside a comment or a string:
is_head_ok = True
for comment in self._pattern_matcher_comments.finditer(whole_text):
if head.start() >= comment.start() and head.start() <= comment.end():
# Bingo: quit this loop:
is_head_ok = False
break
if is_head_ok:
for string in self._pattern_matcher_strings.finditer(whole_text):
if head.start() >= string.start() and head.start() <= string.end():
# Bingo: quit this loop:
is_head_ok = False
break
if is_head_ok:
# This does not seem to be in a comment or string: add it for now!
actual_block_heads.append(head)
# So, these block heads are NOT inside comments or strings!
# Now, check if they blocks and save them as a list of tuples (block_start,block_end,block_type)
# with the start and end given as offsets in the document and type as a two-letter code:
blocks_for_heads = [(None,None,None)] * len(actual_block_heads)
i = 0
for head in actual_block_heads:
# See which type this is:
block_type = head.group()[:2]
if block_type in ["if","fu","fo","wh"]:
# functions, if, for and while can have parameters as well:
# Get its parameters:
param_start = head.end()-1
param_end = self.search_matching_paranthesis(whole_text,param_start)
if param_end != None:
# Params seem to be fine: continue by finding the {} block, if any:
# Look for the {}, if there:
block_start,block_end = self.search_block(whole_text,param_end)
#print "For " + head.group() + " at " + str(doc.get_iter_at_offset(head.start()).get_line()+1) + ": (" + (str(doc.get_iter_at_offset(block_start).get_line()+1) if block_start != None else "None") + "," + (str(doc.get_iter_at_offset(block_end).get_line()+1) if block_end != None else "None") + ")"
# Save the block for this head:
blocks_for_heads[i] = (param_end,block_end,block_type)
elif block_type in ["re","el"]:
# else and repeat cannot heave parameters:
# Find the {} block, if any:
block_start,block_end = self.search_block(whole_text,head.end())
#print "For " + head.group() + " at " + str(doc.get_iter_at_offset(head.start()).get_line()+1) + ": (" + (str(doc.get_iter_at_offset(block_start).get_line()+1) if block_start != None else "None") + "," + (str(doc.get_iter_at_offset(block_end).get_line()+1) if block_end != None else "None") + ")"
# Save the block for this head:
blocks_for_heads[i] = (head.end(),block_end,block_type)
else:
# What the heck is this?
print "Unexpected match: '" + head.group() + "'..."
# Go to the next element in the list:
i = i + 1
# Delete those heads for which getting the blocks failed for various reasons or for which the block take only one line:
i = 0
while i < len(actual_block_heads):
# See if this head has a real block associated:
if blocks_for_heads[i][0] == None or blocks_for_heads[i][1] == None or doc.get_iter_at_offset(blocks_for_heads[i][0]).get_line() == doc.get_iter_at_offset(blocks_for_heads[i][1]).get_line():
# Remove it:
del blocks_for_heads[i]
del actual_block_heads[i]
else:
i += 1
## DEBUG: print the blocks list:
#print blocks_for_heads
# Now, find the blocks containing the current line following the user's preferences given in self.prefs['code_folding_block_preference']:
containing_blocks_indices = []
highest_block = (None,0) # The highest level (biggest) block as a pair (index,number_of_lines)
lowest_block = (None,0) # The lowest level (smallest) block as a pair (index,number_of_lines)
highest_function = (None,0) # The highest level (biggest) function block as a pair (index,number_of_lines)
lowest_function = (None,0) # The lowest level (smallest) function block as a pair (index,number_of_lines)
for i in range(len(blocks_for_heads)):
line1 = doc.get_iter_at_offset(blocks_for_heads[i][0]).get_line()
line2 = doc.get_iter_at_offset(blocks_for_heads[i][1]).get_line()
if cur_line >= line1 and cur_line <= line2:
# This block does contain it!
containing_blocks_indices += [i]
# See if this the highest-level (biggest) block to date:
if highest_block[1] < (line2 - line1):
# Nope: make it so!
highest_block = (i,line2 - line1)
# See if this the lowest-level (smallest) block to date:
if lowest_block[1] == 0 or lowest_block[1] > (line2 - line1):
# Nope: make it so!
lowest_block = (i,line2 - line1)
# Function blocks:
if blocks_for_heads[i][2] == "fu":
# See if this the highest-level (biggest) function block to date:
if highest_function[1] < (line2 - line1):
# Nope: make it so!
highest_function = (i,line2 - line1)
# See if this the lowest-level (smallest) function block to date:
if lowest_function[1] == 0 or lowest_function[1] > (line2 - line1):
# Nope: make it so!
lowest_function = (i,line2 - line1)
# See what type of block the user whatns folded:
block_to_fold = None
if self._plugin.prefs['code_folding_block_preference'] == 'highest_block':
if highest_block[1] > 0:
block_to_fold = highest_block
else:
info_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, _("No block contains the current line, thus nothing to fold...") )
info_dialog.run()
info_dialog.destroy()
return
elif self._plugin.prefs['code_folding_block_preference'] == 'lowest_block':
if lowest_block[1] > 0:
block_to_fold = lowest_block
else:
info_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, _("No block contains the current line, thus nothing to fold...") )
info_dialog.run()
info_dialog.destroy()
return
elif self._plugin.prefs['code_folding_block_preference'] == 'highest_function':
if highest_function[1] > 0:
block_to_fold = highest_function
elif highest_block[1] > 0:
block_to_fold = highest_block
info_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, _("No function block contains the current line, falling back to any type of block...") )
info_dialog.run()
info_dialog.destroy()
else:
info_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, _("No block contains the current line, thus nothing to fold...") )
info_dialog.run()
info_dialog.destroy()
return
elif self._plugin.prefs['code_folding_block_preference'] == 'lowest_function':
if lowest_function[1] > 0:
block_to_fold = lowest_function
elif lowest_block[1] > 0:
block_to_fold = lowest_block
info_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, _("No function block contains the current line, falling back to any type of block...") )
info_dialog.run()
info_dialog.destroy()
else:
info_dialog = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, _("No block contains the current line, thus nothing to fold...") )
info_dialog.run()
info_dialog.destroy()
return
## DEBUG:
#print "Containing blocks: " + str(containing_blocks_indices) + " and the higest-level block is " + str(highest_block[0])
# If there's a block to fold, fold it!
if block_to_fold[1] > 0:
# Do the folding:
#Gdk.event_handler_set(self.func,None)
# Hide the view, disable tooltips and consume the events:
view.hide_all()
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = False
while Gtk.events_pending():
Gtk.main_iteration()
#print "block: " + str(doc.get_iter_at_offset(blocks_for_heads[highest_block[0]][0]).get_line()+1) + " to " + str(doc.get_iter_at_offset(blocks_for_heads[highest_block[0]][1]).get_line()+1)
block_start = doc.get_iter_at_offset(blocks_for_heads[block_to_fold[0]][0])
block_end = doc.get_iter_at_offset(blocks_for_heads[block_to_fold[0]][1])
block_start.set_line_offset(0)
block_start_end = block_start.copy()
block_start_end.forward_line()
block_end.set_line_offset(0)
block_end.forward_line()
# place the cursor at the begining of the folded code line:
doc.place_cursor(block_start)
# do the actual folding:
doc.apply_tag(self.folded_tag, block_start, block_start_end)
doc.remove_tag(self.folded_tag, block_start_end, block_end)
doc.remove_tag(self.folded_invisible_tag, block_start_end, block_end)
doc.apply_tag(self.folded_invisible_tag, block_start_end, block_end)
self.show_folding_icon(doc,view,block_start)
# Consume the events, eisable tooltips and show the view:
while Gtk.events_pending():
Gtk.main_iteration()
view.show_all()
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
view.props.has_tooltip = True
else:
print _("There's no block to fold...")
#def func(self, event, user_data):
# print "Got gdk event!"
# Gtk.main_do_event(event)
# return True
def search_matching_paranthesis(self,whole_text,param_start):
# DEBUG:
return
# Serach for the matching closed paranthesis of the open one at the param_start position:
# Matching parantheses to consider: (), [] and {} and, of course, no comments # and strings "" or '':
if whole_text[param_start] !="(":
print _("'Expecting (' but instead got '") + whole_text[param_start] + "'!"
return None
# Initialize the counters for each type of thing (as a dictionary):
counters = {'(':1,'[':0,'{':0,'#':0,'"':0,"'":0}
# And start scanning:
cur_pos = param_start+1
while counters['('] > 0 and cur_pos < len(whole_text):
# See what I'm looking at:
cur_char = whole_text[cur_pos]
# and advance to the next char:
cur_pos += 1
# Process the strings first:
if cur_char == '"' and counters['#'] == 0:
# Begining or end of string?
if counters['"'] > 0:
# String's ending!
counters['"'] = 0
continue
else:
# String's begining:
counters['"'] = 1
continue
if cur_char == "'" and counters['#'] == 0:
# Begining or end of string?
if counters["'"] > 0:
# String's ending!
counters["'"] = 0
continue
else:
# String's begining:
counters["'"] = 1
continue
# See if this char is within a string:
if counters['"'] > 0 or counters["'"] > 0:
# Indeed: skip it!
continue
# Process comments now:
if cur_char == '#':
# Begining of a comment!
counters['#'] = 1
continue
if counters['#'] > 0:
# I'm within a comment:
if cur_char == '\n':
# but got a newline -> comment it over!
counters['#'] = 0
continue
# Not in a comment or string: look for matching parantheses:
if cur_char == "(":
counters['('] += 1
elif cur_char == ")":
counters['('] -= 1
if counters['('] == 0 and counters['['] == 0 and counters['{'] == 0:
# This is the happy end!!!
return cur_pos
elif cur_char == "[":
counters['['] += 1
elif cur_char == "]":
counters['['] -= 1
if counters['['] < 0:
# Oops!
print "Error matching parantheses..."
return None
elif cur_char == "{":
counters['{'] += 1
elif cur_char == "}":
counters['{'] -= 1
if counters['{'] < 0:
# Oops!
print "Error matching parantheses..."
return None
return None
def search_block(self,whole_text,param_end):
# DEBUG:
return
# Serach for the {} block following the params list (if any) and return the begining and end as a pair:
# Consume all whitespaces and comments:
block_start = None
block_end = None
cur_pos = param_end
while cur_pos < (len(whole_text)-1):
# Skip any white spaces here:
cur_pos = self.skipws(whole_text,cur_pos)
if cur_pos < (len(whole_text)-1):
if whole_text[cur_pos] == "#":
# Skip this comment as well:
cur_pos = self.skipcomment(whole_text,cur_pos)
else:
# This is where the instruction or block should be:
if whole_text[cur_pos] == "{":
# It's a block:
block_start = cur_pos
# and look for its end!
block_end = self.search_block_end(whole_text,block_start)
return (block_start,block_end)
else:
# Just an instruction, no block:
return (None,None)
return (None,None)
def skipws(self,whole_text,cur_pos):
# DEBUG:
return
# Skip white spaces:
while cur_pos < len(whole_text)-1 and whole_text[cur_pos].isspace():
cur_pos += 1
return cur_pos
def skipcomment(self,whole_text,cur_pos):
# DEBUG:
return
# Skip comments:
if cur_pos < len(whole_text)-1 and whole_text[cur_pos] == "#":
# Comment starts: eat it until the first newline:
while cur_pos < len(whole_text)-1 and not whole_text[cur_pos] in ['\n','\r']:
cur_pos += 1
return cur_pos
def search_block_end(self,whole_text,block_start):
# DEBUG:
return
# Serach for the matching closing block "}" of the open one at the block_start position:
# Matching parantheses to consider: (), [] and {} and, of course, no comments # and strings "" or '':
if whole_text[block_start] !="{":
print _("Expecting '{' but instead got '") + whole_text[param_start] + "'!"
return None
# Initialize the counters for each type of thing (as a dictionary):
counters = {'(':0,'[':0,'{':1,'#':0,'"':0,"'":0}
# And start scanning:
cur_pos = block_start+1
while counters['{'] > 0 and cur_pos < len(whole_text):
# See what I'm looking at:
cur_char = whole_text[cur_pos]
# and advance to the next char:
cur_pos += 1
# Process the strings first:
if cur_char == '"' and counters['#'] == 0:
# Begining or end of string?
if counters['"'] > 0:
## DEBUG
#print "Ending a " + '"' + " string: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
# String's ending!
counters['"'] = 0
continue
else:
## DEBUG
#print "Starting a " + '"' + " string: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
# String's begining:
counters['"'] = 1
continue
if cur_char == "'" and counters['#'] == 0:
# Begining or end of string?
if counters["'"] > 0:
## DEBUG
#print "Ending a " + "'" + " string: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
# String's ending!
counters["'"] = 0
continue
else:
## DEBUG
#print "Starting a " + "'" + " string: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
# String's begining:
counters["'"] = 1
continue
# See if this char is within a string:
if counters['"'] > 0:
## DEBUG
#print "Inside a " + '"' + " string: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
# Indeed: skip it!
continue
if counters["'"] > 0:
## DEBUG
#print "Inside a " + "'" + " string: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
# Indeed: skip it!
continue
# Process comments now:
if cur_char == '#':
## DEBUG
#print "Starting a comment: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
# Begining of a comment!
counters['#'] = 1
continue
if counters['#'] > 0:
# I'm within a comment:
if cur_char in ['\n','\r']:
## DEBUG
#print "Ending a comment: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
# but got a newline -> comment it over!
counters['#'] = 0
continue
## DEBUG
#print "Inside a comment: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
continue
# Not in a comment or string: look for matching parantheses:
## DEBUG
#print "Normal text: '" + (cur_char if not cur_char in ['\n','\r'] else "NL") + "'" + str(counters)
if cur_char == "{":
counters['{'] += 1
elif cur_char == "}":
counters['{'] -= 1
if counters['{'] == 0:
# This is the happy end!!!
return cur_pos
elif cur_char == "[":
counters['['] += 1
elif cur_char == "]":
counters['['] -= 1
if counters['['] < 0:
# Oops!
print "Error matching parantheses..."
return None
elif cur_char == "(":
counters['('] += 1
elif cur_char == ")":
counters['('] -= 1
if counters['('] < 0:
# Oops!
print "Error matching parantheses..."
return None
#print "Did not find '{' by the end of the file: " + str(counters)
return None
def create_pattern_matcher(self):
# DEBUG:
return
# Create the appropriate pattern matcher for blocks (see fold_containing_block above):
pattern_definition_block_heads = r""
# 1. function(...) { BLOCK }
pattern_definition_block_heads += r"function\s*\("
# 2. for(...){ BLOCK }
pattern_definition_block_heads += (r"|" + r"for\s*\(")
# 3. if(...) { BLOCK } [else {BLOCK} ]
pattern_definition_block_heads += (r"|" + r"if\s*\(|else")
# 4. repeat { BLOCK }
pattern_definition_block_heads += (r"|" + r"repeat")
# 5. while(...) { BLOCK }
pattern_definition_block_heads += (r"|" + r"while\s*\(")
self._pattern_matcher_block_heads = re.compile(pattern_definition_block_heads)
# The pattern matchers for strings and comments:
pattern_definition_comments = r"#.*"
pattern_definition_strings = r"'.*'" + r"|" + r'".*"'
self._pattern_matcher_comments = re.compile(pattern_definition_comments)
self._pattern_matcher_strings = re.compile(pattern_definition_strings)
# Ask the code folding engine to provide some tooltip for this position (if any) and return (do_tooltip,tooltip_text):
def get_tooltip(self, view, doc, position_iter ):
# DEBUG:
return
# See if this iterator is on a folded code line:
# Make sure the folding tags are defined:
self.check_create_folding_tags(doc,view)
# See if the current line is actually representing some folded code:
folded_text= self.get_folded_text(doc,view,position_iter)
if folded_text != None:
# Good, extract the first two and the last two lines:
first_lines_no = 3
last_lines_no = 3
tooltip_text = None
text_lines = folded_text.splitlines() # don't keep line breaks in there
text_lines = [s for s in text_lines if s.strip()] # remove empty lines
if len(text_lines) <= (first_lines_no + last_lines_no):
# Display the whole text:
tooltip_text = '> ' + '\n> '.join(text_lines)
else:
# Use only the few first and last lines:
tooltip_text = '> ' + '\n> '.join(text_lines[:first_lines_no]) + "\n..........\n> " + '\n> '.join(text_lines[-last_lines_no:])
return (True,tooltip_text)
return (False,None)
def inspect_folded_code(self,doc,view,cur_pos_iterator):
# DEBUG:
return
# Display the folded text here:
if not self.activate_code_folding:
return
if not doc or not view:
print _("Code folding: there must be a document and view for text to be (un)folded!")
return
if not cur_pos_iterator:
return
# Make sure the folding tags are defined:
self.check_create_folding_tags(doc,view)
# Get the current line:
cur_line = cur_pos_iterator #doc.get_iter_at_mark(doc.get_insert())
# Get folded text at the current line (if any):
folded_text= self.get_folded_text(doc,view,cur_line)
if folded_text != None:
# Display it!
# Create a top-level dialog with one button (Close) and a scrollable TextView:
dialog = Gtk.Dialog(_("Inspecting folded code..."),
None,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT)
# The info lable at the top:
info_label = Gtk.Label(label=_("Folded code at line ") + str(cur_line.get_line()+1) + _(":"))
info_label.show()
dialog.vbox.pack_start(info_label,expand=False,fill=False)
# The TextView and associated TextBuffer:
code_view = Gtk.TextView(None)
code_text = code_view.get_buffer()
code_text.set_text(folded_text)
code_view.set_editable(False)
code_view.show()
# Scroll support:
scrolled_window = Gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
dialog.vbox.pack_start(scrolled_window, True, True, 0)
scrolled_window.show()
scrolled_window.add_with_viewport(code_view)
# The unfold code button:
unfold_button = dialog.add_button(_("Unfold"), 1 ) # Unfold code
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
unfold_button.set_tooltip_text(_("Unfold the code and close"))
# The close button:
close_button = dialog.add_button(_("Close"), 0 ) # Close
if use_GtkBuilder_or_Glade():
# Gtk supports tooltips:
close_button.set_tooltip_text(_("Close without unfolding the code"))
# The initial dialog size:
dialog.resize( 600, 400 )
# Collect the user's response:
response = dialog.run()
if response == 1:
# Try to unfold the code as told:
#doc.place_cursor(cur_line) # make sure the current line is the current one!
self.unfold(doc,view,cur_pos_iterator)
# Close the dialog:
dialog.destroy()
def get_folded_text(self, doc, view, folded_start_line):
# DEBUG:
return
# Get the text in the folded section begning here:
# Make sure the folding tags are defined:
self.check_create_folding_tags(doc,view)
# See if the current line is actually representing some folded code:
if folded_start_line.has_tag(self.folded_tag):
# Good: now, try ot get the actually folded text:
folded_start_line.set_line_offset(0)
folded_end_line = folded_start_line.copy()
folded_end_line.forward_lines(1)
folded_end_line.forward_to_tag_toggle(self.folded_invisible_tag)
folded_text = doc.get_text(folded_start_line,folded_end_line)
return folded_text
return None
|