[16bb17]: pype.py Maximize Restore History

Download this file

pype.py    6243 lines (5417 with data), 243.8 kB

   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
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
#!/usr/bin/env python
'''
This software is licensed under the GPL (GNU General Public License) version 2
as it appears here: http://www.gnu.org/copyleft/gpl.html
It is also included with this archive as `gpl.txt <gpl.txt>`_.
'''
#------------ User-changable settings are available in the menus -------------
from __version__ import VERSION_, VERSION
#------------------------ Startup/restart information ------------------------
import sys, os
if sys.platform == 'linux2' and 'DISPLAY' not in os.environ:
raise SystemError('DISPLAY not set when importing or running pype')
from optparse import OptionParser
_options = OptionParser()
_options.add_option('--version', dest='version', default='2.8',
help='This sets the minimal version of wxPython you would like to use')
_options.add_option('--ansi', dest='use_ansi', action='store_true', default=None,
help='This tells PyPE to use an ansi version of wxPython')
_options.add_option('--unicode', dest='use_unicode', action='store_true', default=None,
help='This tells PyPE to use a unicode version of wxPython')
_options.add_option('--debug', dest='debug', action='store_true', default=False,
help='Enable the debugger shell within PyPE')
_options.add_option('--standalone', dest='standalone', action='store_true', default=False,
help='Uses the local .pype for preferences')
_options.add_option('--fontsize', dest='fontsize', action='store', type=int, default=None,
help='Sets the base font size')
_options.add_option('--port', dest='port', action='store', type=int, default=None,
help='Sets the port on which to listen/check for the other PyPE instance')
_options.add_option('--font', dest='font', default=None,
help='Sets the font for PyPE to use instead of it\'s default font')
_options.add_option('--use_old_parser', '--use-old-parser', dest='use_old', action='store_true', default=False,
help='Use the older parser instead of the Python 2.6 and later AST parser')
_options.add_option('--last', dest='last', action='store_true', default=False,
help='Load the documents that were open when PyPE last closed')
_options, _args = _options.parse_args()
if not hasattr(sys, 'frozen'):
v = _options.version
import wxversion
if _options.use_ansi and _options.use_unicode:
print 'You can only enable ansi OR unicode, not both'
raise SystemExit
if _options.use_ansi or _options.use_unicode:
v = v.split('-')[0]
if _options.use_ansi:
v += '-ansi'
if _options.use_unicode:
v += '-unicode'
wxversion.ensureMinimal(v, optionsRequired=('-' in v))
DEBUG = _options.debug
_standalone = _options.standalone
USE_THREAD = True
PRINTMACROS = 0
if _options.fontsize:
FONTSIZE = _options.fontsize
if _options.port:
PORTNUM = _options.port
if _options.font:
FONT = _options.font.replace('_', ' ').replace('-', ' ')
USE_NEW = not _options.use_old
def _restart(orig_path=os.getcwd(), orig_sysargv=sys.argv[:]):
os.chdir(orig_path)
args = [sys.executable] + orig_sysargv
if len(spawnargs) == 1:
_ = args.pop(0)
os.execvp(args[0], args + ['--last'])
#-------------- Create reference to this module in __builtins__ --------------
if isinstance(__builtins__, dict):
__builtins__['_pype'] = sys.modules[__name__]
__builtins__['USE_NEW'] = USE_NEW
else:
__builtins__._pype = sys.modules[__name__]
__builtins__.USE_NEW = USE_NEW
#------------------------------ System Imports -------------------------------
import bisect
import collections
import cStringIO
import fnmatch
import keyword
import imp
import md5
import pprint
import Queue
import re
import string
import textwrap
import threading
import time
import traceback
#-------------------------------- wx imports ---------------------------------
import wx
if wx.VERSION[:4] == (2, 6, 3, 3) and not wx.USE_UNICODE:
raise SystemError('''
This version of wxPython (2.6.3.3 ansi) has known issues with pasting. If you
must use wxPython 2.6.3.3, please use wxPython 2.6.3.3 unicode and pass the
--unicode command line option.
'''.replace(' ', ''))
HAS_NATIVE_ANNOTATIONS = wx.version() >= '2.9.'
import wx.gizmos
import wx.lib.newevent
from wx import aui
_style = aui.AUI_NB_SCROLL_BUTTONS|aui.AUI_NB_TOP
from wx import stc
wxstc = stc
from wx.lib.dialogs import ScrolledMessageDialog
if DEBUG:
try:
from wx.py import crust
except:
print "Debugging console not available, try to source version of PyPE"
current_path = os.getcwd()
EFFECTUAL_NORMCASE = os.path.normcase('AbCdEf') == 'abcdef'
UNICODE = wx.USE_UNICODE
#--------------------- configuration and plugins imports ---------------------
from configuration import (
REM_SWAP, collapse_style, eol, extns, fmt_Rmode, fmt_mode, getData,
homedir, nosocket, runpath, spawnargs, str_unrepr, stylefile,
unrepr, validate, wildcard
)
MAX_SAVE_STATE_DOC_SIZE = 0x400000 #2**22 bytes, a little over a 4 megs
MAX_SAVE_STATE_LINE_COUNT = 20000 #anything more than 4 megs or 20k lines
#change the standard font size
import StyleSetter
if 'FONTSIZE' in globals() or 'FONT' in globals():
StyleSetter.fs = globals().get('FONTSIZE', StyleSetter.fs)
StyleSetter.cn = globals().get('FONT', StyleSetter.cn)
StyleSetter.update_faces()
from plugins import browser
from plugins import codetree
from plugins import documents
from plugins import filehistory
from plugins import filtertable
from plugins import findbar
from plugins import findinfiles
from plugins import help
from plugins import interpreter
from plugins import keydialog
from plugins import lineabstraction
from plugins import logger
from plugins import lru
from plugins import macro
from plugins import methodhelper
from plugins import parsers
from plugins import pubsub
from plugins import scheduler
from plugins import shell
from plugins import single_instance
if 'PORTNUM' in globals():
single_instance.port = PORTNUM
from plugins import spellcheck
from plugins import textrepr
from plugins import todo
from plugins import triggerdialog
from plugins import window_management
from plugins.window_management import docstate, _choicebook
from plugins import workspace
#---------------------------- Event Declarations -----------------------------
class cancelled(Exception):
pass
class pass_keyboard(cancelled):
pass
def isdirty(win):
if not isinstance(win, PythonSTC):
return False
if win.dirty:
return True
fn = win.root.getAlmostAbsolute(win.filename, win.dirname)
dirty = 0
if win.mod != None:
try:
mod = os.stat(fn)[8]
dirty += mod != win.mod
except:
dirty += bool(win.dirname.strip())
if dirty:
win.MakeDirty()
return bool(dirty)
for i in [logger, findbar, lru, filehistory, browser, workspace, todo,
findinfiles, shell, textrepr, spellcheck, keydialog]:
i.cancelled = cancelled
i.isdirty = isdirty
#some definitions
if 1:
STRINGPRINTABLE = dict.fromkeys(map(ord, string.printable))
IDR = wx.NewId()
DDR = wx.NewId()
#keypresses
if 1:
keyMap = {}
for name in dir(wx):
if name.startswith('WXK_'):
key = getattr(wx, name)
keyMap[key] = name[4:]
_keys = dict.fromkeys(keyMap.iteritems())
for i in ["SHIFT", "ALT", "CONTROL", "MENU"]:
key = getattr(wx, "WXK_"+i)
keyMap[key] = ''
del key
def _decode_key(keycode):
if keycode >= 256:
return unichr(keycode)
else: #keycode < 256:
return chr(keycode)
def GetKeyCode(evt):
if 'unicode' in wx.PlatformInfo:
return evt.GetUnicodeKey()
return evt.GetKeyCode()
if isinstance(__builtins__, dict):
__builtins__['GetKeyCode'] = GetKeyCode
else:
__builtins__.GetKeyCode = GetKeyCode
def GetKeyPress(evt):
keycode = evt.GetKeyCode()
keyname = keyMap.get(keycode, None)
if keyname is None:
if "unicode" in wx.PlatformInfo:
keycode = evt.GetUnicodeKey()
if keycode <= 127:
keycode = evt.GetKeyCode()
keyname = unichr(evt.GetUnicodeKey())
elif keycode < 256:
if keycode == 0:
keyname = "NUL"
elif keycode < 27:
keyname = chr(ord('A') + keycode-1)
else:
keyname = chr(keycode)
else:
keyname = "(%s)unknown" % keycode
modifiers = ""
for mod, ch in [(evt.ControlDown(), 'Ctrl+'),
(evt.AltDown(), 'Alt+'),
(evt.ShiftDown(), 'Shift+'),
(evt.MetaDown(), 'Meta+')]:
if mod:
modifiers += ch
return modifiers + keyname
#menu preferences
if 1:
MENULIST = []
MENUPREF = {}
OLD_MENUPREF= {}
HOTKEY_TO_ID = {}
def _spl(n):
return (n.split('\t', 1) + [''])[:2]
def recmenu(menu, id):
## print menu.__class__, wx.MenuItem, wx.Menu,
if isinstance(menu, wx.MenuBar):
for i in xrange(menu.GetMenuCount()):
r = menu.GetMenu(i)
if r.FindItemById(id):
return "%s->%s"%(menu.GetLabelTop(i), recmenu(r, id))
elif isinstance(menu, wx.Menu):
ITEMS = menu.GetMenuItems()
for i in ITEMS:
a = recmenu(i, id)
if a:
return a
return ''
elif isinstance(menu, wx.MenuItem):
sm = menu.GetSubMenu()
if sm:
a = recmenu(sm, id)
if a:
return '%s->%s'%(menu.GetLabel(), a)
return ''
elif menu.GetId() == id:
return menu.GetLabel()
else:
return ''
raise Exception("Tried adding a non-menu to a menu? Contact the author.")
def GETACC(X):
if len(X) == 3:
return X
return X[0], X[1], X[1]
def menuAdd(root, menu, name, desc, funct, id, kind=wx.ITEM_NORMAL):
a = wx.MenuItem(menu, id, 'TEMPORARYNAME', desc, kind)
menu.AppendItem(a)
wx.EVT_MENU(root, id, funct)
ns, oacc = _spl(name)
hier = recmenu(menuBar, id)[:-13] + ns
if hier in MENUPREF:
name, acc, acc2 = GETACC(MENUPREF[hier])
else:
if hier in OLD_MENUPREF:
name, acc, acc2 = MENUPREF[hier] = GETACC(OLD_MENUPREF[hier])
else:
name, acc, acc2 = MENUPREF[hier] = GETACC((ns, oacc))
MENULIST.append((hier, name, oacc, acc, kind in [wx.ITEM_NORMAL, wx.ITEM_CHECK], acc2))
## if type(acc) != type(acc2):
## acc2 = acc2.decode('latin-1')
## if acc != acc2:
## print "mismatched hotkey: %r %r"%(acc, acc2)
if acc or acc2:
HOTKEY_TO_ID[acc2] = id
menuBar.SetLabel(id, '%s\t%s'%(name, acc))
menuBar.SetHelpString(id, desc)
def menuAddM(parent, menu, name, help=''):
if isinstance(parent, wx.Menu):
id = wx.NewId()
parent.AppendMenu(id, "TEMPORARYNAME", menu, help)
hier = recmenu(menuBar, id) + name
name, toss, toss2 = MENUPREF[hier] = GETACC(MENUPREF.get(hier, (name, '')))
menuBar.SetLabel(id, name)
menuBar.SetHelpString(id, help)
else:
hier = name
name, toss, toss2 = MENUPREF[hier] = GETACC(MENUPREF.get(hier, (name, '')))
parent.Append(menu, name)
MENULIST.append((hier, name, '', toss, 0, toss2))
def getIcon():
data = getData()
stream = cStringIO.StringIO(data)
image = wx.ImageFromStream(stream)
bitmap = wx.BitmapFromImage(image)
icon = wx.EmptyIcon()
icon.CopyFromBitmap(bitmap)
return icon
NEWDOCUMENT = 0L
#document styling events
if 1:
#style ids
# _S 0 _DS 1 2 3 _DD 4 _DD2 5 6
ASSOC = [(wx.NewId(), wx.NewId(), 'pyrex', stc.STC_LEX_PYTHON, wx.NewId(), wx.NewId(), "Pyrex"),
#made Python second to override the lexer2lang option
(wx.NewId(), wx.NewId(), 'python', stc.STC_LEX_PYTHON, wx.NewId(), wx.NewId(), "Python"),
(wx.NewId(), wx.NewId(), 'html', stc.STC_LEX_HTML, wx.NewId(), wx.NewId(), "HTML"),
(wx.NewId(), wx.NewId(), 'xml', stc.STC_LEX_XML, wx.NewId(), wx.NewId(), "XML"),
(wx.NewId(), wx.NewId(), 'cpp', stc.STC_LEX_CPP, wx.NewId(), wx.NewId(), "C/C++"),
(wx.NewId(), wx.NewId(), 'text', stc.STC_LEX_NULL, wx.NewId(), wx.NewId(), "Text"),
(wx.NewId(), wx.NewId(), 'tex', stc.STC_LEX_LATEX, wx.NewId(), wx.NewId(), "TeX/LaTeX")]
SITO = [i[4] for i in ASSOC]
SITO2 = [i[5] for i in ASSOC]
## PY_S, PYX_S, HT_S, XM_S, CC_S, TX_S, TEX_S = [i[0] for i in ASSOC]
## PY_DS, PYX_DS, HT_DS, XM_DS, CC_DS, TX_DS, TEX_DS = [i[1] for i in ASSOC]
## PY_DD, PYX_DD, HT_DD, XM_DD, CC_DD, TX_DD, TEX_DD = SITO
## PY_DD2, PYX_DD2, HT_DD2, XM_DD2, CC_DD2, TX_DD2, TEX_DD2 = SITO2
lexers = dict([(i[0],i[2]) for i in ASSOC])
lexers2 = dict([(i[2],i[0]) for i in ASSOC])
lexers.update(dict([(i[1],i[2]) for i in ASSOC]))
lexers3 = dict([(i[2],i[1]) for i in ASSOC])
lexer2lang = dict([(i[3],i[2]) for i in ASSOC])
SOURCE_ID_TO_OPTIONS = dict([(i[4], (i[2], i[6])) for i in ASSOC])
SOURCE_ID_TO_OPTIONS2 = dict([(i[5], (i[2], i[6])) for i in ASSOC])
ASSOC.insert(1, ASSOC.pop(0))
#checkbox ids
if 1:
MIDDLE_CL = wx.NewId()
AUTO = wx.NewId()
FETCH_M = wx.NewId()
AC_KEYWORDS = wx.NewId()
AC_LENGTH = wx.NewId()
ANNOTATIONS_VISIBLE = wx.NewId()
NUM = wx.NewId()
MARGIN = wx.NewId()
USETABS = wx.NewId()
INDENTGUIDE = wx.NewId()
WRAPL = wx.NewId()
SLOPPY = wx.NewId()
SMARTPASTE = wx.NewId()
SAVE_CURSOR = wx.NewId()
HIGHLIGHT_LINE = wx.NewId()
IMAGE_BUTTONS = wx.NewId()
S_WHITE = wx.NewId()
S_LEND = wx.NewId()
DND_ID = wx.NewId()
DB_ID = wx.NewId()
IT_ID = wx.NewId()
METH_C_ID = wx.NewId()
LB_ID = wx.NewId()
WIDE_ID = wx.NewId()
TALL_ID = wx.NewId()
SINGLE_ID = wx.NewId()
USEBOM_ID = wx.NewId()
ONE_TAB = wx.NewId()
TD_ID = wx.NewId()
STRICT_TODO_ID = wx.NewId()
FINDBAR_BELOW_EDITOR = wx.NewId()
NO_FINDBAR_HISTORY = wx.NewId()
CLEAR_FINDBAR_HISTORY = wx.NewId()
ZI = wx.NewId()
SHOW_RECENT = wx.NewId()
SHOW_SEARCH = wx.NewId()
SHOW_MIST = wx.NewId()
TRIGGER = wx.NewId()
REC_MACRO = wx.NewId()
#toolbar ids
TB_MAPPING = {
wx.NewId(): (0, 'Hide', "Don't show the toolbar (requires restart)"),
wx.NewId(): (1, 'Top', "Show the toolbar accross the top horizontally (requires restart)"),
wx.NewId(): (2, 'Left', "Show the toolbar along the left side vertically (requires restart)")
}
TB_RMAPPING = dict([(j[0], (j[0], i, j[1], j[2])) for i,j in TB_MAPPING.iteritems()])
#line ending ids
LE_MAPPING = {
wx.NewId():(stc.STC_EOL_CRLF, 0, "CRLF (windows)", "Change the line endings for the current document to CRLF/Windows line endings"),
wx.NewId():(stc.STC_EOL_LF, 1, "LF (*nix)", "Change the line endings for the current document to LF/*nix line endings"),
wx.NewId():(stc.STC_EOL_CR, 2, "CR (mac)", "Change the line endings for the current document to CR/Macintosh line endings")
}
LE_RMAPPING = dict([(j[0], (j[1], i, j[2], j[3])) for i,j in LE_MAPPING.iteritems()])
#long line indicator ids
LL_MAPPING = {
wx.NewId():(stc.STC_EDGE_BACKGROUND, 0, "Background", "Long lines will have a different background color beyond the column limit"),
wx.NewId():(stc.STC_EDGE_LINE, 1, "Line", "Long lines will have a vertical line at the column limit"),
wx.NewId():(stc.STC_EDGE_NONE, 2, "None", "Show no long line indicator")
}
LL_RMAPPING = dict([(j[0],(j[1], i, j[2], j[3])) for i,j in LL_MAPPING.iteritems()])
#cursor behavior ids
CARET_ID_TO_OPTIONS = {
wx.NewId() : (0, stc.STC_CARET_EVEN|stc.STC_CARET_SLOP|stc.STC_CARET_STRICT, 1, "Margin Respecting", "Caret is at least M lines from the top and bottom, N*M pixels from the right and left"),
wx.NewId() : (1, stc.STC_CARET_EVEN|stc.STC_CARET_STRICT, 4, "Centered", "Caret is centered on the display, if possible"),
wx.NewId() : (2, stc.STC_CARET_STRICT, 3, "Top Attached", "Caret is always on the top line, if possible"),
wx.NewId() : (3, stc.STC_CARET_SLOP|stc.STC_CARET_STRICT, 2, "Margin Attached", "Caret is always M lines from the top, and N*M pixels from the right, if possible"),
wx.NewId() : (4, stc.STC_CARET_EVEN, 0, "PyPE Classic", "Caret is at least 1 line from the top and bottom, 10 pixels from the right and left"),
}
CARET_OPTION_TO_ID = dict([(j[0], (i, j[1])) for i,j in CARET_ID_TO_OPTIONS.iteritems()])
#caret width option
CARET_W_OPTION_TO_W = dict([(wx.NewId(), i) for i in (1,2,3)])
CARET_W_WIDTH_TO_O = dict([(j,i) for i,j in CARET_W_OPTION_TO_W.iteritems()])
#title display ids
TITLE_ID_TO_OPTIONS = {
wx.NewId() : (0, "%(pype)s", "No file information"),
wx.NewId() : (1, "%(pype)s - %(fn)s", "File name after title"),
wx.NewId() : (2, "%(fn)s - %(pype)s", "File name before title"),
wx.NewId() : (3, "%(pype)s - %(fn)s - [%(long)s]", "File and full path after title"),
wx.NewId() : (4, "%(fn)s - [%(long)s] - %(pype)s", "File and full path before title"),
}
TITLE_OPTION_TO_ID = dict([(j[0], (i, j[1], j[2])) for i,j in TITLE_ID_TO_OPTIONS.iteritems()])
#for determining what to display in the Documents tab.
DOCUMENT_LIST_OPTIONS = {
wx.NewId() : (1, "Filename"),
wx.NewId() : (3, "Filename, Path"),
wx.NewId() : (2, "Path"),
wx.NewId() : (0, "Path, Filename")
}
DOCUMENT_LIST_OPTION_TO_ID = dict([(j[0], i) for i,j in DOCUMENT_LIST_OPTIONS.items()])
DOCUMENT_LIST_OPTIONS2 = {
wx.NewId() : (1, "Filename"),
wx.NewId() : (3, "Filename, Path"),
wx.NewId() : (2, "Path"),
wx.NewId() : (0, "Path, Filename")
}
DOCUMENT_LIST_OPTION_TO_ID2 = dict([(j[0], i) for i,j in DOCUMENT_LIST_OPTIONS2.items()])
#for determining what to do when double-clicking on a macro.
MACRO_CLICK_OPTIONS = {
wx.NewId() : (0, "do nothing"),
wx.NewId() : (1, "open for editing"),
wx.NewId() : (2, "run macro")
}
MACRO_CLICK_TO_ID = dict([(j[0], i) for i,j in MACRO_CLICK_OPTIONS.iteritems()])
PYTHON_INTERPRETER_CHOICES = []
#for determining what kind of indicator to show in shell output.
SHELL_OUTPUT_OPTIONS = {
wx.NewId(): (0, "no indicator", stc.STC_INDIC_HIDDEN),
wx.NewId(): (1, "plain underline", stc.STC_INDIC_PLAIN),
wx.NewId(): (2, "squiggle underline", stc.STC_INDIC_SQUIGGLE),
wx.NewId(): (3, "TT underline", stc.STC_INDIC_TT),
wx.NewId(): (4, "box outline", stc.STC_INDIC_BOX)
}
try:
SHELL_OUTPUT_OPTIONS[wx.NewId()] = (5, "round box outline", stc.STC_INDIC_ROUNDBOX)
except:
pass
SHELL_NUM_TO_ID = dict([(j,i) for i,(j,k,l) in SHELL_OUTPUT_OPTIONS.iteritems()])
SHELL_NUM_TO_INDIC = dict([(j,l) for i,(j,k,l) in SHELL_OUTPUT_OPTIONS.iteritems()])
#for determining how often to check syntax
SYNTAX_CHECK_DELAY_L = [
(wx.NewId(), -1, "never"),
(wx.NewId(), 0, "at most every 5 seconds"),
(wx.NewId(), 1, "at most every 20 seconds"),
(wx.NewId(), 2, "at most every 2 minutes")
]
SYNTAX_CHECK_DELAY_NUM_TO_ID = dict([(j,i) for i,j,k in SYNTAX_CHECK_DELAY_L])
SYNTAX_CHECK_DELAY_ID_TO_NUM = dict([(i,j) for i,j,k in SYNTAX_CHECK_DELAY_L])
#for determining how often to "refresh" automatically
REFRESH_DELAY_L = [(wx.NewId(), j, k) for i,j,k in SYNTAX_CHECK_DELAY_L]
REFRESH_DELAY_NUM_TO_ID = dict([(j,i) for i,j,k in REFRESH_DELAY_L])
REFRESH_DELAY_ID_TO_NUM = dict([(i,j) for i,j,k in REFRESH_DELAY_L])
_MULT = (5, 20, 120, 5)
_MULT2 = (5, 5, 5, 5)
#for turning tools on or off
TOOLS_ENABLE_L = [
(wx.NewId(), 'Name', 'source tree ordered by name', 'leftt', 'tree1'),
(wx.NewId(), 'Line', 'source tree ordered by line number', 'rightt', 'tree2'),
(wx.NewId(), 'Filter', 'filterable definition list', 'filterl', 'filter'),
(wx.NewId(), 'Todo', 'todo listing', 'todot', 'todo'),
## (wx.NewId(), 'Tags', 'tagged definition filter', 'taglist', 'sourcetags'),
## (wx.NewId(), 'TagM', 'definition tag manager', 'tagmanage', 'tagger'),
(wx.NewId(), 'Global Filter', 'global filterable definition list', 'ignore', 'ignore'),
]
TOOLS_ENABLE = dict([(j[0], i) for i,j in enumerate(TOOLS_ENABLE_L)])
TOOLS_ENABLE_LKP = dict([(i[3], i[4]) for i in TOOLS_ENABLE_L])
#bookmark support
BOOKMARKNUMBER = 1
BOOKMARKSYMBOL = stc.STC_MARK_CIRCLE
NOTIFICATIONNUMBER = 2
NOTIFICATIONSYMBOL = stc.STC_MARK_SHORTARROW
BOOKMARKMASK = 6
NOTIFICATIONMASK = 4
#unicode BOM stuff
if 1:
BOM = [('+/v8-', 'utf-7'),
('\xef\xbb\xbf', 'utf-8'),
('\xfe\xff', 'utf-16-be'),
('\xff\xfe', 'utf-16-le'),
('', 'ascii'),
('', 'other')]
try:
_ = u'\ufeff'.encode('utf-32')
except:
pass
else:
BOM.insert(2, ('\xff\xfe\0\0', 'utf-32-le'))
BOM.insert(3, ('\0\0\xfe\xff', 'utf-32-be'))
ADDBOM = {}
ENCODINGS = {}
for i,j in BOM:
ADDBOM[j] = i
ENCODINGS[j] = wx.NewId()
del i
del j
#font stuff
if 1:
cn = 'Courier New'
if wx.Platform == '__WXMSW__':
faces = {'times': cn, 'mono' : cn, 'helv' : cn, 'other': cn,
'size' : 10, 'size2': 9}
else:
faces = {'times': 'Courier', 'mono' : 'Courier',
'helv' : 'Courier', 'other': 'Courier', 'size' : 10,
'size2': 10 }
del cn
#SashWindow stuff
if 1:
def makeSubWindow(parent, id, size, orientation, alignment, sash):
win = wx.SashLayoutWindow(
parent, id, wx.DefaultPosition, size,
wx.NO_BORDER|wx.SW_3D
)
win.SetDefaultSize(size)
win.SetOrientation(orientation)
win.SetAlignment(alignment)
## win.SetBackgroundColour(wx.Colour(127, 0, 0))
win.SetSashVisible(sash, True)
## win.SetMinimumSizeX(30)
return win
#subwindow ids
ID_WINDOW_BOTTOM = wx.NewId()
ID_WINDOW_RIGHT = wx.NewId()
#subwindow constants
SMALL = 10
BIG = 10000
DB_LOC = {0:(wx.LAYOUT_LEFT, wx.SASH_RIGHT),
1:(wx.LAYOUT_RIGHT, wx.SASH_LEFT)}
LB_LOC = {0:(wx.LAYOUT_TOP, wx.SASH_BOTTOM),
1:(wx.LAYOUT_BOTTOM, wx.SASH_TOP)}
#findbar ids
if 1:
pypeID_DELETE = wx.NewId()
pypeID_FINDBAR = wx.NewId()
pypeID_REPLACEBAR = wx.NewId()
pypeID_TOGGLE_BOOKMARK = wx.NewId()
pypeID_NEXT_BOOKMARK = wx.NewId()
pypeID_PRIOR_BOOKMARK = wx.NewId()
#extension to image map
EXT_TO_IMG = {'python':1, 'pyrex':1}
def GDI(name):
if USE_DOC_ICONS:
ext = name.split('.')[-1].lower()
if ext in ('spt', 'tmpl'):
return 0
return EXT_TO_IMG.get(extns.get(ext, 0), 0)
return -1
#
def get_filetype(fn):
return extns.get(fn.split('.')[-1].lower(), 'python')
fake_primary_clipboard = ''
def GetClipboardText(use_primary=False):
success = False
if not sys.platform.startswith('win'):
wx.TheClipboard.UsePrimarySelection(use_primary)
elif use_primary:
return fake_primary_clipboard
do = wx.TextDataObject()
if wx.TheClipboard.Open():
success = wx.TheClipboard.GetData(do)
wx.TheClipboard.Close()
if success:
return do.GetText()
return None
def SetClipboardText(txt, use_primary=False):
if not sys.platform.startswith('win'):
wx.TheClipboard.UsePrimarySelection(use_primary)
elif use_primary:
global fake_primary_clipboard
fake_primary_clipboard = txt
return True
do = wx.TextDataObject()
do.SetText(txt)
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(do)
wx.TheClipboard.Close()
return True
return False
RESET = {'cursor_posn':0,
'BM':[],
'FOLD':[]}
#threaded parser
if 1:
parse_queue = Queue.Queue()
_cheetah_re = re.compile('#(extends|block|end if|end block|end def)')
DoneParsing, EVT_DONE_PARSING = wx.lib.newevent.NewEvent()
def _parse(lang, source, le, which, x, slowparse=0):
source = source.replace('\r\n', '\n').replace('\r', '\n')
le = '\n'
if lang in ('python', 'pyrex'):
if _cheetah_re.search(source):
return parsers.cheetah_parser(source, le, which, x)
elif slowparse:
try:
return parsers.fast_parser(source, le, which, x)
except:
traceback.print_exc()
pass
return parsers.faster_parser(source, le, which, x)
elif lang == 'tex':
return parsers.latex_parser(source, le, which, x)
elif lang == 'cpp':
return parsers.c_parser(source, le, which, x)
elif lang in ('xml', 'html'):
return parsers.ml_parser(source, le, which, x)
else:
return [], [], {}, []
def parse(lang, source, le, which, x, slowparse=0):
r = _parse(lang, source, le, which, x, slowparse)
r2 = [] #parsers._get_tags(r[0], r[-1])
return r + (r2,)
def parse_thread(frame, startthread=1):
if startthread:
a = threading.Thread(target=parse_thread, args=(frame,0))
a.start()
return
null = lambda:None
while 1:
x = parse_queue.get()
if not x:
break
source, stc, lang = x
t = time.time()
tpl = parse(lang, source, '\n', 3, null, 1)
t = time.time()-t
try:
wx.PostEvent(frame, DoneParsing(stc=stc, tpl=tpl, delta=t))
except:
# the main frame has closed
break
file_mods_to_check = Queue.Queue()
def check_files(frame, startthread=1):
if startthread:
x = threading.Thread(target=check_files, args=(frame, 0))
x.start()
return
lastcheck = None
while 1:
request_time, files_to_check = file_mods_to_check.get()
while not file_mods_to_check.empty():
# if the current list isn't the last list, get a more
# up-to-date list
request_time, files_to_check = file_mods_to_check.get()
if files_to_check is None:
break
curcheck = time.time()
if not lastcheck:
lastcheck = time.time()-61
if request_time and curcheck - lastcheck < 60:
# don't re-check more than once a minute
continue
for f in files_to_check:
fn = f[0]
try:
f.append(os.stat(fn)[8])
except:
f.append(None)
f.append(None)
else:
try:
f.append(md5.new(open(fn, 'rb').read()).digest())
except:
f[-1:] = [None, None]
lastcheck = curcheck
try:
if request_time and time.time()-request_time > 30:
# it took us more than 30 seconds to check...
# the check probably isn't valid.
# we'll wait for another check request
continue
wx.CallAfter(frame.CheckedDocMods, files_to_check)
except:
# the main frame has closed
break
sys_excepthook = sys.excepthook
def my_excepthook(typ, inst, trace):
if typ is cancelled or typ is pass_keyboard:
return
return sys_excepthook(typ, inst, trace)
sys.excepthook = my_excepthook
def veto(*args):
args[-1].Veto()
start_use = time.time()
end_use = time.time()
def _to_str(i):
if isinstance(i, unicode):
return i.encode('utf-8')
else:
return i
def do_nothing(*args):
return
NULLDOC = None
def auto_thaw(method):
def wrapper(self, *args, **kwargs):
self.Freeze()
try:
return method(self, *args, **kwargs)
finally:
self.Thaw()
wx.Yield()
wrapper.__name__ = method.__name__
return wrapper
#---------------------- Frame that contains everything -----------------------
class MainWindow(wx.Frame):
def __init__(self,parent,id,title,fnames):
wx.Frame.__init__(self,parent,id, title, size = ( 1024, 600 ),
style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
self.starting = 1
self.redirect = methodhelper.MethodHelper(self)
global root
root = self
#------------------------------- configuration -------------------------------
if 1:
self.SetIcon(getIcon())
self.FINDSHOWN = 0
path = os.path.join(homedir, 'menus.txt')
if UNICODE:
p = os.path.join(homedir, 'menus.u.txt')
if os.path.exists(p):
path = p
print "Loading menus from", path
try: OLD_MENUPREF.update(unrepr(open(path, 'r').read()))
except: pass
single_instance.callback = self.OnDrop
#recent menu relocated to load configuration early on.
recentmenu = wx.Menu()
#--------------------------- cmt-001 - 08/06/2003 ----------------------------
#----------------- Adds opened file history to the File menu -----------------
if 1:
self.fileHistory = wx.FileHistory()
self.fileHistory.UseMenu(recentmenu)
self.configPath = homedir
self.loadHistory()
self.Maximize(LASTWINDOWSTATE)
self.SetSize(LASTSIZE)
self.SetPosition(LASTPOSITION)
wx.Yield()
self.restart = 0
self.restartt = 0
wx.EVT_MENU_RANGE(self, wx.ID_FILE1, wx.ID_FILE9, self.OnFileHistory)
self.lastused = lru.lastused(128+len(lastopen), LASTUSED)
self.curdocstates = {}
window_management.enabled = dict.fromkeys([i for i in window_management.possible if i not in disabled_tools])
#------------------------- end cmt-001 - 08/06/2003 --------------------------
self.toparse = []
self.parsing = 0
try:
## typ = wx.ITEM_RADIO
typ = wx.ITEM_CHECK
self.HAS_RADIO = 1
except:
typ = wx.ITEM_NORMAL
self.HAS_RADIO = 0
#------------------------------- window layout -------------------------------
if 1:
self.sb = wx.StatusBar(self, -1)
if UNICODE:
#to display encoding in unicode supporting platforms
self.sb.SetFieldsCount(3)
self.sb.SetStatusWidths([-1, 95, 60])
else:
self.sb.SetFieldsCount(2)
self.sb.SetStatusWidths([-1, 95])
self.SetStatusBar(self.sb)
if TOOLBAR:
self._setupToolBar()
# Setting up the menu
## bottom = makeSubWindow(self, ID_WINDOW_BOTTOM, (BIG, SASH1),
## wx.LAYOUT_HORIZONTAL,
## *LB_LOC[logbarlocn])
## right = makeSubWindow(self, ID_WINDOW_RIGHT, (SASH2, BIG),
## wx.LAYOUT_VERTICAL,
## *DB_LOC[docbarlocn])
bottom = self.client2 = SplitterWindow(self, -1, style=wx.SP_NOBORDER)
right = self.client = SplitterWindow(bottom, -1, style=wx.SP_NOBORDER)
self.control = documents.MyNB(self, -1, self.client)
self.BOTTOM = bottom
self.RIGHT = right
## self.BOTTOMNB = wx.Notebook(bottom, -1)
self.BOTTOMNB = aui.AuiNotebook(bottom, -1, style=_style)
## self.RIGHTNB = wx.Notebook(right, -1)
self.RIGHTNB = aui.AuiNotebook(right, -1, style=_style)
bottom.SplitHorizontally(right, self.BOTTOMNB, -SASH1, not logbarlocn)
wx.Yield()
right.SplitVertically(self.control, self.RIGHTNB, -SASH2, not docbarlocn)
wx.Yield()
## self.RIGHTNB.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, browser.ChangedPage)
self.RIGHTNB.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, browser.ChangedPage)
self.docpanel, self.dragger = documents._MyLC(self.RIGHTNB, self)
if DEBUG:
self.crust = crust.Crust(self.RIGHTNB, rootObject=app,
rootLabel='main', execStartupScript=False)
self.RIGHTNB.AddPage(self.crust, "DEBUG")
y = [('Name', 'leftt'), ('Line','rightt'), ('Filter', 'filterl'), ('Todo','todot')]#, ('Tags', 'taglist'), ('TagM', 'tagmanage')]
if ONE_TAB_:
self.single_ctrl = wx.Choicebook(self.RIGHTNB, -1)
self.RIGHTNB.AddPage(self.single_ctrl, "Tools")
for name,i in y:
if ONE_TAB_:
ctrl = self.single_ctrl
elif TODOBOTTOM and name == 'Todo':
ctrl = self.BOTTOMNB
else:
ctrl = self.RIGHTNB
x = _choicebook(ctrl, -1)
if TOOLS_ENABLE_LKP[i] in window_management.enabled:
ctrl.AddPage(x, name)
setattr(self, i, x)
self.gf = filtertable.GlobalFilter(self.RIGHTNB, self)
self.gfp = self.RIGHTNB.GetPageCount()
if global_filter_table:
self.RIGHTNB.AddPage(self.gf, "GlobalF")
else:
self.gf.Hide()
self.macropage = macro.macroPanel(self.RIGHTNB, self)
self.RIGHTNB.AddPage(self.macropage, "Macros")
self.BOTTOMNB.AddPage(logger.logger(self.BOTTOMNB), 'Log')
## self.BOTTOMNB.AddPage(findinfiles.FindInFiles(self.BOTTOMNB, self), "Find in Files")
self.findinfiles = findinfiles.FindInFiles(self.BOTTOMNB, self)
self.BOTTOMNB.AddPage(self.findinfiles, "Search")
self.BOTTOMNB.AddPage(spellcheck.SpellCheck(self.BOTTOMNB, self), "Spell Check")
## self.shell = shell.Shell(self.BOTTOMNB, self, self.config.get('shellprefs', {}))
## self.BOTTOMNB.AddPage(self.shell, "Shell")
if UNICODE:
self.BOTTOMNB.AddPage(textrepr.TextRepr(self.BOTTOMNB, self), "repr(text)")
self.BOTTOMNB.AddPage(help.MyHtmlWindow(self.BOTTOMNB), "Help")
self.RIGHTNB.AddPage(self.docpanel, 'Documents')
self.pathmarks = browser.FilesystemBrowser(self.RIGHTNB, self, pathmarksn)
self.RIGHTNB.AddPage(self.pathmarks, "Browse...")
self.altview = View(self.BOTTOMNB, wx.NewId(), self.BOTTOMNB)
self.BOTTOMNB.AddPage(self.altview, "Split")
self.altview2 = View(self.RIGHTNB, wx.NewId(), self.RIGHTNB)
self.RIGHTNB.AddPage(self.altview2, "Split")
global NULLDOC
NULLDOC = self.altview.GetDocPointer()
self.altview.AddRefDocument(NULLDOC)
#------------------------- Insert menus into Menubar -------------------------
global menuBar
menuBar = wx.MenuBar()
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
self.menubar = menuBar
#--------------------------------- File Menu ---------------------------------
if 1:
filemenu= wx.Menu()
menuAddM(menuBar, filemenu, "&File")
menuAdd(self, filemenu, "&New\tCtrl+N", "New file", self.OnNew, wx.ID_NEW)
menuAdd(self, filemenu, "&Open\tCtrl+O", "Open a file", self.OnOpen, wx.ID_OPEN)
menuAdd(self, filemenu, "Open &Module\tAlt+M", "Open a module for editing using the same path search as import would", self.OnOpenModule, wx.NewId())
menuAdd(self, filemenu, "Open &Last\t", "Open all the documents that were opening before last program exit", self.OnOpenPrevDocs, wx.NewId())
menuAddM(filemenu, recentmenu, "Open Recent")
filemenu.AppendSeparator()
menuAdd(self, filemenu, "&Save\tCtrl+S", "Save a file", self.OnSave, wx.ID_SAVE)
menuAdd(self, filemenu, "Save &As", "Save a file as...", self.OnSaveAs, wx.ID_SAVEAS)
menuAdd(self, filemenu, "Sa&ve All", "Save all open files...", self.OnSaveAll, wx.NewId())
menuAdd(self, filemenu, "Save Copy As", "Save a copy of the current file as...", self.OnSaveCopyAs, wx.NewId())
filemenu.AppendSeparator()
menuAdd(self, filemenu, "New Python Shell", "Opens a Python shell in a new tab", self.OnNewPythonShell, wx.NewId())
menuAdd(self, filemenu, "New Command Shell", "Opens a command line shell in a new tab", self.OnNewCommandShell, wx.NewId())
menuAdd(self, filemenu, "Run Current File", "Runs the current file", self.OnRunCurrentFile, wx.NewId())
menuAdd(self, filemenu, "Run Current File -i", "Runs the current file, passing -i to the command line for Python documents", self.OnRunCurrentFileI, wx.NewId())
menuAdd(self, filemenu, "Run Selected Code", "Runs the currently selected code in a Python shell", self.OnRunSelected, wx.NewId())
filemenu.AppendSeparator()
menuAdd(self, filemenu, "Add Module Search Path", "Add a path to search during subsequent 'Open Module' executions", self.AddSearchPath, wx.NewId())
menuAdd(self, filemenu, "&Reload", "Reload the current document from disk", self.OnReload, wx.ID_REVERT)
menuAdd(self, filemenu, "Check Mods\tShift+F5", "Check to see if any files have been modified", self.OnCheckMods, wx.NewId())
menuAdd(self, filemenu, "&Close\tCtrl+W", "Close the file in this tab", self.OnClose, wx.ID_CLOSE)
workspace.WorkspaceMenu(filemenu, self, workspaces, workspace_order)
menuAdd(self, filemenu, "Restart", "Restart PyPE", self.OnRestart, wx.NewId())
menuAdd(self, filemenu, "E&xit\tAlt+F4", "Terminate the program", self.OnExit, wx.NewId())
#--------------------------------- Edit Menu ---------------------------------
if 1:
editmenu= wx.Menu()
menuAddM(menuBar, editmenu, "&Edit")
menuAdd(self, editmenu, "Undo\tCtrl+Z", "Undo last modifications", self.OnUndo, wx.ID_UNDO)
menuAdd(self, editmenu, "Redo\tCtrl+Y", "Redo last modifications", self.OnRedo, wx.ID_REDO)
editmenu.AppendSeparator()
menuAdd(self, editmenu, "Select All\tCtrl+A", "Select all text", self.OnSelectAll, wx.NewId())
menuAdd(self, editmenu, "Start/End Selection", "Will allow you to set selection start and end positions without holding shift", self.redirect.OnSelectToggle, wx.NewId())
menuAdd(self, editmenu, "Cut\tCtrl+X", "Cut selected text", self.OnCut, wx.ID_CUT)
menuAdd(self, editmenu, "Copy\tCtrl+C", "Copy selected text", self.OnCopy, wx.ID_COPY)
menuAdd(self, editmenu, "Paste\tCtrl+V", "Paste clipboard text", self.OnPaste, wx.ID_PASTE)
menuAdd(self, editmenu, "Delete", "Delete selected text", self.OnDeleteSelection, pypeID_DELETE)
editmenu.AppendSeparator()
menuAdd(self, editmenu, "PasteAndDown", "Paste clipboard text and move cursor down", self.OnPasteAndDown, wx.NewId())
menuAdd(self, editmenu, "Paste Rectangular", "Paste clipboard text as a rectangle", self.OnPasteRectangular, wx.NewId())
menuAdd(self, editmenu, "Delete Right", "Delete from caret to end of line", self.OnDeleteRight, wx.NewId())
menuAdd(self, editmenu, "Delete Line", "Delete current line", self.OnDeleteLine, wx.NewId())
editmenu.AppendSeparator()
menuAdd(self, editmenu, "Show Find Bar\tCtrl+F", "Shows the find bar at the bottom of the editor", self.OnShowFindbar, pypeID_FINDBAR)
menuAdd(self, editmenu, "Show Replace Bar\tCtrl+R", "Shows the replace bar at the bottom of the editor", self.OnShowReplacebar, pypeID_REPLACEBAR)
menuAdd(self, editmenu, "Find again\tF3", "Finds the text in the find bar again", self.OnFindAgain, wx.NewId())
## editmenu.AppendSeparator()
## if self.config['usesnippets']:
## menuAdd(self, editmenu, "Insert Snippet\tCtrl+return", "Insert the currently selected snippet into the document", self.snippet.OnListBoxDClick, wx.NewId())
#------------------------------ Transform Menu -------------------------------
if 1:
transformmenu= wx.Menu()
menuAddM(menuBar, transformmenu, "&Transforms")
menuAdd(self, transformmenu, "Indent Region\tCtrl+]", "Indent region", self.redirect.OnIndent, IDR)
menuAdd(self, transformmenu, "Dedent Region\tCtrl+[", "Dedent region", self.redirect.OnDedent, DDR)
menuAdd(self, transformmenu, "Wrap Selected Text\tAlt+W", "Wrap selected text to a specified width", self.redirect.OnWrap, wx.NewId())
transformmenu.AppendSeparator()
menuAdd(self, transformmenu, "Insert Comment\tCtrl+I", "Insert a centered comment", self.redirect.OnInsertComment, wx.NewId())
menuAdd(self, transformmenu, "Comment Selection\tAlt+8", "Comment selected lines", self.redirect.OnCommentSelection, wx.NewId())
menuAdd(self, transformmenu, "Uncomment Selection\tAlt+9", "Uncomment selected lines", self.redirect.OnUncommentSelection, wx.NewId())
transformmenu.AppendSeparator()
menuAdd(self, transformmenu, "Wrap try/except", "Wrap the selected code in a try/except clause", self.redirect.WrapExcept, wx.NewId())
menuAdd(self, transformmenu, "Wrap try/finally", "Wrap the selected code in a try/finally clause", self.redirect.WrapFinally, wx.NewId())
menuAdd(self, transformmenu, "Wrap try/except/finally", "Wrap the selected code in a try/except/finally clause", self.redirect.WrapExceptFinally, wx.NewId())
transformmenu.AppendSeparator()
menuAdd(self, transformmenu, "Tabs to Spaces", "Convert leading tabs to spaces", self.redirect.convertLeadingTabsToSpaces, wx.NewId())
menuAdd(self, transformmenu, "Spaces to Tabs", "Convert leading spaces to tabs", self.redirect.convertLeadingSpacesToTabs, wx.NewId())
transformmenu.AppendSeparator()
menuAdd(self, transformmenu, "Perform Trigger", "Performs a trigger expansion if possible", self.redirect.OnTriggerExpansion, TRIGGER)
#--------------------------------- View Menu ---------------------------------
if 1:
viewmenu= wx.Menu()
menuAddM(menuBar, viewmenu,"&View")
menuAdd(self, viewmenu, "Previous Tab\tAlt+,", "View the tab to the left of the one you are currently", self.OnLeft, wx.NewId())
menuAdd(self, viewmenu, "Next Tab\tAlt+.", "View the tab to the right of the one you are currently", self.OnRight, wx.NewId())
viewmenu.AppendSeparator()
menuAdd(self, viewmenu, "Zoom In\tCtrl++", "Make the text in the editing component bigger", self.OnZoom, ZI)
menuAdd(self, viewmenu, "Zoom Out\tCtrl+-", "Make the text in the editing component smaller", self.OnZoom, wx.NewId())
viewmenu.AppendSeparator()
menuAdd(self, viewmenu, "Go to line number\tAlt+G", "Advance to the given line in the currently open document", self.OnGoto, wx.NewId())
menuAdd(self, viewmenu, "Go to position", "Advance to the given position in the currently open document", self.OnGotoP, wx.NewId())
menuAdd(self, viewmenu, "Jump forward", "Advance the cursor to the next quote/bracket", self.redirect.OnJumpF, wx.NewId())
menuAdd(self, viewmenu, "Jump backward", "Advance the cursor to the previous quote/bracket", self.redirect.OnJumpB, wx.NewId())
viewmenu.AppendSeparator()
menuAdd(self, viewmenu, "Toggle Bookmark\tCtrl+M", "Create/remove bookmark for this line", self.OnToggleBookmark, pypeID_TOGGLE_BOOKMARK)
menuAdd(self, viewmenu, "Next Bookmark\tF2", "Hop to the next bookmark in this file", self.OnNextBookmark, pypeID_NEXT_BOOKMARK)
menuAdd(self, viewmenu, "Previous Bookmark\tShift+F2", "Hop to the previous bookmark in this file", self.OnPreviousBookmark, pypeID_PRIOR_BOOKMARK)
menuAdd(self, viewmenu, "Clear Notifications", "Clears all notifications and line annotations", self.OnClearNotifications, wx.NewId())
viewmenu.AppendSeparator()
menuAdd(self, viewmenu, "Find Definition", "Shows the filter tool and tries to find the current word in the definitions", self.OnFindDefn, wx.NewId())
viewmenu.AppendSeparator()
menuAdd(self, viewmenu, "Split Wide", "Shows an alternate view of the current document in the wide tools", self.OnSplitW, wx.NewId())
menuAdd(self, viewmenu, "Split Tall", "Shows an alternate view of the current document in the tall tools", self.OnSplitT, wx.NewId())
menuAdd(self, viewmenu, "Unsplit", "Removes all document views", self.OnUnsplit, wx.NewId())
#------------------------------- Document menu -------------------------------
if 1:
setmenu= wx.Menu()
menuAddM(menuBar, setmenu, "&Document")
## menuAdd(self, setmenu, "Use Snippets (req restart)", "Enable or disable the use of snippets, requires restart for change to take effect", self.OnSnipToggle, SNIPT, wx.ITEM_CHECK)
## setmenu.AppendSeparator()
#------------------------------ Style subenu ---------------------
stylemenu= wx.Menu()
menuAddM(setmenu, stylemenu, "Syntax Highlighting", "Change the syntax highlighting for the currently open document")
for i in ASSOC:
name, mid = i[6], i[0]
st = "Highlight for %s syntax"%name
if name == 'Text':
st = "No Syntax Highlighting"
menuAdd(self, stylemenu, name, st, self.OnStyleChange, mid, typ)
#---------------------------- Encodings submenu ------------------
if UNICODE:
encmenu= wx.Menu()
menuAddM(setmenu, encmenu, "Encodings", "Change text encoding")
menuAdd(self, encmenu, 'ascii', "Change encoding for the current file to ascii (will use utf-8 if unicode characters found)", self.OnEncChange, ENCODINGS['ascii'], typ)
menuAdd(self, encmenu, 'other', "Will use the encoding specified in your encoding declaration, reverting to ascii if not found, and utf-8 as necessary", self.OnEncChange, ENCODINGS['other'], typ)
for bom, enc in BOM[:-2]:
menuAdd(self, encmenu, enc, "Change encoding for the current file to %s"%enc, self.OnEncChange, ENCODINGS[enc], typ)
#--------------------------- Line ending menu --------------------
endingmenu = wx.Menu()
menuAddM(setmenu, endingmenu, "Line Ending", "Change the line endings on the current document")
x = LE_RMAPPING.values()
x.sort()
for _, idn, name, helpt in x:
menuAdd(self, endingmenu, name, helpt, self.OnLineEndChange, idn, typ)
#
setmenu.AppendSeparator()
menuAdd(self, setmenu, "Show Autocomplete", "Show the autocomplete dropdown while typing", self.OnAutoCompleteToggle, AUTO, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Use Methods", "Try to only display methods of classes during autocomplete", self.OnUseMethodsToggle, FETCH_M, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Autocomplete Keywords", "Include standard Python keywords and names in the autocomplete list", self.OnUseKeywordsToggle, AC_KEYWORDS, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Set Autocomplete Length", "The number of characters necessary to produce an autocomplete list", self.OnAutocompleteLength, AC_LENGTH)
menuAdd(self, setmenu, "Show line numbers", "Show or hide the line numbers on the current document", self.OnNumberToggle, NUM, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Show margin", "Show or hide the bookmark signifier margin on the current document", self.OnMarginToggle, MARGIN, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Show Indentation Guide", "Show or hide gray indentation guides in indentation", self.OnIndentGuideToggle, INDENTGUIDE, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Show Whitespace", "Show or hide 'whitespace' characters", self.OnWhitespaceToggle, S_WHITE, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Show Line Endings", "Show or hide line ending characters", self.OnLineEndingToggle, S_LEND, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Save Position", "Remember or forget the last position of the cursor when the current document is closed", self.OnSavePositionToggle, SAVE_CURSOR, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Highlight Current line", "When checked, will change the background color of the current line", self.HightlightLineToggle, HIGHLIGHT_LINE, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Show Annotations", "When checked, will show annotations when available", self.AnnotationsToggle, ANNOTATIONS_VISIBLE, wx.ITEM_CHECK)
setmenu.AppendSeparator()
menuAdd(self, setmenu, "Refresh\tF5", "Refresh the browsable source tree, autocomplete listing, and the tooltips (always accurate, but sometimes slow)", self.OnRefresh, wx.NewId())
menuAdd(self, setmenu, "Run Macro", "Run the currently selected macro on the current document", self.macropage.OnPlay, wx.NewId())
setmenu.AppendSeparator()
menuAdd(self, setmenu, "Expand all", "Expand all folded code through the entire document", self.OnExpandAll, wx.NewId())
menuAdd(self, setmenu, "Fold all", "Fold all expanded code through the entire document", self.OnFoldAll, wx.NewId())
menuAdd(self, setmenu, "Use Tabs", "New indentation will include tabs", self.OnSetTabToggle, USETABS, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Wrap Long Lines", "Visually continue long lines to the next line", self.OnWrapL, WRAPL, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Sloppy Cut/Copy", "Will select all partially selected lines during cut/copy.", self.OnSloppy, SLOPPY, wx.ITEM_CHECK)
menuAdd(self, setmenu, "Smart Paste", "Will auto-indent pastes that are multi-line", self.OnSmartPaste, SMARTPASTE, wx.ITEM_CHECK)
setmenu.AppendSeparator()
menuAdd(self, setmenu, "Set Triggers", "Sets trigger expansions for the current document", self.OnSetTriggers, wx.NewId())
menuAdd(self, setmenu, "Set Indent Width", "Set the number of spaces per indentation level", self.OnSetIndent, wx.NewId())
menuAdd(self, setmenu, "Set Tab Width", "Set the visual width of tabs in the current open document", self.OnSetTabWidth, wx.NewId())
menuAdd(self, setmenu, "Set Long Line Column", "Set the column number for the long line indicator", self.OnSetLongLinePosition, wx.NewId())
#---------------------------- Long line submenu ------------------
longlinemenu = wx.Menu()
menuAddM(setmenu, longlinemenu, "Set Long Line Indicator", "Change the mode that signifies long lines")
x = LL_RMAPPING.values()
x.sort()
for _, idn, name, helpt in x:
menuAdd(self, longlinemenu, name, helpt, self.OnSetLongLineMode, idn, typ)
#------------------------------- Options Menu --------------------------------
if 1:
optionsmenu= wx.Menu()
menuAddM(menuBar, optionsmenu, "&Options")
settingsmenu = wx.Menu()
menuAddM(optionsmenu, settingsmenu, "Save Settings", "Set the default behavior of documents opened of a given type")
for mid in SITO:
lang, desc = SOURCE_ID_TO_OPTIONS[mid]
menuAdd(self, settingsmenu, desc, "Save the settings for the current document as the default for %s documents"%desc, self.OnSaveLang, mid)
#menuAdd(self, settingsmenu, "", ", self.OnSaveSettings, wx.NewId())
loadsettingsmenu = wx.Menu()
menuAddM(optionsmenu, loadsettingsmenu, "Load Settings", "Set the current document behavior to that of the default for documents of a given type")
for mid in SITO2:
lang, desc = SOURCE_ID_TO_OPTIONS2[mid]
menuAdd(self, loadsettingsmenu, desc, "Set the current document behavior to that of the default for %s"%desc, self.OnLoadSavedLang, mid)
optionsmenu.AppendSeparator()
#-------------------------- Default Style submenu ----------------
stylemenu2 = wx.Menu()
menuAddM(optionsmenu, stylemenu2, "Default Highlighting", "Set the default syntax highlighting for new or unknown documents")
for i in ASSOC:
name, mid = i[6], i[1]
st = "All new or unknown documents will be highlighted as %s"%name
menuAdd(self, stylemenu2, name, st, self.OnDefaultStyleChange, mid, typ)
## optionsmenu.AppendSeparator()
## menuAdd(self, optionsmenu, "Enable File Drops", "Enable drag and drop file support onto the text portion of the editor", self.OnDNDToggle, DND_ID, wx.ITEM_CHECK)
optionsmenu.AppendSeparator()
menuAdd(self, optionsmenu, "One PyPE", "When checked, will listen on port 9999 for filenames to open", self.OnSingleToggle, SINGLE_ID, wx.ITEM_CHECK)
menuAdd(self, optionsmenu, "Use Icons", "When checked, the editor uses filetype-specific icons next to file names", self.OnIconToggle, IT_ID, wx.ITEM_CHECK)
menuAdd(self, optionsmenu, "Method Colors", "When checked, the editor will use colored icons next to functions and methods based on how 'public' a method is (requires refresh)", self.OnMethodColorToggle, METH_C_ID, wx.ITEM_CHECK)
if UNICODE:
menuAdd(self, optionsmenu, "Always Write BOM", "If checked, will write BOM when coding: directive is found, otherwise not", self.OnBOMToggle, USEBOM_ID, wx.ITEM_CHECK)
if sys.platform.startswith('win32'):
menuAdd(self, editmenu, "Enable Middle Paste", "Allows PyPE-centric middle-paste in Windows", self.OnMiddleClickToggle, MIDDLE_CL, wx.ITEM_CHECK)
menuAdd(self, optionsmenu, "Strict Todo", "When checked, todos must also begin with > character (except xml/html)", self.OnStrictTodoToggle, STRICT_TODO_ID, wx.ITEM_CHECK)
menuAdd(self, optionsmenu, "Set Line Color", "The color of the current line when 'Highlight Current Line' is enabled", self.OnLineColor, wx.NewId())
_om = wx.Menu()
menuAddM(optionsmenu, _om, "Layout Options", "Options regarding the PyPE window layout")
menuAdd(self, _om, "Editor on top", "When checked, the editor is above the Todos, Log, etc., otherwise it is below", self.OnLogBarToggle, LB_ID, wx.ITEM_CHECK)
menuAdd(self, _om, "Editor on left", "When checked, the editor is left of the source trees, document list, etc., otherwise it is to the right", self.OnDocBarToggle, DB_ID, wx.ITEM_CHECK)
menuAdd(self, _om, "Show Wide Tools", "Shows or hides the tabbed tools that are above or below the editor", self.OnShowWideToggle, WIDE_ID, wx.ITEM_CHECK)
menuAdd(self, _om, "Show Tall Tools", "Shows or hides the tabbed tools that are right or left of the editor", self.OnShowTallToggle, TALL_ID, wx.ITEM_CHECK)
menuAdd(self, _om, "One Tab", "When checked, the name, line, filter, and todo lists all share a tab (requires restart)", self.OnOneTabToggle, ONE_TAB, wx.ITEM_CHECK)
menuAdd(self, _om, "Wide Todo", "When checked, the todo list will be near the Log tab, when unchecked, will be near the Documenst tab (requires restart)", self.OnTodoToggle, TD_ID, wx.ITEM_CHECK)
_om.AppendSeparator()
x = TB_RMAPPING.values()
x.sort()
for _, idn, name, helpt in x:
menuAdd(self, _om, "(toolbar)" + name, helpt, self.OnToolBar, idn, typ)
doptmenu = wx.Menu()
menuAddM(optionsmenu, doptmenu, "Documents Tab", "Change behavior of the Documents tab")
for value in (1,3,2,0):
iid = DOCUMENT_LIST_OPTION_TO_ID[value]
desc = DOCUMENT_LIST_OPTIONS[iid][1]
menuAdd(self, doptmenu, "(documents) " +desc, "Make the Documents list look like: %s"%desc, self.OnChangeDocumentsOptions, iid, typ)
doptmenu.AppendSeparator()
menuAdd(self, doptmenu, "Show Recent", "When checked, will provide a list of recently open documents in the Documents tab (requires restart)", self.OnShowRecentDocs, SHOW_RECENT, wx.ITEM_CHECK)
## if show_recent:
doptmenu.AppendSeparator()
for value in (1,3,2,0):
iid = DOCUMENT_LIST_OPTION_TO_ID2[value]
desc = DOCUMENT_LIST_OPTIONS2[iid][1]
menuAdd(self, doptmenu, "(recent) " + desc, "Make the Recent Documents list look like: %s"%desc, self.OnChangeDocumentsOptions2, iid, typ)
doptmenu.AppendSeparator()
menuAdd(self, doptmenu, "Show Quick Browse", "Show a searchable listing of recently open documents and watched paths", self.OnShowQuickbrowse, SHOW_SEARCH, typ)
moptmenu = wx.Menu()
menuAddM(optionsmenu, moptmenu, "Macro Options", "Change the behavior of macros during double-click")
menuAdd(self, moptmenu, "Use images for macro buttons", "When checked, the macro buttons will have images (requires restart)", self.OnMacroButtonImage, IMAGE_BUTTONS, typ)
moptmenu.AppendSeparator()
for value in xrange(3):
iid = MACRO_CLICK_TO_ID[value]
desc = MACRO_CLICK_OPTIONS[iid][1]
menuAdd(self, moptmenu, "(double click) " + desc, "When double clicking on a macro: %s"%desc, self.OnChangeMacroOptions, iid, typ)
#
#ability to enable/disable a tool
toolsmenu = wx.Menu()
menuAddM(optionsmenu, toolsmenu, "Tool Options", "Enable or disable a particular tool")
for i in TOOLS_ENABLE_L:
menuAdd(self, toolsmenu, i[1], "Enable "+i[2], self.OnToolToggle, i[0], wx.ITEM_CHECK)
optionsmenu.AppendSeparator()
caretmenu = wx.Menu()
menuAddM(optionsmenu, caretmenu, "Caret Options", "Set options relating to your blinking cursor")
x = [(j[2], i, j[3], j[4]) for i,j in CARET_ID_TO_OPTIONS.iteritems()]
x.sort()
for _, idn, name, helpt in x:
menuAdd(self, caretmenu, "(caret behavior) " + name, helpt, self.OnCaret, idn, typ)
caretmenu.AppendSeparator()
menuAdd(self, caretmenu, "Set Caret M value", "Set the number of lines of unapproachable margin, the M value referenced in Caret Options", self.OnCaretM, wx.NewId())
menuAdd(self, caretmenu, "Set Caret N value", "Set the multiplier, the N value referenced in Caret Options", self.OnCaretN, wx.NewId())
caretmenu.AppendSeparator()
for i in (1,2,3):
menuAdd(self, caretmenu, "caret is %i pixels wide"%i, "Set your caret to be %i pixels wide."%i, self.OnCaretWidth, CARET_W_WIDTH_TO_O[i], typ)
#---------------- Python interpreter choice for Python Shell -----------------
shellmenu = wx.Menu()
menuAddM(optionsmenu, shellmenu, "Shell Options", "Set various shell options")
for i in xrange(len(SHELL_OUTPUT_OPTIONS)):
idn = SHELL_NUM_TO_ID[i]
desc = SHELL_OUTPUT_OPTIONS[idn][1]
menuAdd(self, shellmenu, "(shell output) "+desc, "Any output recieved from shells will be indicated by: %s"%desc, self.OnShellStyle, idn, typ)
shellmenu.AppendSeparator()
menuAdd(self, shellmenu, "Set Shell Output Color", "The color of the output indicator chosen above", self.OnShellColor, wx.NewId())
self.python_choices = choices = shellmenu
menuAdd(self, choices, "Browse for Python shells...", "Choose some Python interpreter not listed", self.OnBrowseInterpreter, wx.NewId())
choices.AppendSeparator()
interpreter.check_paths(python_choices, which_python)
for i in interpreter.python_choices:
self.AddPythonOption(i, i==interpreter.which_python)
#--------------- end Python interpreter choice for Python Shell --
_realtime = wx.Menu()
menuAddM(optionsmenu, _realtime, "Realtime Options", "Adjust the behavior of the realtime syntax checker and tool refresh")
for i, n, d in SYNTAX_CHECK_DELAY_L:
menuAdd(self, _realtime, "(check syntax) " + d, "Check the syntax of Python documents at most every: %s"%d, self.OnSyntaxChange, i, wx.ITEM_CHECK)
_realtime.AppendSeparator()
for i, n, d in REFRESH_DELAY_L:
menuAdd(self, _realtime, "(update tools) " + d, "Refresh at most every: %s"%d, self.OnRefreshChange, i, wx.ITEM_CHECK)
findbar = wx.Menu()
menuAddM(optionsmenu, findbar, "Findbar Options", "Set findbar preferences")
menuAdd(self, findbar, "Findbar below editor", "When checked, any new find/replace bars will be below the editor, otherwise above (bars will need to be reopened)", self.OnFindbarToggle, FINDBAR_BELOW_EDITOR, wx.ITEM_CHECK)
menuAdd(self, findbar, "Use Findbar history", "When checked, allows for the find and replace bars to keep history of searches (bars will need to be reopened)", self.OnFindbarHistory, NO_FINDBAR_HISTORY, wx.ITEM_CHECK)
menuAdd(self, findbar, "Clear Find Bar history", "Clears the find/replace history on the current document", self.OnFindbarClear, CLEAR_FINDBAR_HISTORY)
optionsmenu.AppendSeparator()
menuAdd(self, optionsmenu, "Change Menus and Hotkeys", "Change the name of menu items and their hotkeys, any changes will require a restart to take effect", self.OnChangeMenu, wx.NewId())
titlemenu = wx.Menu()
menuAddM(optionsmenu, titlemenu, "Title Options", "Set what information you would like PyPE to display in the title bar")
fn = "pype.py"
long = "C:\\PyPE\\pype.py"
pype = "PyPE %s"%VERSION
for i in xrange(5):
title_id, proto, desc = TITLE_OPTION_TO_ID[i]
menuAdd(self, titlemenu, desc, "Set the title like: "+proto%locals(), self.OnChangeTitle, title_id, typ)
menuAdd(self, optionsmenu, "Save preferences", "Saves all of your current preferences now", self.OnSavePreferences, wx.NewId())
#--------------------------------- Help Menu ---------------------------------
if 1:
helpmenu= wx.Menu()
menuAddM(menuBar, helpmenu, "&Help")
menuAdd(self, helpmenu, "About...", "About this piece of software", self.OnAbout, wx.ID_ABOUT)
helpmenu.AppendSeparator()
menuAdd(self, helpmenu, "PyPE Help\tF1", "View the help", self.OnHelp, wx.ID_HELP)
#------------------------ A ...few... state variables ------------------------
if 1:
self.Show(True)
self.dirname = '.'
self.closing = 0
self.openfiles = {}
self.realfn = {}
self.dpm = 0
self.menubar.Check(AUTO, showautocomp)
self.menubar.Check(WRAPL, wrapmode != wxstc.STC_WRAP_NONE)
## self.menubar.Check(DND_ID, dnd_file)
self.menubar.Check(IT_ID, USE_DOC_ICONS)
codetree.colored_icons = colored_icons
self.menubar.Check(METH_C_ID, codetree.colored_icons)
self.menubar.Check(LB_ID, logbarlocn)
self.menubar.Check(DB_ID, docbarlocn)
self.menubar.Check(WIDE_ID, SHOWWIDE)
self.menubar.Check(TALL_ID, SHOWTALL)
self.menubar.Check(ONE_TAB, ONE_TAB_)
self.menubar.Check(SINGLE_ID, single_pype_instance)
if UNICODE:
self.menubar.Check(USEBOM_ID, always_write_bom)
self.menubar.Check(SHELL_NUM_TO_ID[SHELL_OUTPUT], 1)
self.menubar.Check(IMAGE_BUTTONS, macro_images)
self.menubar.Check(TD_ID, TODOBOTTOM)
self.menubar.Check(STRICT_TODO_ID, STRICT_TODO)
self.menubar.Check(USETABS, use_tabs)
self.menubar.Check(INDENTGUIDE, indent_guide)
self.menubar.Check(lexers3[DEFAULTLEXER], 1)
self.menubar.Check(SAVE_CURSOR, save_cursor)
self.menubar.Check(SYNTAX_CHECK_DELAY_NUM_TO_ID[HOW_OFTEN1], 1)
self.menubar.Check(REFRESH_DELAY_NUM_TO_ID[HOW_OFTEN2], 1)
self.menubar.Check(FINDBAR_BELOW_EDITOR, findbar_location)
self.menubar.Check(NO_FINDBAR_HISTORY, not no_findbar_history)
self.menubar.Check(CARET_W_WIDTH_TO_O[CARET_WIDTH], 1)
self.menubar.FindItemById(CLEAR_FINDBAR_HISTORY).Enable(not no_findbar_history)
self.menubar.Check(DOCUMENT_LIST_OPTION_TO_ID[document_options], 1)
if hasattr(self.docpanel, 'recentlyclosed'):
self.menubar.Check(DOCUMENT_LIST_OPTION_TO_ID2[document_options2], 1)
self.menubar.Check(SHOW_RECENT, show_recent)
self.menubar.Check(SHOW_SEARCH, show_search)
self.menubar.Check(MIDDLE_CL, MIDDLE_PASTE)
for i in TOOLS_ENABLE_L:
if i[4] in window_management.enabled:
self.menubar.Check(i[0], 1)
elif i[1] == 'Global Filter' and global_filter_table:
self.menubar.Check(i[0], 1)
#------------------------ Drag and drop file support -------------------------
self.SetDropTarget(FileDropTarget(self))
#set up some events
if 1:
wx.EVT_CLOSE(self, self.OnExit)
wx.EVT_END_SESSION(self, self.OnExit)
wx.EVT_QUERY_END_SESSION(self, self.OnExit)
wx.EVT_SIZE(self, self.OnSize)
wx.EVT_ACTIVATE(self, self.OnActivation)
wx.EVT_KEY_DOWN(self, self.OnKeyPressed)
self.starting = 0
if self.control.GetPageCount() > 0:
stc = self.getNumWin()[1]
self.OnDocumentChange(stc)
#set up some timers
if 1:
self.timer = Timer(self.ex_size, None)
self.timer2 = Timer(self.single_instance_poller)
self.timer2.Start(100, oneShot=False)
self.timer3 = Timer(self._no_activity, None)
# pushed to mainwindow from PythonSTC
#syntax checking
self.t = Timer(self.redirect._gotcharacter, None)
#live tree/tool update
self.t2 = Timer(self.redirect._gotcharacter2, None)
#interpreter polling
## self.global_poller = wx.Timer(self, wx.NewId())
## self.Bind(wx.EVT_TIMER, self.RunEvents, self.global_poller)
## self.global_poller.Start(500, oneShot=False)
wx.CallAfter(scheduler._schedulethread)
#------------------ Open files passed as arguments to PyPE -------------------
self.client.Unsplit(startup=1)
self.client2.Unsplit(startup=1)
if SHOWTALL:
wx.CallAfter(self.client.Split)
if SHOWWIDE:
wx.CallAfter(self.client2.Split)
if (not SHOWWIDE) or (not SHOWTALL):
self.OnSize(None)
wx.CallAfter(self.OnDrop, fnames, 0)
if single_pype_instance:
single_instance.startup()
if USE_THREAD:
self.Bind(EVT_DONE_PARSING, self.doneParsing)
wx.CallAfter(parse_thread, self)
wx.CallAfter(check_files, self)
pubsub.subscribe('document.selected', self.OnDocumentChange)
# work-around for a refresh bug in wxPython 2.9+
pubsub.subscribe('document', (lambda x,sc=self.control: sc.SendSizeEvent()))
def redrawvisible(self, win=None):
if (not isinstance(win, PythonSTC)) and self.control.GetPageCount() > 0:
num, win = self.getNumWin()
if win:
win.parent.Refresh()
## def RunEvents(self, evt):
## scheduler.GlobalSchedule.run(time.time())
#...
def _activity(self, py=None, stc=None):
global start_use, end_use
if start_use == None:
start_use = time.time()
end_use = time.time()
self.timer3.Start(5000, oneShot=True)
if stc:
if HOW_OFTEN2 != -1:
self.t2.Start(stc.lastparse2, oneShot=True)
#we always want to check syntax in the shell
if HOW_OFTEN1 != -1 or not isinstance(stc, PythonSTC):
self.t.Start(stc.lastparse, oneShot=True)
def _no_activity(self, e):
global USED_TIME, start_use
if start_use:
USED_TIME += long(max(end_use-start_use, 5))
start_use = None
def _updateChecks(self):
win = None
try:
num, win = self.getNumWin()
except cancelled:
## print "no window!"
pass
self.control.updateChecks(win)
def getglobal(self, nam):
return globals()[nam]
def getInt(self, title, text, default):
dlg = wx.TextEntryDialog(self, text, title, str(default), pos=(0,0))
resp = dlg.ShowModal()
valu = dlg.GetValue()
dlg.Destroy()
if resp != wx.ID_OK:
raise cancelled
return validate(valu, default)
def _setupToolBar(self):
size = (16,16)
def getBmp(artId, client):
bmp = wx.ArtProvider_GetBitmap(artId, client, size)
if not bmp.Ok():
bmp = EmptyBitmap(*size)
return bmp
if TOOLBAR == 1:
orient = wx.TB_HORIZONTAL
else:
orient = wx.TB_VERTICAL
tb = self.CreateToolBar(
orient|wx.NO_BORDER|wx.TB_FLAT|wx.TB_TEXT)
tb.SetToolBitmapSize(size)
icon = getBmp(wx.ART_NORMAL_FILE, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_NEW, icon, "New Document",
"Create a new empty document")
icon = getBmp(wx.ART_FILE_OPEN, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_OPEN, icon, "Open",
"Open an existing document")
icon = getBmp(wx.ART_FILE_SAVE, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_SAVE, icon, "Save", "Save current document")
icon = getBmp(wx.ART_FILE_SAVE_AS, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_SAVEAS, icon, "Save as...", "Save current document as...")
tb.AddSeparator()
icon = getBmp(wx.ART_FOLDER, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_CLOSE, icon, "Close", "Close the current document")
tb.AddSeparator()
icon = getBmp(wx.ART_CUT, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_CUT, icon, "Cut",
"Cut selection to the clibboard")
icon = getBmp(wx.ART_COPY, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_COPY, icon, "Copy",
"Copy selection to the clibboard")
icon = getBmp(wx.ART_PASTE, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_PASTE, icon, "Paste",
"Paste current clibboard contents")
icon = getBmp(wx.ART_DELETE, wx.ART_TOOLBAR)
tb.AddSimpleTool(pypeID_DELETE, icon, "Delete",
"Delete selection")
tb.AddSeparator()
icon = getBmp(wx.ART_UNDO, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_UNDO, icon, "Undo",
"Undo edit")
icon = getBmp(wx.ART_REDO, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_REDO, icon, "Redo",
"Redo edit (i.e. undo undo edit)")
tb.AddSeparator()
icon = getBmp(wx.ART_FIND, wx.ART_TOOLBAR)
tb.AddSimpleTool(pypeID_FINDBAR, icon, "Find",
"Find")
icon = getBmp(wx.ART_FIND_AND_REPLACE, wx.ART_TOOLBAR)
tb.AddSimpleTool(pypeID_REPLACEBAR, icon, "Replace",
"Find and replace")
tb.AddSeparator()
icon = getBmp(wx.ART_ADD_BOOKMARK, wx.ART_TOOLBAR)
tb.AddSimpleTool(pypeID_TOGGLE_BOOKMARK, icon, "Toggle Bookmark",
"Create or Remove a bookmark at the current line")
icon = getBmp(wx.ART_GO_DOWN, wx.ART_TOOLBAR)
tb.AddSimpleTool(pypeID_NEXT_BOOKMARK, icon, "Next Bookmark",
"Go to the next bookmark in this file")
icon = getBmp(wx.ART_GO_UP, wx.ART_TOOLBAR)
tb.AddSimpleTool(pypeID_PRIOR_BOOKMARK, icon, "Previous Bookmark",
"Go to the previous bookmark in this file")
tb.AddSeparator()
tb.AddSeparator()
icon = getBmp(wx.ART_HELP, wx.ART_TOOLBAR)
tb.AddSimpleTool(wx.ID_HELP, icon, "Help!",
"Opens up the help for PyPE")
tb.Realize()
def OnDocumentChange(self, stc_or_msg, forced=False):
if isinstance(stc_or_msg, dict):
for stc in self.control:
if id(stc) == stc_or_msg.stc_id:
break
else:
return
else:
stc = stc_or_msg
if not forced and not self.starting:
self.t.Stop()
self.t2.Stop()
if not self.starting:
start = time.time()
if stc.cached is None or forced:
if stc.refresh:
return
stc.ConvertEOLs(fmt_mode[stc.format])
out = wxstc.StyledTextCtrl.GetText(stc)
m2 = md5.new(_to_str(out)).digest()
if m2 == stc.m2:
return
stc.m2 = m2
out = out.replace('\t', stc.GetTabWidth()*' ')
lang = lexer2lang.get(stc.GetLexer(), 'text')
if out and USE_THREAD:
stc.refresh = 1
parse_queue.put((out, stc, lang))
return
tpl = parse(lang, out, stc.format, 3, lambda:None)
self._doneParsing(stc, tpl, time.time()-start)
self.updateWindowTitle()
def doneParsing(self, evt):
stc = evt.stc
if not stc:
return
self._doneParsing(stc, evt.tpl, evt.delta)
def _doneParsing(self, stc, tpl, delta):
if isinstance(stc, PythonSTC):
fcn = lambda dt: int(max(dt, 1)*_MULT[HOW_OFTEN2]*1000)
else:
fcn = lambda dt: int(max(dt, .02)*5*1000)
t = time.time()
stc.refresh = 0
stc.cached = tpl
h1, _, stc.tooltips, todo, tags = tpl
stc.hierarchy = h1
## stc.kw.sort()
## stc.kw = ' '.join(stc.kw)
stc.docstate.Update(h1, todo, tags)
if self.gf:
self.gf.new_hierarchy(stc, h1)
delta += time.time()-t
stc.lastparse2 = int(max((5,20,120)[HOW_OFTEN2]*delta, (5,20,120)[HOW_OFTEN2])*1000)
if not stc.automatic:
self.SetStatusText(("Browsable source tree, autocomplete, tooltips and todo"
" updated for %s in %.1f seconds.")%(stc.filename, delta))
stc.automatic = 0
def updateWindowTitle(self):
pype = "PyPE %s"%VERSION
stc = None
try:
num, stc = self.getNumWin()
except cancelled:
self.SetTitle(pype)
return
if stc is not None:
fn = stc.getshort()
long = stc.getlong()
disp = TITLE_OPTION_TO_ID[title_option][1]%locals()
else:
disp = pype
self.SetTitle(disp)
def ex_size(self, evt=None):
#an attempt to keep the findbar the correct size
try:
win = self.getNumWin()[1]
if win.parent.IsSplit():
w2 = win.parent.GetWindow2()
try:
size = (w2.GetEffectiveMinSize())[1]+5
except:
size = (w2.GetAdjustedBestSize())[1]+5
win.parent.SetSashPosition(-size)
except cancelled:
pass
# Save window size before it is maximized
if not self.IsMaximized():
global LASTSIZE, LASTPOSITION
LASTSIZE = self.GetSizeTuple()
LASTPOSITION = self.GetPositionTuple()
def single_instance_poller(self, evt=None):
if single_pype_instance:
single_instance.poll()
wins = [self.altview, self.altview2]
try:
wins.append(self.getNumWin()[1])
except cancelled:
pass
for win in wins:
x = win.GetMarginWidth(0)
if x:
#we are supposed to have a margin...
y = len(str(win.GetLineCount()))
z = int(.9*StyleSetter.fs*max(4, y+1))
if x != z:
win.SetMarginWidth(0, z)
def OnSize(self, event):
self.ex_size()
if event:
event.Skip()
def dialog(self, message, title, styl=wx.OK, pos=(0,0)):
d= wx.MessageDialog(self, message, title, styl, pos=pos)
retr = d.ShowModal()
d.Destroy()
return retr
def exceptDialog(self, title="Error"):
k = cStringIO.StringIO()
traceback.print_exc(file=k)
k = k.getvalue()
print k
dlg = ScrolledMessageDialog(self, k, title, pos=(0,0))
dlg.ShowModal()
dlg.Destroy()
def OnDrop(self, fnames, error=1):
cwd = current_path
for i in fnames:
dn, fn = os.path.split(self.getAlmostAbsolute(i, cwd))
if self.isOpen(fn, dn):
if len(fnames)==1:
self.selectAbsolute(self.getAbsolute(fn, dn))
else:
self.makeOpen(fn, dn)
try:
a = self.newTab(dn, fn, len(fnames)==1)
i = os.path.join(dn, fn)
if UNICODE: a = "%s as %s"%(i, a)
else: a = i
self.SetStatusText("Opened %s"%a)
except:
self.closeOpen(fn, dn)
if error:
self.exceptDialog("File open failed")
try:
wx.SafeYield()
except:
pass
self.redrawvisible()
def SetStatusText(self, text, number=0, log=1):
if (number == 0) and text:
if log:
print text
text = "[%s] %s"%(time.asctime(), text)
wx.CallAfter(self.sb.SetStatusText, text, number)
def OnActivation(self, e):
try:
self.control.__iter__
except wx.PyDeadObjectError:
e.Skip()
return
self.OnCheckMods(force=False)
self.redrawvisible()
self.SendSizeEvent()
e.Skip()
def OnCheckMods(self, evt=None, force=True):
try:
self.control.__iter__
except wx.PyDeadObjectError:
e.Skip()
return
docs_and_flags = []
for document in self.control:
fn = self.getAlmostAbsolute(document.filename, document.dirname)
docs_and_flags.append([fn, (document.filename, document.dirname), document.mod])
if docs_and_flags:
t = (not force) and time.time() or 0
file_mods_to_check.put((time.time(), docs_and_flags))
CheckMacros()
def CheckedDocMods(self, mods):
dirty = []
deleted = []
for fn, pair, omod, cmod, digest in mods:
if not self.isOpen(*pair):
continue
document = self.control.GetPage(self.getPositionAbsolute(self.getAbsolute(*pair))).GetWindow1()
if omod and not cmod:
## self.selectAbsolute(self.getAbsolute(*pair))
document.MakeDirty(None)
deleted.append(self.getAbsolute(*pair))
document.mod = None
elif omod != cmod:
if md5.new(document.GetText(error=0)).digest() == digest:
#Fixes a problem with PyPE being open during daylight
#savings time changes.
#Also fixes an issue when an identical file is saved
#over a currently-being-edited file.
document.mod = cmod
document.MakeClean(None)
continue
else:
dirty.append(self.getAbsolute(*pair))
## self.selectAbsolute(self.getAbsolute(*pair))
document.MakeDirty(None)
if deleted:
dlg = wx.MessageDialog(self,
"Some files seem to have been deleted by an external program.\n"
"Unless these files are saved, data loss may occur.\n" + '\n'.join(deleted),
"WARNING", pos=(0,0))
dlg.Destroy()
if dirty:
dlg = wx.MultiChoiceDialog(self,
"The following files have been modified on disk since you\n"
"last saved, and have been marked as 'dirty'.\n"
"Select the files that you would like to reload now.\n"
"You can reload the files individually via File -> Reload,\n"
"or you can force a re-check of the files via\n"
"File -> Check Mods.", "Some documents have changed", dirty, pos=(0,0))
dlg.SetSelections(range(len(dirty)))
if dlg.ShowModal() == wx.ID_OK:
for name in (dirty[i] for i in dlg.GetSelections()):
dirname, filename = os.path.split(name)
self._reload_file(filename, dirname)
dlg.Destroy()
#--------------------------- cmt-001 - 08/06/2003 ----------------------------
#--------------------- Saving and loading of preferences ---------------------
def loadHistory(self):
if not os.path.exists(self.configPath):
os.mkdir(self.configPath)
path = os.path.join(self.configPath, 'history.txt')
if UNICODE:
p = os.path.join(self.configPath, 'history.u.txt')
if os.path.exists(p):
path = p
print "Loading history from", path
try:
self.config = unrepr(open(path, 'r').read())
except:
traceback.print_exc()
self.config = {}
if 'history' in self.config:
history = self.config['history']
history.reverse()
for h in history:
self.fileHistory.AddFileToHistory(h)
if 'lastpath' in self.config:
self.lastpath = self.config['lastpath']
doc_def = {}
#insert global document defaults here
dct = {
'use_tabs':0,
'spaces_per_tab':8,
'indent':4,
'collapse':1,
'marker_margin':1,
'line_margin':1,
'col_line':78,
'col_mode':stc.STC_EDGE_LINE,
'indent_guide':0,
'showautocomp':0,
'fetch_methods':1,
'use_keywords':1,
'wrapmode':stc.STC_WRAP_NONE,
'sortmode':1,
'save_cursor':0,
'cursor_posn':0,
'whitespace':0,
'show_line_ends':0,
## 'triggers':{},
'findbarprefs':{},
'sloppy':0,
'smartpaste':0,
'showline':0,
'fetch_methods':1,
'use_keywords':1,
'ac_length':1,
'annotations_visible':2,
}
for _i in ASSOC:
doc_def[_i[2]] = dict(dct)
if _i[2] in ('xml', 'html'):
doc_def['indent'] = 2
doc_def[_i[2]]['triggers'] = {}
for (nam, dflt) in [('modulepaths', []),
## ('usesnippets', 0),
## ('usetodo', 0),
## ('paths', {}),
## ('display2code', {}),
## ('displayorder', []),
## ('shellcommands', []),
('lastopen', []),
('LASTUSED', []),
('DEFAULTLEXER', 'python'),
('FIF_STATE', ([], [], [], 0, 0, 0)),
('match_flags', wx.FR_DOWN),
('pathmarksn', []),
('workspaces', {}),
('workspace_order', []),
('SASH1', 80),
('SASH2', 300),
('LASTSIZE', (750,550)),
('LASTPOSITION', self.GetPositionTuple()),
('LASTWINDOWSTATE', 0),
('logbarlocn', 1),
('docbarlocn', 1),
('dnd_file', 1),
('caret_option', 0),
('caret_slop', 10),
('caret_multiplier', 20),
('findbarprefs', {}),
('no_findbar_history', 0),
('title_option', 0),
('document_defaults', doc_def),
('DOCUMENT_DEFAULTS', dct),
('TODOBOTTOM', 1),
('TOOLBAR', 0),
('SHOWWIDE', 1),
('SHOWTALL', 1),
('shellprefs', {}),
('findbar_location', 1),
('single_pype_instance', 0),
('DICTIONARIES', {}),
('USE_DOC_ICONS', 1),
('CARET_WIDTH', 1),
('ONE_TAB_', 1),
('always_write_bom', 1),
('document_options', 1),
('document_options2', 1),
('macro_doubleclick', 0),
('COLOUR', '#d0d0d0'),
('SHELL_OUTPUT', 0),
('SHELL_COLOR', '#d0d0d0'),
('macro_images', 1),
('show_recent', 1),
('STRICT_TODO', 0),
('python_choices', []),
('which_python', ''),
('colored_icons', 1),
('SEARCH_SASH_POSITION', 0),
('USED_TIME', 0L),
('HOW_OFTEN1', -1),
('HOW_OFTEN2', -1),
('disabled_tools', []),
('paths_to_watch', []),
('extensions_to_watch', list(set(extns))),
('show_search', 1),
('global_filter_table', 0),
('MIDDLE_PASTE', 0),
]:
if nam in self.config:
if isinstance(dflt, dict):
for k,v in dflt.iteritems():
if k not in self.config[nam]:
if isinstance(v, dict):
self.config[nam][k] = dict(v)
else:
self.config[nam][k] = v
elif isinstance(v, dict):
V = self.config[nam][k]
for k2,v2 in v.iteritems():
if k2 not in V:
V[k2] = v2
elif isinstance(dflt, dict):
self.config[nam] = dict(dflt)
else:
self.config[nam] = dflt
globals()[nam] = self.config[nam]
globals().update(dct)
globals().update(self.config.setdefault('DOCUMENT_DEFAULTS', dct))
def saveHistory(self):
LASTOPEN = []
sav = []
for win in self.control:
if win.dirname:
sav.append(self.getAlmostAbsolute(win.filename, win.dirname))
LASTOPEN.append((self.getAlmostAbsolute(win.filename, win.dirname), win.GetSaveState()))
if 'LASTOPEN' in self.config:
del self.config['LASTOPEN']
#saving document state
self.config['lastopen'] = sav
self.config['LASTUSED'] = self.lastused.items() + LASTOPEN
self.config['LASTSIZE'] = LASTSIZE
self.config['LASTPOSITION'] = LASTPOSITION
self.config['LASTWINDOWSTATE'] = self.IsMaximized()
self.config['SASH1'] = self.client2.getSize()#BOTTOM.GetSize()[1]-self.control.GetSize()[1]
self.config['SASH2'] = self.client.getSize()#self.GetSize()[0]-self.control.GetSize()[0]
## print 'savehistory sash sizes', self.config['SASH2'], self.config['SASH1']
history = []
for i in range(self.fileHistory.GetNoHistoryFiles()):
history.append(self.fileHistory.GetHistoryFile(i))
self.config['history'] = history
## a = []
## for i in self.shell.order:
## a.append(self.shell.menu[i])
## self.config['shellcommands'] = a
self.config['match_flags'] = match_flags
self.config['pathmarksn'] = self.pathmarks.op.GetLabels()
self.config['workspaces'] = workspaces
self.config['workspace_order'] = workspace_order
self.config['logbarlocn'] = logbarlocn
self.config['docbarlocn'] = docbarlocn
self.config['dnd_file'] = dnd_file
self.config['caret_option'] = caret_option
self.config['caret_slop'] = caret_slop
self.config['caret_multiplier'] = caret_multiplier
self.config['findbarprefs'] = findbarprefs
self.config['no_findbar_history'] = no_findbar_history
self.config['title_option'] = title_option
self.config['TODOBOTTOM'] = TODOBOTTOM
self.config['single_pype_instance'] = single_pype_instance
self.config['TOOLBAR'] = TOOLBAR
self.config['SHOWWIDE'] = SHOWWIDE
self.config['SHOWTALL'] = SHOWTALL
self.config['USE_DOC_ICONS'] = USE_DOC_ICONS
## self.config['shellprefs'] = self.shell.save_prefs()
self.config['findbar_location'] = findbar_location
## if self.config['usesnippets'] and (not self.restart):
## self.config['display2code'] = self.snippet.display2code
## self.config['displayorder'] = self.snippet.displayorder
self.config['lastpath'] = self.config.get('lp', current_path)
self.config['CARET_WIDTH'] = CARET_WIDTH
self.config['ONE_TAB_'] = ONE_TAB_
self.config['always_write_bom'] = always_write_bom
self.config['document_options'] = document_options
self.config['document_options2'] = document_options2
self.config['macro_doubleclick'] = macro_doubleclick
self.config['COLOUR'] = COLOUR
self.config['SHELL_OUTPUT'] = SHELL_OUTPUT
self.config['SHELL_COLOR'] = SHELL_COLOR
self.config['macro_images'] = macro_images
self.config['show_recent'] = show_recent
self.config['STRICT_TODO'] = STRICT_TODO
self.config['python_choices'] = interpreter.python_choices
self.config['which_python'] = interpreter.which_python
self.config['colored_icons'] = codetree.colored_icons
self.config['SEARCH_SASH_POSITION'] = self.findinfiles.controlsWindow.GetSashPosition()
self.config['USED_TIME'] = USED_TIME
self.config['HOW_OFTEN1'] = HOW_OFTEN1
self.config['HOW_OFTEN2'] = HOW_OFTEN2
self.config['disabled_tools'] = [i for i in window_management.possible if i not in window_management.enabled]
self.config['paths_to_watch'] = paths_to_watch
self.config['extensions_to_watch'] = extensions_to_watch
self.config['show_search'] = show_search
self.config['global_filter_table'] = global_filter_table
self.config['MIDDLE_PASTE'] = MIDDLE_PASTE
try:
if UNICODE:
path = os.sep.join([self.configPath, 'history.u.txt'])
else:
path = os.sep.join([self.configPath, 'history.txt'])
print "Saving history to", path
f = open(path, "w")
f.write(pprint.pformat(self.config))
f.close()
if UNICODE:
path = os.sep.join([self.configPath, 'menus.u.txt'])
else:
path = os.sep.join([self.configPath, 'menus.txt'])
print "Saving menus to", path
f = open(path, "w")
f.write(pprint.pformat(MENUPREF))
f.close()
except:
self.exceptDialog("Could not save preferences to %s"%path)
#------------------------- end cmt-001 - 08/06/2003 --------------------------
#----------------------------- File Menu Methods -----------------------------
def getPositionAbsolute(self, path, newf=0):
## print path
path = os.path.normcase(path)
for i in xrange(self.control.GetPageCount()):
win = self.control.GetPage(i).GetWindow1()
if newf:
if os.path.normcase(win.getshort()) == path:
return i
elif os.path.normcase(win.getlong()) == path:
return i
return -1
def selectAbsolute(self, path):
if self.isAbsOpen(path):
i = self.getPositionAbsolute(path)
if i != -1:
self.control.SetSelection(i)
def isOpen(self, fn, dn):
return dn and fn and (self.getAbsolute(fn, dn) in self.openfiles)
def isAbsOpen(self, path):
return path in self.openfiles
def makeOpen(self, fn, dn):
if fn and dn:
a = self.getAbsolute(fn, dn)
self.openfiles[a] = self.splitAbsolute(a)
self.realfn[a] = self.getAlmostAbsolute(fn, dn)
def closeOpen(self, fn, dn):
if fn and dn:
a = self.getAbsolute(fn, dn)
del self.openfiles[a]
del self.realfn[a]
def getAbsolute(self, fn, dn):
return os.path.normcase(os.path.normpath(os.path.realpath(os.path.join(dn, fn))))
def getAlmostAbsolute(self, fn, dn):
return os.path.normpath(os.path.realpath(os.path.join(dn, fn)))
def splitAbsolute(self, path):
return os.path.split(os.path.normcase(path))
def OnNew(self,e):
self.newTab('', ' ', 1)
self.control.GetPage(self.control.GetSelection()).GetWindow1().opened = 1
def OnSave(self,e,upd=1):
wnum, win = self.getNumWin(e)
if win.dirname:
# todo: we really should check the state of the file on-disk
# in order to verify that we had the proper modification time
# earlier...
try:
txt = win.GetText()
ofn = os.path.join(win.dirname, win.filename)
fil = open(ofn, 'wb')
fil.write(txt)
fil.close()
if UNICODE: a = "%s as %s"%(ofn, win.enc)
else: a = ofn
if upd:
win.mod = os.stat(ofn)[8]
self.SetStatusText("Correctly saved %s"%a)
self.curdocstates[ofn] = win.GetSaveState()
if upd:
win.MakeClean()
except cancelled:
raise
except:
self.exceptDialog("Save Failed")
raise cancelled
else:
self.OnSaveAs(e)
def OnSaveAs(self,e,upd=1):
wnum, win = self.getNumWin(e)
dlg = wx.FileDialog(self, "Save file as...", current_path, "", "All files (*.*)|*.*", wx.SAVE|wx.OVERWRITE_PROMPT, pos=(0,0))
rslt = dlg.ShowModal()
if rslt == wx.ID_OK:
fn=dlg.GetFilename()
dn=dlg.GetDirectory()
if sys.platform == 'win32' and dn[1:] == ':':
dn += '\\'
pth = self.getAlmostAbsolute(fn, dn)
dn, fn = os.path.split(pth)
if win.filename != fn or win.dirname != dn:
if self.isOpen(fn, dn):
self.dialog("Another file with that name and path is already open.\nSave aborted to prevent data corruption.", "Save Aborted!")
raise cancelled
if self.isOpen(win.filename, win.dirname):
self.closeOpen(win.filename, win.dirname)
#we do a quick GetText to make sure we don't set the file/dir names
#unless we really can get the text for the file.
x = win.GetText()
if not upd:
x,y = win.filename, win.dirname
win.filename = fn
win.dirname = dn
if upd:
self.makeOpen(fn, dn)
self.fileHistory.AddFileToHistory(pth)
try:
self.OnSave(e,upd)
finally:
if not upd:
win.filename, win.dirname = x,y
if upd:
#fix the icons and names.
self.dragger._RemoveItem(wnum)
self.dragger._InsertItem(wnum, fn)
win.MakeDirty()
win.MakeClean()
if upd:
if USE_DOC_ICONS:
self.control.SetPageImage(wnum, GDI(fn))
self.control.SetSelection(wnum)
else:
raise cancelled
def OnSaveCopyAs(self, evt):
self.OnSaveAs(evt, 0)
def OnSaveAll(self, e):
sel = self.control.GetSelection()
cnt = self.control.GetPageCount()
for i in xrange(cnt):
self.control.SetSelection(i)
try:
self.OnSave(e)
except cancelled:
pass
if cnt:
self.control.SetSelection(sel)
def OnOpen(self,e):
wd = self.config.get('lastpath', current_path)
dlg = wx.FileDialog(self, "Choose a/some file(s)...", wd, "", wildcard, wx.OPEN|wx.MULTIPLE, pos=(0,0))
if dlg.ShowModal() == wx.ID_OK:
self.OnDrop(dlg.GetPaths())
self.config['lp'] = dlg.GetDirectory()
dlg.Destroy()
def FindModule(self, mod):
fndmod = mod.split('.')
lf = len(fndmod)
pth = sys.path[:]
pth[1:1] = [current_path]
for j in range(lf):
i = fndmod[j]
fdsc = imp.find_module(i, pth)
if not (fdsc[0] is None):
fdsc[0].close()
mod = fdsc[1]
if fdsc[2][2] != imp.PY_SOURCE:
return self.dialog("%s is not python source"%mod, "not correct format for editing")
return mod
elif fdsc[1]:
pth[1:1] = [fdsc[1]]
else:
raise cancelled
#If we are outside the loop, this means that the current 'module'
#that we are on is a folder-module. We can easily load the __init__.py
#from this folder.
return os.sep.join([pth[1], '__init__.py'])
def OnOpenModule(self,e):
dlg = wx.TextEntryDialog(self, 'Enter the module name you would like to open', 'Open module...', pos=(0,0))
if dlg.ShowModal() == wx.ID_OK:
mod = dlg.GetValue()
else:
mod = ''
dlg.Destroy()
if mod:
sp = sys.path[:]
sys.path.extend(self.config['modulepaths'])
try:
self.OnDrop([self.FindModule(mod)])
except:
self.dialog("module %s not found"%mod, "not found")
sys.path = sp
def OnOpenPrevDocs(self, e):
if "lastopen" in self.config:
self.OnDrop(self.config['lastopen'], 1)
def AddSearchPath(self, e):
dlg = wx.DirDialog(self, "Choose a path", "", style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON, pos=(0,0))
if dlg.ShowModal() == wx.ID_OK:
path = os.path.normcase(os.path.normpath(dlg.GetPath()))
if not (path in self.config['modulepaths']) and not (path in sys.path):
self.config['modulepaths'].append(path)
def OnNewPythonShell(self, e):
self.newTab("", " ", 1, 1)
def OnNewCommandShell(self, e):
self.newTab("", " ", 1, 2)
def OnRunCurrentFile(self, e, interact=0):
win = self.getNumWin(e)[1]
if not win.dirname:
self.SetStatusText("Error: can't start unnamed file")
return
extn = win.filename.split('.')[-1]
fn = win.filename
if ' ' in fn:
fn = '"%s"'%fn
dir = win.dirname
if extn in ('py', 'pyw'):
#if we don't run via a command shell, then either sometimes we
#don't get wx GUIs, or sometimes we can't kill the subprocesses
inte = ('', '-i')[bool(interact)]
if sys.platform == 'win32':
cmd = 'cmd /c '
else:
cmd = ''
## cmd = 'sh --noediting -c '
cmd += 'python -u %s %s'%(inte, fn.replace('"', '\\"'))
elif extn in ('tex',):
cmd = 'pdflatex %s'%fn
elif extn in ('htm', 'html', 'shtm', 'shtml'):
return webbrowser.open(os.path.join(dir, fn))
else:
self.SetStatusText("Error: I don't know how to run file type: %r"%extn)
return
data = (dir, cmd)
i = -1
for i,j in enumerate(self.control):
if not isinstance(j, PythonSTC) and not j.filter and not j.restartable and j.restart:
#we found a re-usable command console
self.control.SetSelection(i)
break
else:
#we need to create a new command console
i += 1
j = None
self.newTab('', ' ', 1, 3)
k = [j]
def run_shell():
j = k[0]
if j is None:
j = self.control.GetPage(i).GetWindow1()
j._Restart(data)
interpreter.FutureCall(25, run_shell)
def OnRunCurrentFileI(self, e):
return self.OnRunCurrentFile(e, 1)
def OnRunSelected(self, e):
win = self.getNumWin(e)[1]
win.lines.selectedlinesi = win.lines.selectedlinesi
#get the lines if we don't already have some
data = ''.join(win.lines.selectedlines)
data = win._StripPrefix(data, 0, 1)
if not data.strip():
print "no data!"
return
#copy the text to the clipboard
if not SetClipboardText(data):
print "no clipboard!"
return
#find some Python shell
i = -1
for i,j in enumerate(self.control):
if not isinstance(j, PythonSTC) and j.filter == 1:
#we found a usable Python shell
self.control.SetSelection(i)
break
else:
#we need to create a new Python shell
i += 1
j = None
self.newTab('', ' ', 1, 1)
k = [j]
def run_copied():
j = k[0]
if j is None:
j = self.control.GetPage(i).GetWindow1()
j.SetSelection(j.promptPosEnd, j.GetTextLength())
j.ReplaceSelection('')
j.Paste()
interpreter.FutureCall(25, run_copied)
@auto_thaw
def newTab(self, d, fn, switch=0, shell=0):
if 'lastpath' in self.config:
del self.config['lastpath']
#ctrlwidth, ctrlh = self.control.GetSizeTuple()
if d:
d, fn = os.path.split(self.getAlmostAbsolute(fn, d))
FN = self.getAlmostAbsolute(fn, d)
f = open(FN, 'rb')
txt = f.read()
f.close()
else:
fn = ' '
FN = ''
txt = ''
split = SplitterWindow(self.control, wx.NewId(), style=wx.SP_NOBORDER)
split.SetMinimumPaneSize(0)
wx.EVT_SPLITTER_SASH_POS_CHANGING(self, split.GetId(), veto)
ftype = extns.get(fn.split('.')[-1].lower(), 'python')
## if ftype in document_defaults:
## print "found filetype-specific defaults", ftype
## else:
## print "could not find", ftype
state = dict(document_defaults.get(ftype, DOCUMENT_DEFAULTS))
if not shell:
nwin = PythonSTC(self.control, wx.NewId(), split)
else:
state = dict(state)
state['wrapmode'] = 1
state['whitespace'] = 0
nwin = interpreter.MyShell(split, wx.NewId(), self, None, shell)
nwin.filename = fn
nwin.dirname = d
if shell < 2:
nwin.changeStyle(stylefile, self.style(fn))
else:
#we don't want to syntax highlight by default for non-python shells.
nwin.changeStyle(stylefile, self.style('a.txt'))
used_default = True
try:
if d:
nwin.mod = os.stat(FN)[8]
if len(txt) == 0:
nwin.format = eol
nwin.SetText('')
else:
nwin.format = parsers.detectLineEndings(txt)
nwin.SetText(txt)
#if FN in self.config['LASTOPEN']:
# state = self.config['LASTOPEN'][FN]
if FN in self.lastused:
_ = self.lastused[FN]
__ = _.pop('triggers', None)
state.update(_)
del _, __, self.lastused[FN]
used_default = False
else:
state['CHECK_VIM'] = None
else:
nwin.mod = None
nwin.format = eol
nwin.SetText(txt)
except UnicodeDecodeError:
nwin.Destroy()
split.Destroy()
self.exceptDialog()
return
## print 2
if not ((d == '') and (fn == ' ')):
self.fileHistory.AddFileToHistory(os.path.join(d, fn))
if 'checksum' in state:
if md5.new(txt).hexdigest() != state['checksum']:
## print "mismatched checksum"
state.update(RESET)
else:
## print "no checksum", fn
state.update(RESET)
if FN:
self.curdocstates[FN] = state
if used_default and nwin.GetTextLength() < 200000:
# try to detect the "true" defaults
state['use_tabs'], state['spaces_per_tab'], state['indent'] = \
parsers.detectLineIndent(nwin.lines, state['use_tabs'], state['spaces_per_tab'], state['indent'])
## print "detected", state['use_tabs'], state['spaces_per_tab'], state['indent']
nwin.SetSaveState(state)
## print 3
if fn == ' ':
## print 3.5
globals()['NEWDOCUMENT'] += 1
nwin.NEWDOCUMENT = NEWDOCUMENT
nwin.docstate = docstate(self, nwin)
## print 4
split.Initialize(nwin)
## print 5
shortname = nwin.getshort()
## print 'Adding page with name:', shortname
self.control.AddPage(split, shortname, switch)
if switch:
wx.CallAfter(self.control.SetSelection, self.control.GetPageCount()-1)
nwin.MakeClean()
## self.OnRefresh(None, nwin)
self.updateWindowTitle()
if switch:
nwin.SetFocus()
## self.OnDocumentChange(nwin)
self.docpanel._refresh()
wx.CallAfter(self._updateChecks)
pubsub.publish('document.open', stc_id=id(nwin))
return nwin.enc
def OnReload(self, e, win=None):
if win == None:
num, win = self.getNumWin(e)
if not e is None:
dlg = wx.MessageDialog(self, "%s was modified after last save.\nReloading from disk will destroy all changes.\n\nContinue anyway?"%win.filename, 'File was modified, data loss may occur!', wx.YES_NO|wx.CANCEL, pos=(0,0))
a = dlg.ShowModal()
if a == wx.ID_CANCEL:
raise cancelled
elif a == wx.ID_NO:
return
self._reload_file(win.filename, win.dirname)
def _reload_file(self, filename, dirname):
try:
FN = self.getAlmostAbsolute(filename, dirname)
posn = self.getPositionAbsolute(self.getAbsolute(filename, dirname))
win = self.control.GetPage(posn).GetWindow1()
fil = open(FN, 'rb')
txt = fil.read()
fil.close()
win.BeginUndoAction()
try:
win.SetText(txt, 0)
finally:
win.EndUndoAction()
win.mod = os.stat(FN)[8]
win.SetSavePoint()
win.MakeClean()
self.curdocstates[FN] = {'checksum':md5.new(txt).hexdigest()}
## self.OnRefresh(None, win)
except:
self.exceptDialog("Reload failed")
## self.dialog("Error encountered while trying to reload from disk.", "Reload failed")
def sharedsave(self, win, force=0):
nam = win.filename
ex = wx.CANCEL*bool(not force)
if not win.dirname.strip():
nam = "<untitled %i>"%win.NEWDOCUMENT
a = self.dialog("%s was modified after last save.\nSave changes before closing?"%nam,\
"Save changes?", wx.YES_NO|ex, pos=(0,0))
if a == wx.ID_CANCEL:
raise cancelled
elif a == wx.ID_NO:
return 0
else:
self.OnSave(None)
return 1
def OnClose(self, e, wnum=None, win=None):
if wnum is None or win is None:
wnum, win = self.getNumWin(e)
fn = self.getAlmostAbsolute(win.filename, win.dirname)
if isdirty(win):
for i, w in enumerate(self.control):
if w is win:
self.control.SetSelection(i)
break
if win.GetParent().IsSplit():
f = win.GetParent().GetWindow2()
if f.replacing:
f.loop = 1
del f
saved = self.sharedsave(win)
elif self.isOpen(win.filename, win.dirname):
#only save difference between the document state and the default
#state for this document...
ftype = extns.get(win.filename.split('.')[-1].lower(), 'python')
dflt = document_defaults.get(ftype, DOCUMENT_DEFAULTS)
x = win.GetSaveState()
for i in x.keys():
if i in dflt and x[i] == dflt[i]:
del x[i]
if DEBUG: print "shared default", i
self.curdocstates[fn] = x
if self.isOpen(win.filename, win.dirname):
self.lastused[fn] = self.curdocstates.pop(fn, {})
self.closeOpen(win.filename, win.dirname)
self.SetStatusText("Closed %s"%self.getAlmostAbsolute(win.filename, win.dirname))
else:
self.SetStatusText("Closed unnamed file without saving")
if self.gf:
self.gf.close_hierarchy(win)
if hasattr(win, "kill"):
win.kill()
if hasattr(win, 't'):
win.t.Stop()
win.t2.Stop()
pubsub.publish('document.close', stc_id=id(win))
self.control.DeletePage(wnum)
self.updateWindowTitle()
self.docpanel._refresh()
wx.CallAfter(self._updateChecks)
def OnRestart(self, e):
self.OnExit(e, 0)
_restart()
def OnExit(self, e, force_exit=1):
try: e.SetCanVeto(1) #try make this vetoable
except: pass
force_user = not getattr(e, 'CanVeto', lambda:1)()
if self.closing:
return e.Skip()
self.closing = 1
cnt = self.control.GetPageCount()
sel = self.control.GetSelection()
try:
for i in xrange(cnt):
win = self.control.GetPage(i).GetWindow1()
if isdirty(win):
self.control.SetSelection(i)
self.sharedsave(win, force_user)
else:
self.curdocstates[self.getAlmostAbsolute(win.filename, win.dirname)] = win.GetSaveState()
except cancelled:
self.closing = 0
if sel > -1:
self.control.SetSelection(sel)
try: return e.Veto()
except: return
self.saveHistory()
parse_queue.put(None)
file_mods_to_check.put((None, None))
ShutdownScheduler()
documents.die = None
if sel > -1:
self.control.SetSelection(sel)
self.Close(True)
if force_exit:
os._exit(0)
#--------------------------- cmt-001 - 08/06/2003 ----------------------------
#------------- Open the file selected from the file history menu -------------
def OnFileHistory(self, e):
fileNum = e.GetId() - wx.ID_FILE1
path = self.fileHistory.GetHistoryFile(fileNum)
self.OnDrop([path])
#------------------------- end cmt-001 - 08/06/2003 --------------------------
#----------------------------- Edit Menu Methods -----------------------------
def OneCmd(self, funct_name, evt):
wnum, win = self.getNumWin(evt)
ff = self.FindFocus()
if ff != win:
if isinstance(ff, (wx.ComboBox, wx.TextCtrl)):
if isinstance(ff, wx.ComboBox):
gm, sm = ff.GetMark, ff.SetMark
else:
gm, sm = ff.GetSelection, ff.SetSelection
if funct_name == 'DeleteSelection':
return ff.Remove(*gm())
elif funct_name == 'SelectAll':
return sm(0, ff.GetLastPosition())
elif sys.platform == 'win32':
if hasattr(ff, 'Can'+funct_name) and getattr(ff, 'Can'+funct_name)():
return getattr(ff, funct_name)()
return
else:
return getattr(ff, funct_name)()
return evt.Skip()
getattr(win, funct_name)()
def OnUndo(self, e):
self.OneCmd('Undo',e)
def OnRedo(self, e):
self.OneCmd('Redo',e)
def OnSelectAll(self, e):
self.OneCmd('SelectAll',e)
def OnCut(self, e):
self.OneCmd('Cut',e)
def OnCopy(self, e):
self.OneCmd('Copy',e)
def OnPaste(self, e):
self.OneCmd('Paste',e)
def OnDeleteSelection(self, e):
self.OneCmd('DeleteSelection',e)
def OnPasteAndDown(self, e):
self.OneCmd('PasteAndDown',e)
def OnPasteRectangular(self, e):
self.OneCmd('PasteRectangular',e)
def OnDeleteRight(self, e):
self.OneCmd('DeleteRight',e)
def OnDeleteLine(self, e):
self.OneCmd('DeleteLine',e)
#----------------------- Find and Replace Bar Display ------------------------
def getNumWin(self, e=None):
num = self.control.GetSelection()
if num >= 0:
return num, self.control.GetPage(num).GetWindow1()
if e:
e.Skip()
raise cancelled
def OnMiddleClickToggle(self, evt):
global MIDDLE_PASTE
MIDDLE_PASTE = not MIDDLE_PASTE
def OnShowFindbar(self, evt):
num, win = self.getNumWin(evt)
if win.parent.IsSplit() and not isinstance(win.parent.GetWindow2(), findbar.FindBar):
win.parent.GetWindow2().close()
if not win.parent.IsSplit():
bar = findbar.FindBar(win.parent, self)
win.parent.SplitHorizontally(win, bar, -(bar.GetBestSize())[1]-5, 1-findbar_location)
bar = win.parent.GetWindow2()
focused = self.FindFocus()
hasfocus = (focused == bar) or (focused and focused.GetParent() == bar)
self.commonbar(win)
if hasfocus:
bar.OnFindN(evt)
def OnShowReplacebar(self, evt):
num, win = self.getNumWin(evt)
if win.parent.IsSplit() and isinstance(win.parent.GetWindow2(), findbar.FindBar):
win.parent.GetWindow2().close()
if not win.parent.IsSplit():
bar = findbar.ReplaceBar(win.parent, self)
win.parent.SplitHorizontally(win, bar, -(bar.GetBestSize())[1]-5, 1-findbar_location)
self.commonbar(win)
def commonbar(self, win):
st,end = win.GetSelection()
box = win.parent.GetWindow2().box1
if st == end and box.GetLastPosition() == 0:
gcp = win.GetCurrentPos()
st = win.WordStartPosition(gcp, 1)
end = win.WordEndPosition(gcp, 1)
if st != end:
x = win.GetTextRange(st, end)
try:
x = str(x)
except UnicodeError:
pass
if not isinstance(x, unicode):
rx = x.encode('string-escape')
if rx != x:
x = repr(x)
box.SetValue(x)
win.SetSelection(st, end)
box.SetFocus()
if isinstance(box, wx.TextCtrl):
box.SetSelection(0, box.GetLastPosition())
else:
box.SetMark(0, len(box.GetValue()))
def OnFindAgain(self, evt):
num, win = self.getNumWin(evt)
if win.parent.IsSplit():
win.parent.GetWindow2().OnFindN(evt)
else:
try:
prefs = win.findbarprefs
except:
prefs = {}
if prefs.get('find',[]):
bar = findbar.FindBar(win.parent, self)
win.parent.SplitHorizontally(win, bar, -(bar.GetBestSize())[1]-5, 1-findbar_location)
win.parent.GetWindow2().OnFindN(evt)
win.SetFocus()
#----------------------------- View Menu Methods -----------------------------
def OnZoom(self, e):
wnum, win = self.getNumWin(e)
if e.GetId() == ZI:incr = 1
else: incr = -1
win.SetZoom(win.GetZoom()+incr)
def OnGoto(self, e):
wnum, win = self.getNumWin(e)
valu = self.getInt('Which line would you like to advance to?', '', win.LineFromPosition(win.GetSelection()[0])+1)
win.GotoLineS(valu)
def OnGotoP(self, e):
wnum, win = self.getNumWin(e)
x = win.GetSelection()[0]
valu = 0
while x > 0:
y, x = x, win.PositionBefore(x)
valu += len(win.GetTextRange(y,x))
valu = self.getInt('What position would you like to advance to?', '', valu)
length = win.GetLength()
x = 0
while valu > 0 and x < length:
y, x = x, win.PositionAfter(x)
valu -= len(win.GetTextRange(y,x))
if not valu:
win.SetSelection(x, x)
def OnRefresh(self, e, win=None):
if win is None:
num, win = self.getNumWin(e)
self.OnDocumentChange(win, True)
def OnToggleBookmark(self, e):
wnum, win = self.getNumWin(e)
lineNo = win.GetCurrentLine()
if win.MarkerGet(lineNo) & NOTIFICATIONMASK:
win.MarkerDelete(lineNo, NOTIFICATIONNUMBER)
elif win.MarkerGet(lineNo) & BOOKMARKMASK:
win.MarkerDelete(lineNo, BOOKMARKNUMBER)
else:
win.MarkerAdd(lineNo, BOOKMARKNUMBER)
def OnNextBookmark(self, e):
wnum, win = self.getNumWin(e)
lineNo = win.GetCurrentLine()
newLineNo = win.MarkerNext(lineNo + 1, BOOKMARKMASK)
if newLineNo != -1:
win.GotoLine(newLineNo)
else:
lineNo = win.GetLineCount()
newLineNo = win.MarkerNext(0, BOOKMARKMASK)
if newLineNo != -1:
win.GotoLine(newLineNo)
win.EnsureVisible(win.GetCurrentLine())
win.EnsureCaretVisible()
def OnPreviousBookmark(self, e):
wnum, win = self.getNumWin(e)
lineNo = win.GetCurrentLine()
newLineNo = win.MarkerPrevious(lineNo - 1, BOOKMARKMASK)
if newLineNo != -1:
win.GotoLine(newLineNo)
else:
lineNo = win.GetLineCount()
newLineNo = win.MarkerPrevious(lineNo, BOOKMARKMASK)
if newLineNo != -1:
win.GotoLine(newLineNo)
win.EnsureVisible(win.GetCurrentLine())
win.EnsureCaretVisible()
def OnClearNotifications(self, e):
wnum, win = self.getNumWin(e)
if win:
win.UpdateNotifications([])
win.AnnotationClearAll()
def OnLeft(self, e):
if self.control.GetSelection() == 0:
self.control.SetSelection(self.control.GetPageCount() - 1)
else:
self.control.AdvanceSelection(False)
def OnRight(self, e):
pc = self.control.GetPageCount()
if pc and self.control.GetSelection() == (pc - 1):
self.control.SetSelection(0)
else:
self.control.AdvanceSelection(True)
def OnFindDefn(self, e):
if 'filter' not in window_management.enabled:
self.SetStatusText("Error: you must enable the filter in 'Options -> Tool Options' to use this feature")
return
num, win = self.getNumWin(e)
if hasattr(self, 'single_ctrl'):
x = self.single_ctrl
else:
x = self.RIGHTNB
for i in xrange(x.GetPageCount()):
if x.GetPage(i) == self.filterl:
x.SetSelection(i)
break
gcp = win.GetCurrentPos()
st = win.WordStartPosition(gcp, 1)
end = win.WordEndPosition(gcp, 1)
f = win.docstate.filter
f.cs.SetValue(1)
f.filter.SetValue(win.GetTextRange(st, end))
f.how.SetValue('exact')
f.update()
f.filter.SetFocus()
def OnSplitW(self, e):
self._OnSplit(self.altview)
def OnSplitT(self, e):
self._OnSplit(self.altview2)
def _OnSplit(self, alt):
num, win = self.getNumWin()
alt.SetDocPointer(NULLDOC) #reset the pointer first
alt.SetDocPointer(win.GetDocPointer())
x = win.GetSaveState(1)
del x['FOLD']
alt.SetSaveState(x)
alt.SetLexer(win.GetLexer())
alt.changeStyle(stylefile, self.style(win.filename))
for i in xrange(alt.parent.GetPageCount()):
if alt.parent.GetPage(i) is alt:
alt.parent.SetSelection(i)
break
if not alt.parent.GetParent().IsSplit():
alt.parent.GetParent().Split()
def OnUnsplit(self, e):
self.altview.SetDocPointer(NULLDOC)
self.altview2.SetDocPointer(NULLDOC)
#--------------------------- Document Menu Methods ---------------------------
def OnStyleChange(self,e):
wnum, win = self.getNumWin(e)
lang = lexers[e.GetId()]
win.changeStyle(stylefile, lang)
win.triggers = document_defaults[lang]['triggers']
wx.CallAfter(self.control.updateChecks, win)
def style(self, fn):
ext = fn.split('.')[-1].lower()
return extns.get(ext, DEFAULTLEXER)
def OnEncChange(self, e):
num, win = self.getNumWin(e)
mid = e.GetId()
newenc = self.menubar.GetLabel(mid)
oldenc = win.enc
if oldenc != newenc:
win.enc = newenc.strip()
self.SetStatusText("encoding changed to %s for %s"%(win.enc,
win.filename.strip() or self.control.GetPageText(num).strip(' *')))
self.SetStatusText(win.enc, 2)
wx.CallAfter(self.control.updateChecks, win)
def OnLineEndChange(self, e):
n, win = self.getNumWin(e)
endid = e.GetId()
newend = LE_MAPPING[endid][0]
oldend = win.GetEOLMode()
if oldend != newend:
win.format = fmt_Rmode[newend]
win.ConvertEOLs(newend)
win.SetEOLMode(newend)
wx.CallAfter(self.control.updateChecks, win)
def OnAutoCompleteToggle(self, event):
# Images are specified with an appended "?type"
#for i in range(len(kw)):
# if kw[i] in keyword.kwlist:
# kw[i] = kw[i]# + "?1"
n, win = self.getNumWin(event)
win.showautocomp = not win.showautocomp
self.control.updateChecks(win)
def OnUseMethodsToggle(self, e):
n, win = self.getNumWin(e)
win.fetch_methods = not win.fetch_methods
def OnUseKeywordsToggle(self, e):
n, win = self.getNumWin(e)
win.use_keywords = not win.use_keywords
def OnAutocompleteLength(self, e):
n, win = self.getNumWin(e)
rslt = self.getInt("Autocomplete Length",
"How many characters must be typed in order for\n"\
"autocomplete to offer suggestions? Enter an integer > 0.",
win.ac_length)
win.ac_length = rslt
def OnNumberToggle(self, e):
n, win = self.getNumWin(e)
win.SetMarginWidth(0, not win.GetMarginWidth(0))
def OnMarginToggle(self, e):
n, win = self.getNumWin(e)
win.SetMarginWidth(1, (win.GetMarginWidth(1)+16)%32)
def OnIndentGuideToggle(self, e):
n, win = self.getNumWin(e)
win.SetIndentationGuides(not win.GetIndentationGuides())
def OnWhitespaceToggle(self, e):
n, win = self.getNumWin(e)
win.SetViewWhiteSpace(not win.GetViewWhiteSpace())
def OnLineEndingToggle(self, e):
n, win = self.getNumWin(e)
win.SetViewEOL(not win.GetViewEOL())
def OnSavePositionToggle(self, e):
n, win = self.getNumWin(e)
win.save_cursor = not win.save_cursor
def HightlightLineToggle(self, e):
n, win = self.getNumWin(e)
win.SetCaretLineVisible(not win.GetCaretLineVisible())
def AnnotationsToggle(self, e):
n, win = self.getNumWin(e)
win.AnnotationSetVisible((not win.AnnotationGetVisible())*2)
def OnExpandAll(self, e):
n, win = self.getNumWin(e)
lc = win.GetLineCount()
win.ShowLines(0, lc-1)
for line in xrange(lc):
if win.GetFoldLevel(line) & stc.STC_FOLDLEVELHEADERFLAG:
win.SetFoldExpanded(line, 1)
def OnFoldAll(self, e):
n, win = self.getNumWin(e)
#these next two lines are to allow
#win.GetFoldLevel() to be accurate
win.HideLines(0, win.GetLineCount()-1)
try: wx.Yield()
except: pass
#toss all the old folds
self.OnExpandAll(e)
lc = win.GetLineCount()
lines = []
for line in xrange(lc):
if win.GetFoldLevel(line) & stc.STC_FOLDLEVELHEADERFLAG:
lines.append(line)
lines.reverse()
for line in lines:
a = win.GetLastChild(line, -1)
win.HideLines(line+1,a)
win.SetFoldExpanded(line, 0)
def OnSetTabToggle(self, e):
n, win = self.getNumWin(e)
a = win.GetUseTabs()
win.SetUseTabs((a+1)%2)
win.SetProperty("tab.timmy.whinge.level", str(a))
def OnWrapL(self, e):
wnum, win = self.getNumWin(e)
self.WrapToggle(win)
def OnSloppy(self, e):
wnum, win = self.getNumWin(e)
win.sloppy = not win.sloppy
def OnSmartPaste(self, e):
wnum, win = self.getNumWin(e)
win.smartpaste = not win.smartpaste
def WrapToggle(self, win):
#tossing the current home/end key configuration, as it will change
win.CmdKeyClear(stc.STC_KEY_HOME,0)
win.CmdKeyClear(stc.STC_KEY_HOME,stc.STC_SCMOD_SHIFT)
win.CmdKeyClear(stc.STC_KEY_HOME,stc.STC_SCMOD_ALT)
win.CmdKeyClear(stc.STC_KEY_HOME,stc.STC_SCMOD_ALT|stc.STC_SCMOD_SHIFT)
win.CmdKeyClear(stc.STC_KEY_END,0)
win.CmdKeyClear(stc.STC_KEY_END,stc.STC_SCMOD_SHIFT)
win.CmdKeyClear(stc.STC_KEY_END,stc.STC_SCMOD_ALT)
win.CmdKeyClear(stc.STC_KEY_END,stc.STC_SCMOD_ALT|stc.STC_SCMOD_SHIFT)
if win.GetWrapMode() == stc.STC_WRAP_NONE:
win.SetWrapMode(stc.STC_WRAP_WORD)
#making home and end work like we expect them to when lines are wrapped
win.CmdKeyAssign(stc.STC_KEY_HOME, 0, stc.STC_CMD_HOMEDISPLAY)
win.CmdKeyAssign(stc.STC_KEY_HOME, stc.STC_SCMOD_SHIFT, stc.STC_CMD_HOMEDISPLAYEXTEND)
win.CmdKeyAssign(stc.STC_KEY_HOME, stc.STC_SCMOD_ALT, stc.STC_CMD_VCHOME)
win.CmdKeyAssign(stc.STC_KEY_HOME, stc.STC_SCMOD_ALT|stc.STC_SCMOD_SHIFT, stc.STC_CMD_VCHOMEEXTEND)
win.CmdKeyAssign(stc.STC_KEY_END, 0, stc.STC_CMD_LINEENDDISPLAY)
win.CmdKeyAssign(stc.STC_KEY_END, stc.STC_SCMOD_SHIFT, stc.STC_CMD_LINEENDDISPLAYEXTEND)
win.CmdKeyAssign(stc.STC_KEY_END, stc.STC_SCMOD_ALT, stc.STC_CMD_LINEEND)
win.CmdKeyAssign(stc.STC_KEY_END, stc.STC_SCMOD_ALT|stc.STC_SCMOD_SHIFT, stc.STC_CMD_LINEENDEXTEND)
else:
win.SetWrapMode(stc.STC_WRAP_NONE)
#making home and end work like we expect them to when lines are not wrapped
win.CmdKeyAssign(stc.STC_KEY_HOME, 0, stc.STC_CMD_VCHOME)
win.CmdKeyAssign(stc.STC_KEY_HOME, stc.STC_SCMOD_SHIFT, stc.STC_CMD_VCHOMEEXTEND)
win.CmdKeyAssign(stc.STC_KEY_HOME, stc.STC_SCMOD_ALT, stc.STC_CMD_HOMEDISPLAY)
win.CmdKeyAssign(stc.STC_KEY_HOME, stc.STC_SCMOD_ALT|stc.STC_SCMOD_SHIFT, stc.STC_CMD_HOMEDISPLAYEXTEND)
win.CmdKeyAssign(stc.STC_KEY_END, 0, stc.STC_CMD_LINEEND)
win.CmdKeyAssign(stc.STC_KEY_END, stc.STC_SCMOD_SHIFT, stc.STC_CMD_LINEENDEXTEND)
win.CmdKeyAssign(stc.STC_KEY_END, stc.STC_SCMOD_ALT, stc.STC_CMD_LINEENDDISPLAY)
win.CmdKeyAssign(stc.STC_KEY_END, stc.STC_SCMOD_ALT|stc.STC_SCMOD_SHIFT, stc.STC_CMD_LINEENDDISPLAYEXTEND)
def OnSetTriggers(self, e):
num, win = self.getNumWin(e)
## print win.triggers
a = triggerdialog.TriggerDialog(self, win, win.triggers)
a.ShowModal()
def OnSetIndent(self, e):
n, win = self.getNumWin(e)
rslt = self.getInt("How many spaces per indent level?", "Enter an integer > 0.",
win.GetIndent())
win.SetIndent(rslt)
def OnSetTabWidth(self, e):
n, win = self.getNumWin(e)
rslt = self.getInt("How many spaces per tab?",
"How many spaces should a tab character,\n"\
"'\\t' represent? Enter an integer > 0.",
win.GetTabWidth())
win.SetTabWidth(rslt)
def OnSetLongLinePosition(self, e):
n, win = self.getNumWin(e)
rslt = self.getInt("Long Line Indicator",
"At what column would you like a long line\n"\
"signifier to be displayed? Enter an integer > 0.",
win.GetEdgeColumn())
win.SetEdgeColumn(rslt)
def OnSetLongLineMode(self, e):
n, win = self.getNumWin(e)
eid = e.GetId()
win.SetEdgeMode(LL_MAPPING[eid][0])
wx.CallAfter(self.control.updateChecks, win)
#--------------------------- Options Menu Methods ----------------------------
def OnSaveLang(self, e):
mid = e.GetId()
lang, desc = SOURCE_ID_TO_OPTIONS.get(mid, ('python', ''))
n, win = self.getNumWin()
dct = win.GetSaveState()
dct.pop('BM', None)
dct.pop('FOLD', None)
dct.pop('checksum', None)
dct.pop('cursor_posn', None)
document_defaults[lang].update(dct)
self.SetStatusText("Updated document defaults for " + desc)
def OnLoadSavedLang(self, e):
mid = e.GetId()
lang, desc = SOURCE_ID_TO_OPTIONS2.get(mid, ('python', ''))
n, win = self.getNumWin()
dct = win.GetSaveState()
dct.update(document_defaults[lang])
s,e = win.GetSelection()
win.SetSaveState(dct)
win.SetSelection(s,e)
self.control.updateChecks(win)
self.SetStatusText("Updated document settings to %s for %s"%(desc, os.path.join(win.dirname, win.filename)))
def OnDefaultStyleChange(self, e):
dl = lexers[e.GetId()]
self.config['DEFAULTLEXER'] = dl
globals()['DEFAULTLEXER'] = dl
wx.CallAfter(self.control.updateChecks, None)
def OnSaveSettings(self, e):
#unused right now.
n, win = self.getNumWin()
dct = win.GetSaveState()
del dct['BM']
del dct['FOLD']
del dct['checksum']
globals().update(dct)
self.config['DOCUMENT_DEFAULTS'] = dct
def OnDNDToggle(self, e):
global dnd_file
dnd_file = not dnd_file
def OnIconToggle(self, e):
global USE_DOC_ICONS
USE_DOC_ICONS = not USE_DOC_ICONS
def OnMethodColorToggle(self, e):
codetree.colored_icons = not codetree.colored_icons
self.OnRefresh(None)
def OnLogBarToggle(self, e):
global logbarlocn
logbarlocn = not logbarlocn
if self.BOTTOM.IsSplit():
self.BOTTOM.swapit()
def OnDocBarToggle(self, e):
global docbarlocn
docbarlocn = not docbarlocn
if self.RIGHT.IsSplit():
self.RIGHT.swapit()
def OnShowWideToggle(self, e):
global SHOWWIDE
SHOWWIDE = not SHOWWIDE
if SHOWWIDE:
self.client2.Split()
## self.BOTTOM.Show()
else:
self.client2.Unsplit()
## self.BOTTOM.Hide()
self.OnSize(None)
self.menubar.Check(WIDE_ID, SHOWWIDE)
def OnShowTallToggle(self, e):
global SHOWTALL
SHOWTALL = not SHOWTALL
if SHOWTALL:
self.client.Split()
## self.RIGHT.Show()
else:
self.client.Unsplit()
## self.RIGHT.Hide()
self.OnSize(None)
self.menubar.Check(TALL_ID, SHOWTALL)
def OnOneTabToggle(self, e):
global ONE_TAB_
ONE_TAB_ = not ONE_TAB_
def OnSingleToggle(self, e):
global single_pype_instance
if single_pype_instance:
single_instance.shutdown()
try:
x = open(os.path.join(runpath, 'nosocket'), 'w')
x.close()
except:
pass
single_pype_instance = 0
else:
try:
os.remove(os.path.join(runpath, 'nosocket'))
except:
if nosocket:
self.menubar.Check(SINGLE_ID, single_pype_instance)
return
try:
single_instance.startup()
except:
single_instance.traceback.print_exc()
self.menubar.Check(SINGLE_ID, single_pype_instance)
else:
single_pype_instance = 1
def OnTodoToggle(self, e):
global TODOBOTTOM
TODOBOTTOM = not TODOBOTTOM
def OnStrictTodoToggle(self, e):
global STRICT_TODO
STRICT_TODO = not STRICT_TODO
def OnBOMToggle(self, e):
global always_write_bom
always_write_bom = not always_write_bom
def OnToolBar(self, e):
global TOOLBAR
TOOLBAR = TB_MAPPING[e.GetId()][0]
self.SetStatusText("To apply your changed toolbar settings, restart PyPE.")
wx.CallAfter(self.control.updateChecks, None)
def OnCaret(self, e):
global caret_option
i = e.GetId()
caret_option, flags = CARET_ID_TO_OPTIONS[i][:2]
wx.CallAfter(self.control.updateChecks, None)
self.SharedCaret()
def OnCaretM(self, e):
global caret_slop
caret_slop = self.getInt("Set Caret M Value", "", caret_slop)
self.SharedCaret()
def OnCaretN(self, e):
global caret_multiplier
caret_multiplier = self.getInt("Set Caret N Value", "", caret_multiplier)
self.SharedCaret()
def OnCaretWidth(self, e):
global CARET_WIDTH
CARET_WIDTH = CARET_W_OPTION_TO_W.get(e.GetId(), 1)
for i in CARET_W_OPTION_TO_W:
self.menubar.Check(i, 0)
self.menubar.Check(e.GetId(), 1)
num, win = self.getNumWin(e)
win.SetCaretWidth(CARET_WIDTH)
def OnBrowseInterpreter(self, e):
wd = os.getcwd()
dlg = wx.FileDialog(
self, message="Choose a Python Interpreter", defaultDir=wd,
defaultFile="", wildcard="All files (*.*)|*.*",
style=wx.OPEN|wx.HIDE_READONLY|wx.FILE_MUST_EXIST, pos=(0,0)
)
x = interpreter.python_choices[:]
if dlg.ShowModal() == wx.ID_OK:
interpreter.check_paths(dlg.GetPaths())
dlg.Destroy()
for i in interpreter.python_choices:
if i not in x:
self.AddPythonOption(i, i==interpreter.which_python)
def AddPythonOption(self, name, select=0):
if select:
for i in PYTHON_INTERPRETER_CHOICES:
self.menubar.Check(i, 0)
nid = wx.NewId()
PYTHON_INTERPRETER_CHOICES.append(nid)
menuAdd(self, self.python_choices, name, "Will use %s as the interpreter for the 'Python Shell' when checked"%name, self.OnChoosePython, nid, wx.ITEM_CHECK)
self.menubar.Check(nid, select)
def OnChoosePython(self, e):
for i in PYTHON_INTERPRETER_CHOICES:
self.menubar.Check(i, 0)
self.menubar.Check(e.GetId(), 1)
interpreter.which_python = self.menubar.GetLabel(e.GetId()).strip()
def OnShellStyle(self, e):
global SHELL_OUTPUT
for i in SHELL_OUTPUT_OPTIONS:
self.menubar.Check(i, 0)
self.menubar.Check(e.GetId(), 1)
SHELL_OUTPUT = SHELL_OUTPUT_OPTIONS[e.GetId()][0]
def OnShellColor(self, e):
global SHELL_COLOR
data = wx.ColourData()
data.SetChooseFull(True)
data.SetColour(SHELL_COLOR)
dlg = wx.ColourDialog(self, data, pos=(0,0))
changed = dlg.ShowModal() == wx.ID_OK
if changed:
c = dlg.GetColourData().GetColour()
SHELL_COLOR = '#%02x%02x%02x'%(c.Red(), c.Green(), c.Blue())
dlg.Destroy()
def OnLineColor(self, e):
global COLOUR
data = wx.ColourData()
data.SetChooseFull(True)
data.SetColour(COLOUR)
dlg = wx.ColourDialog(self, data, pos=(0,0))
changed = dlg.ShowModal() == wx.ID_OK
if changed:
c = dlg.GetColourData().GetColour()
COLOUR = '#%02x%02x%02x'%(c.Red(), c.Green(), c.Blue())
dlg.Destroy()
self.getNumWin()[1].SetCaretLineBack(COLOUR)
def OnSyntaxChange(self, e):
for i in SYNTAX_CHECK_DELAY_ID_TO_NUM:
self.menubar.Check(i, 0)
self.menubar.Check(e.GetId(), 1)
global HOW_OFTEN1
HOW_OFTEN1 = SYNTAX_CHECK_DELAY_ID_TO_NUM[e.GetId()]
def OnRefreshChange(self, e):
for i in REFRESH_DELAY_ID_TO_NUM:
self.menubar.Check(i, 0)
self.menubar.Check(e.GetId(), 1)
global HOW_OFTEN2
HOW_OFTEN2 = REFRESH_DELAY_ID_TO_NUM[e.GetId()]
def SharedCaret(self):
for win in self.control:
win.SetSlopPolicy()
def OnFinbarDefault(self, e):
n, win = self.getNumWin()
if win.GetParent().IsSplit():
win.GetParent().GetWindow2().savePreferences()
a = dict(win.findbarprefs)
del a['find']
del a['replace']
global findbarprefs
findbarprefs = a
def OnFindbarClear(self, e):
n, win = self.getNumWin()
if win.GetParent().IsSplit():
bar = win.GetParent().GetWindow2()
bar.box1.Clear()
bar.box1.SetValue("")
if not isinstance(bar, findbar.FindBar):
bar.box2.Clear()
bar.box2.SetValue("")
else:
win.findbarprefs['replace'] = []
else:
win.findbarprefs['find'] = []
win.findbarprefs['replace'] = []
def OnFindbarToggle(self, e):
global findbar_location
findbar_location = not findbar_location
def OnFindbarHistory(self, e):
global no_findbar_history
no_findbar_history = not no_findbar_history
self.menubar.FindItemById(CLEAR_FINDBAR_HISTORY).Enable(not no_findbar_history)
def OnChangeMenu(self, e):
keydialog.MenuItemDialog(self, self).ShowModal()
def OnChangeTitle(self, e):
global title_option
i = e.GetId()
title_option, _, _ = TITLE_ID_TO_OPTIONS[i]
self.updateWindowTitle()
wx.CallAfter(self.control.updateChecks, None)
def OnChangeDocumentsOptions(self, e):
global document_options
i = e.GetId()
document_options = DOCUMENT_LIST_OPTIONS[i][0]
self.docpanel._setcolumn()
self.docpanel._refresh()
wx.CallAfter(self.control.updateChecks, None)
def OnChangeDocumentsOptions2(self, e):
global document_options2
i = e.GetId()
document_options2 = DOCUMENT_LIST_OPTIONS2[i][0]
self.docpanel._setcolumn()
self.docpanel._refresh()
wx.CallAfter(self.control.updateChecks, None)
def OnShowRecentDocs(self, e):
global show_recent
show_recent = not show_recent
def OnShowQuickbrowse(self, e):
global show_search
show_search = not show_search
def OnChangeMacroOptions(self, e):
global macro_doubleclick
i = e.GetId()
macro_doubleclick = MACRO_CLICK_OPTIONS[i][0]
wx.CallAfter(self.control.updateChecks, None)
def OnToolToggle(self, e):
tool = e.GetId()
info = TOOLS_ENABLE_L[TOOLS_ENABLE[tool]]
if info[1] == 'Global Filter':
global global_filter_table
global_filter_table = not global_filter_table
if global_filter_table:
self.RIGHTNB.InsertPage(self.gfp, self.gf, "GlobalF")
wx.CallAfter(self.gf.OnText, None)
else:
self.RIGHTNB.RemovePage(self.gfp)
self.gf.Hide()
elif info[4] in window_management.enabled:
window_management.enabled.pop(info[4])
t = getattr(self, info[3])
t.Hide()
for i in xrange(t.parent.GetPageCount()):
if t.parent.GetPage(i) == t:
t.parent.RemovePage(i)
break
else:
window_management.enabled[info[4]] = None
t = getattr(self, info[3])
t.parent.AddPage(t, info[1])
for i in self.control:
if hasattr(i, '_invalidate_cache'):
i._invalidate_cache()
win = self.getNumWin()[1]
win.docstate.Show()
def OnMacroButtonImage(self, e):
global macro_images
macro_images = not macro_images
def OnSavePreferences(self, e):
self.saveHistory()
#----------------------------- Help Menu Methods -----------------------------
def OnAbout(self, e):
t = []
used = USED_TIME
for i,j in ((60, 'seconds'), (60, 'minutes'), (24, 'hours')):
if not used:
break
k = used%i
if k:
t.insert(0, "%s %s"%(k, j))
used = (used-k)/i
if used:
t.insert(0, "%s %s"%(used, "days"))
t = ', '.join(t)
txt = """
PyPE was written to scratch an itch. I (Josiah Carlson), was looking for
an editor for Python that had the features I wanted. I couldn't find one,
so I wrote PyPE.
PyPE %s (Python Programmers Editor)
http://come.to/josiah
PyPE is copyright 2003-2010 Josiah Carlson.
Contributions are copyright their respective authors.
This software is licensed under the GPL (GNU General Public License) version 2
as it appears here: http://www.gnu.org/copyleft/gpl.html
It is also included with this software as gpl.txt.
If you do not also receive a copy of gpl.txt with your version of this
software, please inform the me of the violation at the web page near the top
of this document.
You have used PyPE for: %s
PyPE is using wxPython version %s"""%(VERSION, t, wx.version())
self.dialog(txt.replace(' ', ''), "About...")
def OnHelp(self, e):
if not SHOWWIDE:
self.OnShowWideToggle(None)
for i in xrange(self.BOTTOMNB.GetPageCount()):
if isinstance(self.BOTTOMNB.GetPage(i), help.MyHtmlWindow):
self.BOTTOMNB.SetSelection(i)
break
def fixsize():
h = self.BOTTOM.GetSize()[1]//2
self.BOTTOM.SetSashPosition(h)
wx.CallAfter(fixsize)
#-------------------------- Hot Key support madness --------------------------
def keyboardShortcut(self, keypressed, evt=None):
menuid = HOTKEY_TO_ID[keypressed]
wx.PostEvent(self, wx.MenuEvent(wx.wxEVT_COMMAND_MENU_SELECTED, menuid))
def OnKeyPressed(self, event):
showpress = False
self._activity()
keypressed = GetKeyPress(event)
#fix for funky bug on OS X
if not self.menubar.IsEnabled(wx.ID_UNDO):
for menuid in (wx.ID_UNDO, wx.ID_REDO, wx.ID_CUT, wx.ID_COPY):
self.menubar.Enable(menuid, 1)
if showpress:
print "keypressed", keypressed
if keypressed in HOTKEY_TO_ID:
return self.keyboardShortcut(keypressed, event)
if self.macropage.RunMacro(keypressed):
return
key = GetKeyCode(event)
wnum = self.control.GetSelection()
pagecount = self.control.GetPageCount()
if wnum > -1:
win = self.control.GetPage(wnum).GetWindow1()
if pagecount:
if (key==13):
if type(self.FindFocus()) not in (PythonSTC, interpreter.MyShell):
return event.Skip()
#when 'enter' is pressed, indentation needs to happen.
if win.AutoCompActive():
return win.AutoCompComplete()
if win.CallTipActive():
win.CallTipCancel()
win._autoindent()
elif key == wx.WXK_ESCAPE:
if win.AutoCompActive():
win.AutoCompCancel()
if win.CallTipActive():
win.CallTipCancel()
else:
event.Skip()
if not (win.GetStyleAt(win.GetCurrentPos())):
#3, 13, 6, 7
if win.CallTipActive():
good = STRINGPRINTABLE
if (key in good) or (key in (wx.WXK_SHIFT, wx.WXK_CONTROL, wx.WXK_ALT)):
pass
#if key in (48, 57) and event.ShiftDown():
# win.CallTipCancel()
#else it is something in the arguments that is OK.
else:
## print "calltipcancel"
win.CallTipCancel()
if (not win.CallTipActive()) and event.ShiftDown() and (key == ord('9')):
## self._ct(win, 1)
wx.CallAfter(self._ct, win, 1)
elif win.showautocomp and bool(win.kw or win.hierarchy):
if keypressed.split('+')[-1] in _keys:
return
if keypressed.endswith('+') and not keypressed.endswith('++'):
return
wx.CallAfter(self._ac, win)
else:
return event.Skip()
def getLeftFunct(self, win, skip=0):
bad = dict.fromkeys('\t .,;:([)]}\'"\\<>%^&+-=*/|`\r\n')
line = win.lines.curline.rstrip('\r\n')
#can't use self.lines.curlinep because it uses utf-aligned positions
#on get, but it uses actual columns on set
colpos = win.GetColumn(win.GetCurrentPos())-skip
cur = colpos-1
## print line[cur:cur+1]
while (cur >= 0) and line[cur:cur+1] not in bad:
cur -= 1
## print line[cur:cur+1]
cur += 1
return cur, colpos, line[cur:colpos], win._is_method(win.lines.curlinei, line, cur)
def _ct(self, win, skip):
## print "calltipshow"
win.CallTipSetBackground(wx.Colour(255, 255, 232))
cur, colpos, word, _ = self.getLeftFunct(win, skip)
tip = '\n'.join(win.tooltips.get(word, []))
if tip:
win.CallTipShow(win.GetCurrentPos(),tip)
## else:
## print "no tip", repr(word)
def _ac(self, win):
cur, colpos, word, method = self.getLeftFunct(win)
if not word or len(word) < win.ac_length:
return win.AutoCompCancel()
## print "got word:", word
words = None
if method and win.fetch_methods:
words = win._method_listing(win.lines.curlinei, cur, word) or []
if not words:
words = win._name_listing(win.lines.curlinei, cur, word)
if win.use_keywords:
words.extend(i for i in win.kw.split() if i.startswith(word))
words.sort()
if len(words) == 0:
## print 'no words!'
return win.AutoCompCancel()
if len(words) == 1 and words[-1] == word:
## print "exact words"
return win.AutoCompCancel()
words = ' '.join(words)
## print "got words:", repr(words)
win.AutoCompSetIgnoreCase(False)
win.AutoCompShow(len(word), words)
#------------- Ahh, Styled Text Control, you make this possible. -------------
#the following table maps from event numbers to method names in the STC macro
#recording
message_lookup_table = {
2013:'SelectAll',
2177:'Cut',
2178:'Copy',
2179:'Paste',
2180:'Clear',
2300:'LineDown',
2301:'LineDownExtend',
2302:'LineUp',
2303:'LineUpExtend',
2304:'CharLeft',
2305:'CharLeftExtend',
2306:'CharRight',
2307:'CharRightExtend',
2308:'WordLeft',
2309:'WordLeftExtend',
2310:'WordRight',
2311:'WordRightExtend',
2312:'Home',
2313:'HomeExtend',
2314:'LineEnd',
2315:'LineEndExtend',
2316:'DocumentStart',
2317:'DocumentStartExtend',
2318:'DocumentEnd',
2319:'DocumentEndExtend',
2320:'PageUp',
2321:'PageUpExtend',
2322:'PageDown',
2323:'PageDownExtend',
2324:'EditToggleOvertype',
2325:'Cancel',
2326:'DeleteBack',
2327:'Tab',
2328:'BackTab',
2329:'NewLine',
2330:'FormFeed',
2331:'VCHome',
2332:'VCHomeExtend',
2333:'ZoomIn',
2334:'ZoomOut',
2335:'DelWordLeft',
2336:'DelWordRight',
2337:'LineCut',
2338:'LineDelete',
2339:'LineTranspose',
2340:'LowerCase',
2341:'UpperCase',
2342:'LineScrollDown',
2343:'LineScrollUp',
2344:'DeleteBackNotLine',
2345:'HomeDisplay',
2346:'HomeDisplayExtend',
2347:'LineEndDisplay',
2348:'LineEndDisplayExtend'
}
encoding_template = '''\
Based on BOM detection, coding declarations,
and defined defaults for the file type you are
opening, PyPE determined that your file was
likely encoded as %r, but its attempt to decode
your document failed due to:
%s
It will now try to decode your document as %r,
and depending on the content of your file, may
result in data corruption if this decision was
not correct and you attempt to save your file.
If you believe PyPE to be in error, do not save
your file, and contact PyPE's author.'''.replace(8*' ', '')
#
def chain(*args):
for i in args:
for j in i:
yield j
def bisect_getall(lst, item):
index = bisect.bisect_left(lst, item)
out = []
while item and index < len(lst) and lst[index][:len(item)] == item:
out.append(lst[index])
index += 1
return out
class PythonSTC(stc.StyledTextCtrl):
def __init__(self, notebook, ID, parent):
stc.StyledTextCtrl.__init__(self, parent, ID)#, style = wx.NO_FULL_REPAINT_ON_RESIZE)
self.SetWordChars('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
self.SetEndAtLastLine(False)
self.paste_rectangle = None
self.cached = None
self.loaded = True
self.MarkerDefine(BOOKMARKNUMBER, BOOKMARKSYMBOL, 'blue', 'blue')
self.MarkerDefine(NOTIFICATIONNUMBER, NOTIFICATIONSYMBOL, 'green', 'green')
_, flags = CARET_OPTION_TO_ID[caret_option]
self.SetXCaretPolicy(flags, caret_slop*caret_multiplier)
self.SetYCaretPolicy(flags, caret_slop)
self.hierarchy = []
self.kw = ''
self.tooltips = {}
self.ignore = {}
self.lines = lineabstraction.LineAbstraction(self)
self.parent = parent
self.notebook = notebook #should also be equal to self.parent.parent
try:
self.root = self.notebook.root
except:
self.root = root
self.sloppy = 0
self.smartpaste = 0
self.dirty = 0
self.refresh = 0
self.lexer = 'text'
self.selep = None
self.recording = 0
self.macro = []
self.fetch_methods = 0
self.use_keywords = 0
self.ac_length = 1
self.fetch_methods_cache = [-1, 0, '', []]
self.annotations = collections.defaultdict(list)
self.annotations_lines = []
self.annotations_visible = 2
self.AnnotationSetVisible(self.annotations_visible)
## if HAS_NATIVE_ANNOTATIONS:
## self.AnnotationSetStyleOffset(256)
## self.StyleSetSpec(512, "fore:#000000,face:%(mono)s,back:#B0B0FF,size:%(size)d" % faces)
#drop file and text support
self.SetDropTarget(FileDropTarget(self.root))
#for command comlpetion
self.SetKeyWords(0, " ".join(keyword.kwlist))
self.SetMargins(0,0)
self.SetViewWhiteSpace(False)
self.SetBackSpaceUnIndents(1)
#self.SetBufferedDraw(False)
#self.SetViewEOL(True)
self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
#self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "size:%(size)d,face:%(mono)s" % faces)
# Setup a margin to hold fold markers
#I agree, what is this value?
#self.SetFoldFlags(16) ### WHAT IS THIS VALUE? WHAT ARE THE OTHER FLAGS? DOES IT MATTER?
self.SetProperty("fold", "1")
self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
self.SetMarginSensitive(2, True)
self.SetMarginWidth(2, 12)
if hasattr(self, 'SetPasteConvertEndings'):
self.SetPasteConvertEndings(1)
if collapse_style: # simple folder marks, like the old version
self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "navy", "white")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "navy", "white")
# Set these to an invisible mark
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BACKGROUND, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_BACKGROUND, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_BACKGROUND, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_BACKGROUND, "white", "black")
else: # more involved "outlining" folder marks
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "black")
# Make some styles, The lexer defines what each style is used for, we
# just have to define what each style looks like. This set is adapted from
# Scintilla sample property files.
#And good wxPython users who have seen some demos know the above was copied
#and pasted, along with a lot of sample code, right out of the demo. The
#demo r0XX0rs.
# Global default styles for all languages
self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "fore:#000000,face:%(mono)s,back:#FFFFFF,size:%(size)d" % faces)
self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(mono)s,size:%(size2)d" % faces)
self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % faces)
self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#003000,face:%(mono)s,back:#80E0E0"% faces)
self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#E0FFE0,face:%(mono)s,back:#FF0000"% faces)
#various settings
self.SetSelBackground(1, '#B0B0FF')
#again, some state variables
self.filename = ''
self.dirname = ''
self.opened = 0
self.AutoCompStops(' .,;:()[]{}\'"\\<>%^&+-=*/|`')
stc.EVT_STC_UPDATEUI(self, ID, self.OnUpdateUI)
stc.EVT_STC_MARGINCLICK(self, ID, self.OnMarginClick)
wx.EVT_KEY_DOWN(self, self.root.OnKeyPressed)
#wx.EVT_CHAR(self, self.root.OnKeyPressed)
wx.EVT_KEY_UP(self, self.key_up)
stc.EVT_STC_CHARADDED(self, ID, self.added)
stc.EVT_STC_CHANGE(self, ID, self.key_up)
#unavailable in 2.5.1.2, didn't work in previous versions of wxPython
# stc.EVT_STC_POSCHANGED(self, ID, self.pos)
stc.EVT_STC_SAVEPOINTREACHED(self, ID, self.MakeClean)
stc.EVT_STC_SAVEPOINTLEFT(self, ID, self.MakeDirty)
stc.EVT_STC_NEEDSHOWN(self, ID, self.OnNeedShown)
self.Bind(wx.EVT_LEFT_UP, self.OnSelectionEnd)
if not isinstance(self, View):
self.Bind(wx.EVT_MIDDLE_UP, self.OnMousePaste)
self.Bind(stc.EVT_STC_MACRORECORD, self.GotEvent)
self.SetModEventMask(stc.STC_MOD_INSERTTEXT|stc.STC_MOD_DELETETEXT|stc.STC_PERFORMED_USER|stc.STC_PERFORMED_UNDO|stc.STC_PERFORMED_REDO)
if REM_SWAP:
self.CmdKeyClear(ord('T'), stc.STC_SCMOD_CTRL)
self.CmdKeyClear(ord('Z'), stc.STC_SCMOD_CTRL)
self.CmdKeyClear(ord('Y'), stc.STC_SCMOD_CTRL)
self.CmdKeyClear(ord('X'), stc.STC_SCMOD_CTRL)
self.CmdKeyClear(ord('C'), stc.STC_SCMOD_CTRL)
self.CmdKeyClear(ord('V'), stc.STC_SCMOD_CTRL)
self.CmdKeyClear(ord('A'), stc.STC_SCMOD_CTRL)
## self.dragstartok = 0
## self.dragging = 0
## sekf.have_selection = 0
## self.Bind(wx.EVT_MOTION, self._checkmouse)
## self.Bind(wx.EVT_LEFT_DOWN, self._checkmouse2)
## self.Bind(wx.EVT_LEFT_UP, self._checkmouse3)
self.has_bad = 0
self.lastparse = _MULT[HOW_OFTEN1]*1000
self.lastparse2 = _MULT[HOW_OFTEN2]*1000
self.m1 = None
self.m2 = None
self.automatic = 0
try:
self.SetTwoPhaseDraw(1)
except:
pass
try:
self.IndicatorSetUnder(1)
except:
pass
def SetSlopPolicy(self):
_, flags = CARET_OPTION_TO_ID[caret_option]
self.SetXCaretPolicy(flags, caret_slop*caret_multiplier)
self.SetYCaretPolicy(flags, caret_slop)
self.SetCaretWidth(CARET_WIDTH)
def gotcharacter(self):
## self._gotcharacter()
self.root._activity(self.lexer == 'python', self)
def _checkmouse(self, evt):
if self.dragging or not self.dragstartok or not evt.Dragging():
return
self._startdrag(evt)
def _checkmouse2(self, evt):
self.dragstartok = 1
evt.Skip()
def _checkmouse3(self, evt):
self.dragstartok = 0
evt.Skip()
def _startdrag(self, evt):
if self.SelectionIsRectangle():
return evt.Skip()
#Need to differentiate between discovering the initial selection
#and dragging that selection. Still working on making it reliable.
def _filetype(self):
if '.' not in self.filename:
return lexer2lang.get(self.GetLexer(), 'python')
return get_filetype(self.filename)
def getshort(self):
if self.dirname:
return self.filename
return '<untitled %i>'%self.NEWDOCUMENT
def getlong(self):
if self.dirname:
return os.path.join(self.dirname, self.filename)
return ''
def MacroToggle(self, e):
self.recording = not self.recording
if self.recording:
self.macro = []
self.StartRecord()
else:
self.StopRecord()
self.root.SetStatusText("Recorded %s steps for the macro"%len(self.macro))
def StopRecord(self):
stc.StyledTextCtrl.StopRecord(self)
#macro: merge all character 2170 events together
macro = []
last = []
x = len(self.macro)
for i in self.macro:
if i[0] != 2170 or (i[0] == 2170 and isinstance(i[-1], (int, long))):
if last:
macro.append((2170, 0, ''.join(last)))
last = []
macro.append(i)
else:
last.append(i[-1])
if last:
macro.append((2170, 0, ''.join(last)))
if len(macro) < x:
self.macro = macro
if PRINTMACROS: print "Reduced macro from %i to %i steps"%(x, len(macro))
def _macro_to_source(self):
mlt = message_lookup_table
z = ['def macro(self):']
for i in self.macro:
m,w,l = i
if m in mlt:
z.append(' self.%s()'%mlt[m])
elif m is None:
z.append(' self.%s(%s)'%(l, w))
elif isinstance(m, basestring):
if l == None:
z.append(" self.root.keyboardShortcut(%r)"%m)
else:
z.append(" #the following shouldn't happen: %r"%(i,))
z.append(" root.Dent(None, %i)"%l)
elif m == 2170:
if isinstance(l, basestring):
z.append(" self.ReplaceSelection(%r)"%l)
else:
z.append(" #this event shouldn't happen: %r"%(i,))
else:
z.append(" #this event shouldn't happen: %r"%(i,))
return '\n'.join(z)
def InterpretTrigger(self, tr, strict=0):
self.BeginUndoAction()
try:
if not strict:
tr = tr.replace('\r\n', '\n').replace('\r', '\n').replace('\n', '%L')
posn = p = self.GetSelection()[0]
todos = tr.split('%C')
for y, todo in enumerate(todos):
for i in re.split('(%L)', todo): # '(%-?L)'
if i == '%L':
self._autoindent()
## elif i == '%-L':
## self._autoindent()
## l = max(self.GetSelection())
## self.SetSelection(l,l)
## self.Dent(None, -1)
else:
self.ReplaceSelection(i)
if y != len(todos)-1:
posn = self.GetSelection()[0]
if posn != p:
self.SetSelection(posn, posn)
finally:
self.EndUndoAction()
def _tdisable(self, fcn, *args, **kwargs):
_, self.recording = self.recording, 0
try:
return fcn(*args, **kwargs)
finally:
self.recording = _
def GotEvent(self, e):
if self.recording:
x = (e.GetMessage(), e.GetWParam(), e.GetLParam())
if x[0] in message_lookup_table:
self.macro.append(x)
elif x[0] != 2170:
print "Unhandled event, please report to the author", x
def PlayMacro(self):
mlt = message_lookup_table
## self.BeginUndoAction()
#macro: z represents generated code based on method name
z = ['def macro(self):']
for i in self.macro:
m,w,l = i
## print i,
if m in mlt:
method = getattr(self, mlt[m])
z.append(' self.%s()'%mlt[m])
method()
elif m is None:
z.append(' self.%s(%s)'%(l, w))
getattr(self, l)(w)
elif isinstance(m, basestring):
if l == None:
z.append(" self.root.keyboardShortcut(%r)"%m)
self.root.keyboardShortcut(m)
else:
print "shouldn't happen!", i
z.append(" root.Dent(None, %i)"%l)
self.root.Dent(None, l)
elif m == 2170:
if isinstance(l, basestring):
z.append(" self.ReplaceSelection(%r)"%l)
self.ReplaceSelection(l)
else:
print "shouldn't happen!", i
else:
print "Unhandled event:",i
wx.Yield()
time.sleep(.01)
## self.EndUndoAction()
print "Performed %s steps of the macro!"%len(self.macro)
if PRINTMACROS: print '\n'.join(z)
def save(self, e):
#print "save reached"
self.key_up(e)
def savel(self, e):
#print "save left"
self.key_up(e)
def key_up(self, e):
if self.GetModify(): self.MakeDirty()
else: self.MakeClean()
self.gotcharacter()
def pos_ch(self, e):
if self.root.control.GetCurrentPage() == self.GetParent():
if not hasattr(self, 'lines'):
return
l = self.lines
self.root.SetStatusText("L%i C%i"%(l.curlinei+1, l.curlinep), 1)
if e:
e.Skip()
if (not HAS_NATIVE_ANNOTATIONS) and self.AnnotationGetVisible():
self._CheckForAnnotation()
self.gotcharacter()
def added(self, e):
if self.recording:
if e:
self.macro.append((2170, 0, _decode_key(e.GetKey())))
## print "got key", repr(self.macro[-1][-1]), e.GetKey()
expanded = 0
try:
full = e is None
tr = self.triggers
fcn = self.PositionBefore
pp = gcp = self.GetCurrentPos()
p = fcn(gcp)
c = 1
while pp != p:
if not full and c > 1:
break
## print repr(tr)
ch = self.GetTextRange(p,pp)
c += 1
## print repr(ch), tr.keys()
tr = tr.get(ch, None)
if tr is None:
## print "ran off of triggers!", repr(ch), p, gcp
break
elif isinstance(tr, (str, unicode)):
if e:
self.macro.append((None, 1, 'added'))
self.SetSelection(p, gcp)
self.ReplaceSelection('')
self.InterpretTrigger(tr)
expanded = 1
break
pp, p = p, fcn(p)
## print p, pp
else:
pass
## print "not found", p, gcp
finally:
self.key_up(e)
def jump(self, direction):
#1 forward, -1 backward
if direction not in (1,-1):
return
#set up characters
chars2, chars3 = '({[:,\'"', ')}]\'"'
if self.GetLexer() in (stc.STC_LEX_HTML, stc.STC_LEX_XML):
chars2 = chars2 + '>'
chars3 = chars3 + '<'
#chars2 are things that we want to be to the right of
#chars3 are things that we want to be to the left of
chars1 = chars2 + chars3
#cursor position information
linenum = self.GetCurrentLine()
pos = self.GetCurrentPos()
#iterator setup
if direction == 1:
it = xrange(pos, self.GetTextLength())
else:
it = xrange(pos-1, -1, -1)
#updates information cross-lines
for p in it:
ch = self.GetTextRange(p, p+1)
if ch not in chars1:
continue
if direction == 1: #if we are heading to the right
#if we want to be to the right of line[p], make it so
if ch in chars2:
p += 1
break
#else if this character is just to the right of where we are at, skip it
elif p == pos:
continue
#else if we want to be to the left of line[p], make it so
elif ch in chars3:
break
else: #else we are heading to the left
#if we want to be to the left of line[p], make it so
if ch in chars3:
break
#else if this character is just to the left of where we are at, skip it
elif p == pos-1:
continue
#else if we want to be to the right of line[p], make it so
elif ch in chars2:
p += 1
break
else:
return
self._tdisable(self.SetSelection, p, p)
def OnJumpF(self, e):
self.jump(1)
def OnJumpB(self, e):
self.jump(-1)
#------------------------- persistant document state -------------------------
def GetSaveState(self, scp=0):
BM = []
FOLD = []
if self.GetParent().IsSplit():
self.GetParent().GetWindow2().savePreferences()
ret = {'BM':BM,
'FOLD':FOLD,
'use_tabs':self.GetUseTabs(),
'spaces_per_tab':self.GetTabWidth(),
'indent':self.GetIndent(),
'marker_margin':bool(self.GetMarginWidth(1)),
'line_margin':bool(self.GetMarginWidth(0)),
'col_line':self.GetEdgeColumn(),
'col_mode':self.GetEdgeMode(),
'indent_guide':self.GetIndentationGuides(),
'showautocomp':self.showautocomp,
'wrapmode':self.GetWrapMode(),
## 'sortmode':self.tree.tree.SORTTREE,
'save_cursor':self.save_cursor,
'cursor_posn':self.GetCurrentPos(),
'findbarprefs':self.findbarprefs,
## 'triggers':self.triggers,
'whitespace':self.GetViewWhiteSpace(),
'show_line_ends':self.GetViewEOL(),
'sloppy':self.sloppy,
'smartpaste':self.smartpaste,
'showline':self.GetCaretLineVisible(),
'fetch_methods':self.fetch_methods,
'use_keywords':self.use_keywords,
'ac_length':self.ac_length,
'annotations_visible':self.AnnotationGetVisible(),
}
if not self.save_cursor and not scp:
del ret['cursor_posn']
if self.GetTextLength() < MAX_SAVE_STATE_DOC_SIZE:
ret['checksum'] = md5.new(self.GetText(0)).hexdigest()
if (self.GetLineCount() < MAX_SAVE_STATE_LINE_COUNT and
self.GetTextLength() < MAX_SAVE_STATE_DOC_SIZE):
for line in xrange(self.GetLineCount()):
if self.MarkerGet(line) & BOOKMARKMASK:
BM.append(line)
if (self.GetFoldLevel(line) & stc.STC_FOLDLEVELHEADERFLAG) and\
(not self.