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
|
/* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* Python extensions by Paul Moore, David Leonard, Roland Puntaier, Nikolay
* Pavlov.
*
* Common code for if_python.c and if_python3.c.
*/
#if PY_VERSION_HEX < 0x02050000
typedef int Py_ssize_t; /* Python 2.4 and earlier don't have this type. */
#endif
#ifdef FEAT_MBYTE
# define ENC_OPT p_enc
#else
# define ENC_OPT "latin1"
#endif
#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
#define INVALID_WINDOW_VALUE ((win_T *)(-1))
static int ConvertFromPyObject(PyObject *, typval_T *);
static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
static PyInt RangeStart;
static PyInt RangeEnd;
/*
* obtain a lock on the Vim data structures
*/
static void
Python_Lock_Vim(void)
{
}
/*
* release a lock on the Vim data structures
*/
static void
Python_Release_Vim(void)
{
}
/* Output buffer management
*/
/* Function to write a line, points to either msg() or emsg(). */
typedef void (*writefn)(char_u *);
static PyTypeObject OutputType;
typedef struct
{
PyObject_HEAD
long softspace;
long error;
} OutputObject;
static int
OutputSetattr(PyObject *self, char *name, PyObject *val)
{
if (val == NULL)
{
PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
return -1;
}
if (strcmp(name, "softspace") == 0)
{
if (!PyInt_Check(val))
{
PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
return -1;
}
((OutputObject *)(self))->softspace = PyInt_AsLong(val);
return 0;
}
PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
return -1;
}
/* Buffer IO, we write one whole line at a time. */
static garray_T io_ga = {0, 0, 1, 80, NULL};
static writefn old_fn = NULL;
static void
PythonIO_Flush(void)
{
if (old_fn != NULL && io_ga.ga_len > 0)
{
((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
old_fn((char_u *)io_ga.ga_data);
}
io_ga.ga_len = 0;
}
static void
writer(writefn fn, char_u *str, PyInt n)
{
char_u *ptr;
/* Flush when switching output function. */
if (fn != old_fn)
PythonIO_Flush();
old_fn = fn;
/* Write each NL separated line. Text after the last NL is kept for
* writing later. */
while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
{
PyInt len = ptr - str;
if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
break;
mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
fn((char_u *)io_ga.ga_data);
str = ptr + 1;
n -= len + 1;
io_ga.ga_len = 0;
}
/* Put the remaining text into io_ga for later printing. */
if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
{
mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
io_ga.ga_len += (int)n;
}
}
static PyObject *
OutputWrite(PyObject *self, PyObject *args)
{
Py_ssize_t len = 0;
char *str = NULL;
int error = ((OutputObject *)(self))->error;
if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
return NULL;
Py_BEGIN_ALLOW_THREADS
Python_Lock_Vim();
writer((writefn)(error ? emsg : msg), (char_u *)str, len);
Python_Release_Vim();
Py_END_ALLOW_THREADS
PyMem_Free(str);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
OutputWritelines(PyObject *self, PyObject *args)
{
PyInt n;
PyInt i;
PyObject *list;
int error = ((OutputObject *)(self))->error;
if (!PyArg_ParseTuple(args, "O", &list))
return NULL;
Py_INCREF(list);
if (!PyList_Check(list))
{
PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
Py_DECREF(list);
return NULL;
}
n = PyList_Size(list);
for (i = 0; i < n; ++i)
{
PyObject *line = PyList_GetItem(list, i);
char *str = NULL;
PyInt len;
if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len))
{
PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
Py_DECREF(list);
return NULL;
}
Py_BEGIN_ALLOW_THREADS
Python_Lock_Vim();
writer((writefn)(error ? emsg : msg), (char_u *)str, len);
Python_Release_Vim();
Py_END_ALLOW_THREADS
PyMem_Free(str);
}
Py_DECREF(list);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
{
/* do nothing */
Py_INCREF(Py_None);
return Py_None;
}
/***************/
static struct PyMethodDef OutputMethods[] = {
/* name, function, calling, documentation */
{"write", OutputWrite, 1, ""},
{"writelines", OutputWritelines, 1, ""},
{"flush", OutputFlush, 1, ""},
{ NULL, NULL, 0, NULL}
};
static OutputObject Output =
{
PyObject_HEAD_INIT(&OutputType)
0,
0
};
static OutputObject Error =
{
PyObject_HEAD_INIT(&OutputType)
0,
1
};
static int
PythonIO_Init_io(void)
{
PySys_SetObject("stdout", (PyObject *)(void *)&Output);
PySys_SetObject("stderr", (PyObject *)(void *)&Error);
if (PyErr_Occurred())
{
EMSG(_("E264: Python: Error initialising I/O objects"));
return -1;
}
return 0;
}
static PyObject *VimError;
/* Check to see whether a Vim error has been reported, or a keyboard
* interrupt has been detected.
*/
static int
VimErrorCheck(void)
{
if (got_int)
{
PyErr_SetNone(PyExc_KeyboardInterrupt);
return 1;
}
else if (did_emsg && !PyErr_Occurred())
{
PyErr_SetNone(VimError);
return 1;
}
return 0;
}
/* Vim module - Implementation
*/
static PyObject *
VimCommand(PyObject *self UNUSED, PyObject *args)
{
char *cmd;
PyObject *result;
if (!PyArg_ParseTuple(args, "s", &cmd))
return NULL;
PyErr_Clear();
Py_BEGIN_ALLOW_THREADS
Python_Lock_Vim();
do_cmdline_cmd((char_u *)cmd);
update_screen(VALID);
Python_Release_Vim();
Py_END_ALLOW_THREADS
if (VimErrorCheck())
result = NULL;
else
result = Py_None;
Py_XINCREF(result);
return result;
}
/*
* Function to translate a typval_T into a PyObject; this will recursively
* translate lists/dictionaries into their Python equivalents.
*
* The depth parameter is to avoid infinite recursion, set it to 1 when
* you call VimToPython.
*/
static PyObject *
VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
{
PyObject *result;
PyObject *newObj;
char ptrBuf[sizeof(void *) * 2 + 3];
/* Avoid infinite recursion */
if (depth > 100)
{
Py_INCREF(Py_None);
result = Py_None;
return result;
}
/* Check if we run into a recursive loop. The item must be in lookupDict
* then and we can use it again. */
if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
|| (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
{
sprintf(ptrBuf, "%p",
our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
: (void *)our_tv->vval.v_dict);
result = PyDict_GetItemString(lookupDict, ptrBuf);
if (result != NULL)
{
Py_INCREF(result);
return result;
}
}
if (our_tv->v_type == VAR_STRING)
{
result = Py_BuildValue("s", our_tv->vval.v_string == NULL
? "" : (char *)our_tv->vval.v_string);
}
else if (our_tv->v_type == VAR_NUMBER)
{
char buf[NUMBUFLEN];
/* For backwards compatibility numbers are stored as strings. */
sprintf(buf, "%ld", (long)our_tv->vval.v_number);
result = Py_BuildValue("s", buf);
}
# ifdef FEAT_FLOAT
else if (our_tv->v_type == VAR_FLOAT)
{
char buf[NUMBUFLEN];
sprintf(buf, "%f", our_tv->vval.v_float);
result = Py_BuildValue("s", buf);
}
# endif
else if (our_tv->v_type == VAR_LIST)
{
list_T *list = our_tv->vval.v_list;
listitem_T *curr;
result = PyList_New(0);
if (list != NULL)
{
PyDict_SetItemString(lookupDict, ptrBuf, result);
for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
{
newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
PyList_Append(result, newObj);
Py_DECREF(newObj);
}
}
}
else if (our_tv->v_type == VAR_DICT)
{
result = PyDict_New();
if (our_tv->vval.v_dict != NULL)
{
hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
long_u todo = ht->ht_used;
hashitem_T *hi;
dictitem_T *di;
PyDict_SetItemString(lookupDict, ptrBuf, result);
for (hi = ht->ht_array; todo > 0; ++hi)
{
if (!HASHITEM_EMPTY(hi))
{
--todo;
di = dict_lookup(hi);
newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
Py_DECREF(newObj);
}
}
}
}
else
{
Py_INCREF(Py_None);
result = Py_None;
}
return result;
}
static PyObject *
VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
{
char *expr;
typval_T *our_tv;
PyObject *result;
PyObject *lookup_dict;
if (!PyArg_ParseTuple(args, "s", &expr))
return NULL;
Py_BEGIN_ALLOW_THREADS
Python_Lock_Vim();
our_tv = eval_expr((char_u *)expr, NULL);
Python_Release_Vim();
Py_END_ALLOW_THREADS
if (our_tv == NULL)
{
PyErr_SetVim(_("invalid expression"));
return NULL;
}
/* Convert the Vim type into a Python type. Create a dictionary that's
* used to check for recursive loops. */
lookup_dict = PyDict_New();
result = VimToPython(our_tv, 1, lookup_dict);
Py_DECREF(lookup_dict);
Py_BEGIN_ALLOW_THREADS
Python_Lock_Vim();
free_tv(our_tv);
Python_Release_Vim();
Py_END_ALLOW_THREADS
return result;
}
static PyObject *ConvertToPyObject(typval_T *);
static PyObject *
VimEvalPy(PyObject *self UNUSED, PyObject *args UNUSED)
{
char *expr;
typval_T *our_tv;
PyObject *result;
if (!PyArg_ParseTuple(args, "s", &expr))
return NULL;
Py_BEGIN_ALLOW_THREADS
Python_Lock_Vim();
our_tv = eval_expr((char_u *)expr, NULL);
Python_Release_Vim();
Py_END_ALLOW_THREADS
if (our_tv == NULL)
{
PyErr_SetVim(_("invalid expression"));
return NULL;
}
result = ConvertToPyObject(our_tv);
Py_BEGIN_ALLOW_THREADS
Python_Lock_Vim();
free_tv(our_tv);
Python_Release_Vim();
Py_END_ALLOW_THREADS
return result;
}
static PyObject *
VimStrwidth(PyObject *self UNUSED, PyObject *args)
{
char *expr;
if (!PyArg_ParseTuple(args, "s", &expr))
return NULL;
return PyLong_FromLong(
#ifdef FEAT_MBYTE
mb_string2cells((char_u *)expr, (int)STRLEN(expr))
#else
STRLEN(expr)
#endif
);
}
/*
* Vim module - Definitions
*/
static struct PyMethodDef VimMethods[] = {
/* name, function, calling, documentation */
{"command", VimCommand, 1, "Execute a Vim ex-mode command" },
{"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
{"bindeval", VimEvalPy, 1, "Like eval(), but returns objects attached to vim ones"},
{"strwidth", VimStrwidth, 1, "Screen string width, counts <Tab> as having width 1"},
{ NULL, NULL, 0, NULL }
};
/*
* Generic iterator object
*/
static PyTypeObject IterType;
typedef PyObject *(*nextfun)(void **);
typedef void (*destructorfun)(void *);
/* Main purpose of this object is removing the need for do python initialization
* (i.e. PyType_Ready and setting type attributes) for a big bunch of objects.
*/
typedef struct
{
PyObject_HEAD
void *cur;
nextfun next;
destructorfun destruct;
} IterObject;
static PyObject *
IterNew(void *start, destructorfun destruct, nextfun next)
{
IterObject *self;
self = PyObject_NEW(IterObject, &IterType);
self->cur = start;
self->next = next;
self->destruct = destruct;
return (PyObject *)(self);
}
static void
IterDestructor(PyObject *self)
{
IterObject *this = (IterObject *)(self);
this->destruct(this->cur);
DESTRUCTOR_FINISH(self);
}
static PyObject *
IterNext(PyObject *self)
{
IterObject *this = (IterObject *)(self);
return this->next(&this->cur);
}
static PyObject *
IterIter(PyObject *self)
{
return self;
}
typedef struct pylinkedlist_S {
struct pylinkedlist_S *pll_next;
struct pylinkedlist_S *pll_prev;
PyObject *pll_obj;
} pylinkedlist_T;
static pylinkedlist_T *lastdict = NULL;
static pylinkedlist_T *lastlist = NULL;
static void
pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
{
if (ref->pll_prev == NULL)
{
if (ref->pll_next == NULL)
{
*last = NULL;
return;
}
}
else
ref->pll_prev->pll_next = ref->pll_next;
if (ref->pll_next == NULL)
*last = ref->pll_prev;
else
ref->pll_next->pll_prev = ref->pll_prev;
}
static void
pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
{
if (*last == NULL)
ref->pll_prev = NULL;
else
{
(*last)->pll_next = ref;
ref->pll_prev = *last;
}
ref->pll_next = NULL;
ref->pll_obj = self;
*last = ref;
}
static PyTypeObject DictionaryType;
#define DICTKEY_GET_NOTEMPTY(err) \
DICTKEY_GET(err) \
if (*key == NUL) \
{ \
PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
return err; \
}
typedef struct
{
PyObject_HEAD
dict_T *dict;
pylinkedlist_T ref;
} DictionaryObject;
static PyObject *
DictionaryNew(dict_T *dict)
{
DictionaryObject *self;
self = PyObject_NEW(DictionaryObject, &DictionaryType);
if (self == NULL)
return NULL;
self->dict = dict;
++dict->dv_refcount;
pyll_add((PyObject *)(self), &self->ref, &lastdict);
return (PyObject *)(self);
}
static void
DictionaryDestructor(PyObject *self)
{
DictionaryObject *this = ((DictionaryObject *) (self));
pyll_remove(&this->ref, &lastdict);
dict_unref(this->dict);
DESTRUCTOR_FINISH(self);
}
static int
DictionarySetattr(PyObject *self, char *name, PyObject *val)
{
DictionaryObject *this = (DictionaryObject *)(self);
if (val == NULL)
{
PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
return -1;
}
if (strcmp(name, "locked") == 0)
{
if (this->dict->dv_lock == VAR_FIXED)
{
PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
return -1;
}
else
{
if (!PyBool_Check(val))
{
PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
return -1;
}
if (val == Py_True)
this->dict->dv_lock = VAR_LOCKED;
else
this->dict->dv_lock = 0;
}
return 0;
}
else
{
PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
return -1;
}
}
static PyInt
DictionaryLength(PyObject *self)
{
return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
}
static PyObject *
DictionaryItem(PyObject *self, PyObject *keyObject)
{
char_u *key;
dictitem_T *di;
DICTKEY_DECL
DICTKEY_GET_NOTEMPTY(NULL)
di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
DICTKEY_UNREF
if (di == NULL)
{
PyErr_SetString(PyExc_KeyError, _("no such key in dictionary"));
return NULL;
}
return ConvertToPyObject(&di->di_tv);
}
static PyInt
DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
{
char_u *key;
typval_T tv;
dict_T *d = ((DictionaryObject *)(self))->dict;
dictitem_T *di;
DICTKEY_DECL
if (d->dv_lock)
{
PyErr_SetVim(_("dict is locked"));
return -1;
}
DICTKEY_GET_NOTEMPTY(-1)
di = dict_find(d, key, -1);
if (valObject == NULL)
{
hashitem_T *hi;
if (di == NULL)
{
DICTKEY_UNREF
PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
return -1;
}
hi = hash_find(&d->dv_hashtab, di->di_key);
hash_remove(&d->dv_hashtab, hi);
dictitem_free(di);
return 0;
}
if (ConvertFromPyObject(valObject, &tv) == -1)
return -1;
if (di == NULL)
{
di = dictitem_alloc(key);
if (di == NULL)
{
PyErr_NoMemory();
return -1;
}
di->di_tv.v_lock = 0;
if (dict_add(d, di) == FAIL)
{
DICTKEY_UNREF
vim_free(di);
PyErr_SetVim(_("failed to add key to dictionary"));
return -1;
}
}
else
clear_tv(&di->di_tv);
DICTKEY_UNREF
copy_tv(&tv, &di->di_tv);
return 0;
}
static PyObject *
DictionaryListKeys(PyObject *self UNUSED)
{
dict_T *dict = ((DictionaryObject *)(self))->dict;
long_u todo = dict->dv_hashtab.ht_used;
Py_ssize_t i = 0;
PyObject *r;
hashitem_T *hi;
r = PyList_New(todo);
for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
{
if (!HASHITEM_EMPTY(hi))
{
PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
--todo;
++i;
}
}
return r;
}
static PyMappingMethods DictionaryAsMapping = {
(lenfunc) DictionaryLength,
(binaryfunc) DictionaryItem,
(objobjargproc) DictionaryAssItem,
};
static struct PyMethodDef DictionaryMethods[] = {
{"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
{ NULL, NULL, 0, NULL }
};
static PyTypeObject ListType;
static PySequenceMethods ListAsSeq;
static PyMappingMethods ListAsMapping;
typedef struct
{
PyObject_HEAD
list_T *list;
pylinkedlist_T ref;
} ListObject;
static PyObject *
ListNew(list_T *list)
{
ListObject *self;
self = PyObject_NEW(ListObject, &ListType);
if (self == NULL)
return NULL;
self->list = list;
++list->lv_refcount;
pyll_add((PyObject *)(self), &self->ref, &lastlist);
return (PyObject *)(self);
}
static void
ListDestructor(PyObject *self)
{
ListObject *this = (ListObject *)(self);
pyll_remove(&this->ref, &lastlist);
list_unref(this->list);
DESTRUCTOR_FINISH(self);
}
static int
list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
{
Py_ssize_t i;
Py_ssize_t lsize = PySequence_Size(obj);
PyObject *litem;
listitem_T *li;
for(i=0; i<lsize; i++)
{
li = listitem_alloc();
if (li == NULL)
{
PyErr_NoMemory();
return -1;
}
li->li_tv.v_lock = 0;
litem = PySequence_GetItem(obj, i);
if (litem == NULL)
return -1;
if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
return -1;
list_append(l, li);
}
return 0;
}
static PyInt
ListLength(PyObject *self)
{
return ((PyInt) (((ListObject *) (self))->list->lv_len));
}
static PyObject *
ListItem(PyObject *self, Py_ssize_t index)
{
listitem_T *li;
if (index>=ListLength(self))
{
PyErr_SetString(PyExc_IndexError, "list index out of range");
return NULL;
}
li = list_find(((ListObject *) (self))->list, (long) index);
if (li == NULL)
{
PyErr_SetVim(_("internal error: failed to get vim list item"));
return NULL;
}
return ConvertToPyObject(&li->li_tv);
}
#define PROC_RANGE \
if (last < 0) {\
if (last < -size) \
last = 0; \
else \
last += size; \
} \
if (first < 0) \
first = 0; \
if (first > size) \
first = size; \
if (last > size) \
last = size;
static PyObject *
ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
{
PyInt i;
PyInt size = ListLength(self);
PyInt n;
PyObject *list;
int reversed = 0;
PROC_RANGE
if (first >= last)
first = last;
n = last-first;
list = PyList_New(n);
if (list == NULL)
return NULL;
for (i = 0; i < n; ++i)
{
PyObject *item = ListItem(self, first + i);
if (item == NULL)
{
Py_DECREF(list);
return NULL;
}
if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
{
Py_DECREF(item);
Py_DECREF(list);
return NULL;
}
}
return list;
}
typedef struct
{
listwatch_T lw;
list_T *list;
} listiterinfo_T;
static void
ListIterDestruct(listiterinfo_T *lii)
{
list_rem_watch(lii->list, &lii->lw);
PyMem_Free(lii);
}
static PyObject *
ListIterNext(listiterinfo_T **lii)
{
PyObject *r;
if (!((*lii)->lw.lw_item))
return NULL;
if (!(r = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
return NULL;
(*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
return r;
}
static PyObject *
ListIter(PyObject *self)
{
listiterinfo_T *lii;
list_T *l = ((ListObject *) (self))->list;
if (!(lii = PyMem_New(listiterinfo_T, 1)))
{
PyErr_NoMemory();
return NULL;
}
list_add_watch(l, &lii->lw);
lii->lw.lw_item = l->lv_first;
lii->list = l;
return IterNew(lii,
(destructorfun) ListIterDestruct, (nextfun) ListIterNext);
}
static int
ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
{
typval_T tv;
list_T *l = ((ListObject *) (self))->list;
listitem_T *li;
Py_ssize_t length = ListLength(self);
if (l->lv_lock)
{
PyErr_SetVim(_("list is locked"));
return -1;
}
if (index>length || (index==length && obj==NULL))
{
PyErr_SetString(PyExc_IndexError, "list index out of range");
return -1;
}
if (obj == NULL)
{
li = list_find(l, (long) index);
list_remove(l, li, li);
clear_tv(&li->li_tv);
vim_free(li);
return 0;
}
if (ConvertFromPyObject(obj, &tv) == -1)
return -1;
if (index == length)
{
if (list_append_tv(l, &tv) == FAIL)
{
PyErr_SetVim(_("Failed to add item to list"));
return -1;
}
}
else
{
li = list_find(l, (long) index);
clear_tv(&li->li_tv);
copy_tv(&tv, &li->li_tv);
}
return 0;
}
static int
ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
{
PyInt size = ListLength(self);
Py_ssize_t i;
Py_ssize_t lsize;
PyObject *litem;
listitem_T *li;
listitem_T *next;
typval_T v;
list_T *l = ((ListObject *) (self))->list;
if (l->lv_lock)
{
PyErr_SetVim(_("list is locked"));
return -1;
}
PROC_RANGE
if (first == size)
li = NULL;
else
{
li = list_find(l, (long) first);
if (li == NULL)
{
PyErr_SetVim(_("internal error: no vim list item"));
return -1;
}
if (last > first)
{
i = last - first;
while (i-- && li != NULL)
{
next = li->li_next;
listitem_remove(l, li);
li = next;
}
}
}
if (obj == NULL)
return 0;
if (!PyList_Check(obj))
{
PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
return -1;
}
lsize = PyList_Size(obj);
for(i=0; i<lsize; i++)
{
litem = PyList_GetItem(obj, i);
if (litem == NULL)
return -1;
if (ConvertFromPyObject(litem, &v) == -1)
return -1;
if (list_insert_tv(l, &v, li) == FAIL)
{
PyErr_SetVim(_("internal error: failed to add item to list"));
return -1;
}
}
return 0;
}
static PyObject *
ListConcatInPlace(PyObject *self, PyObject *obj)
{
list_T *l = ((ListObject *) (self))->list;
PyObject *lookup_dict;
if (l->lv_lock)
{
PyErr_SetVim(_("list is locked"));
return NULL;
}
if (!PySequence_Check(obj))
{
PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
return NULL;
}
lookup_dict = PyDict_New();
if (list_py_concat(l, obj, lookup_dict) == -1)
{
Py_DECREF(lookup_dict);
return NULL;
}
Py_DECREF(lookup_dict);
Py_INCREF(self);
return self;
}
static int
ListSetattr(PyObject *self, char *name, PyObject *val)
{
ListObject *this = (ListObject *)(self);
if (val == NULL)
{
PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
return -1;
}
if (strcmp(name, "locked") == 0)
{
if (this->list->lv_lock == VAR_FIXED)
{
PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed list"));
return -1;
}
else
{
if (!PyBool_Check(val))
{
PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
return -1;
}
if (val == Py_True)
this->list->lv_lock = VAR_LOCKED;
else
this->list->lv_lock = 0;
}
return 0;
}
else
{
PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
return -1;
}
}
static struct PyMethodDef ListMethods[] = {
{"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
{ NULL, NULL, 0, NULL }
};
typedef struct
{
PyObject_HEAD
char_u *name;
} FunctionObject;
static PyTypeObject FunctionType;
static PyObject *
FunctionNew(char_u *name)
{
FunctionObject *self;
self = PyObject_NEW(FunctionObject, &FunctionType);
if (self == NULL)
return NULL;
self->name = PyMem_New(char_u, STRLEN(name) + 1);
if (self->name == NULL)
{
PyErr_NoMemory();
return NULL;
}
STRCPY(self->name, name);
func_ref(name);
return (PyObject *)(self);
}
static void
FunctionDestructor(PyObject *self)
{
FunctionObject *this = (FunctionObject *) (self);
func_unref(this->name);
PyMem_Del(this->name);
DESTRUCTOR_FINISH(self);
}
static PyObject *
FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
{
FunctionObject *this = (FunctionObject *)(self);
char_u *name = this->name;
typval_T args;
typval_T selfdicttv;
typval_T rettv;
dict_T *selfdict = NULL;
PyObject *selfdictObject;
PyObject *result;
int error;
if (ConvertFromPyObject(argsObject, &args) == -1)
return NULL;
if (kwargs != NULL)
{
selfdictObject = PyDict_GetItemString(kwargs, "self");
if (selfdictObject != NULL)
{
if (!PyMapping_Check(selfdictObject))
{
PyErr_SetString(PyExc_TypeError,
_("'self' argument must be a dictionary"));
clear_tv(&args);
return NULL;
}
if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
return NULL;
selfdict = selfdicttv.vval.v_dict;
}
}
error = func_call(name, &args, selfdict, &rettv);
if (error != OK)
{
result = NULL;
PyErr_SetVim(_("failed to run function"));
}
else
result = ConvertToPyObject(&rettv);
/* FIXME Check what should really be cleared. */
clear_tv(&args);
clear_tv(&rettv);
/*
* if (selfdict!=NULL)
* clear_tv(selfdicttv);
*/
return result;
}
static struct PyMethodDef FunctionMethods[] = {
{"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
{ NULL, NULL, 0, NULL }
};
/*
* Options object
*/
static PyTypeObject OptionsType;
typedef int (*checkfun)(void *);
typedef struct
{
PyObject_HEAD
int opt_type;
void *from;
checkfun Check;
PyObject *fromObj;
} OptionsObject;
static PyObject *
OptionsItem(OptionsObject *this, PyObject *keyObject)
{
char_u *key;
int flags;
long numval;
char_u *stringval;
DICTKEY_DECL
if (this->Check(this->from))
return NULL;
DICTKEY_GET_NOTEMPTY(NULL)
flags = get_option_value_strict(key, &numval, &stringval,
this->opt_type, this->from);
DICTKEY_UNREF
if (flags == 0)
{
PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
return NULL;
}
if (flags & SOPT_UNSET)
{
Py_INCREF(Py_None);
return Py_None;
}
else if (flags & SOPT_BOOL)
{
PyObject *r;
r = numval ? Py_True : Py_False;
Py_INCREF(r);
return r;
}
else if (flags & SOPT_NUM)
return PyInt_FromLong(numval);
else if (flags & SOPT_STRING)
{
if (stringval)
return PyBytes_FromString((char *) stringval);
else
{
PyErr_SetString(PyExc_ValueError, "Unable to get option value");
return NULL;
}
}
else
{
PyErr_SetVim("Internal error: unknown option type. Should not happen");
return NULL;
}
}
static int
set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
char_u *key;
int numval;
char_u *stringval;
int opt_flags;
int opt_type;
void *from;
{
win_T *save_curwin;
tabpage_T *save_curtab;
aco_save_T aco;
int r = 0;
switch (opt_type)
{
case SREQ_WIN:
if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
== FAIL)
{
PyErr_SetVim("Problem while switching windows.");
return -1;
}
set_option_value(key, numval, stringval, opt_flags);
restore_win(save_curwin, save_curtab);
break;
case SREQ_BUF:
aucmd_prepbuf(&aco, (buf_T *) from);
set_option_value(key, numval, stringval, opt_flags);
aucmd_restbuf(&aco);
break;
case SREQ_GLOBAL:
set_option_value(key, numval, stringval, opt_flags);
break;
}
return r;
}
static int
OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
{
char_u *key;
int flags;
int opt_flags;
int r = 0;
DICTKEY_DECL
if (this->Check(this->from))
return -1;
DICTKEY_GET_NOTEMPTY(-1)
flags = get_option_value_strict(key, NULL, NULL,
this->opt_type, this->from);
DICTKEY_UNREF
if (flags == 0)
{
PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
return -1;
}
if (valObject == NULL)
{
if (this->opt_type == SREQ_GLOBAL)
{
PyErr_SetString(PyExc_ValueError, "Unable to unset global option");
return -1;
}
else if (!(flags & SOPT_GLOBAL))
{
PyErr_SetString(PyExc_ValueError, "Unable to unset option without "
"global value");
return -1;
}
else
{
unset_global_local_option(key, this->from);
return 0;
}
}
opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
if (flags & SOPT_BOOL)
{
if (!PyBool_Check(valObject))
{
PyErr_SetString(PyExc_ValueError, "Object must be boolean");
return -1;
}
r = set_option_value_for(key, (valObject == Py_True), NULL, opt_flags,
this->opt_type, this->from);
}
else if (flags & SOPT_NUM)
{
int val;
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(valObject))
val = PyInt_AsLong(valObject);
else
#endif
if (PyLong_Check(valObject))
val = PyLong_AsLong(valObject);
else
{
PyErr_SetString(PyExc_ValueError, "Object must be integer");
return -1;
}
r = set_option_value_for(key, val, NULL, opt_flags,
this->opt_type, this->from);
}
else
{
char_u *val;
if (PyBytes_Check(valObject))
{
if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
return -1;
if (val == NULL)
return -1;
val = vim_strsave(val);
}
else if (PyUnicode_Check(valObject))
{
PyObject *bytes;
bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
if (bytes == NULL)
return -1;
if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
return -1;
if (val == NULL)
return -1;
val = vim_strsave(val);
Py_XDECREF(bytes);
}
else
{
PyErr_SetString(PyExc_ValueError, "Object must be string");
return -1;
}
r = set_option_value_for(key, 0, val, opt_flags,
this->opt_type, this->from);
vim_free(val);
}
return r;
}
static int
dummy_check(void *arg UNUSED)
{
return 0;
}
static PyObject *
OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
{
OptionsObject *self;
self = PyObject_NEW(OptionsObject, &OptionsType);
if (self == NULL)
return NULL;
self->opt_type = opt_type;
self->from = from;
self->Check = Check;
self->fromObj = fromObj;
if (fromObj)
Py_INCREF(fromObj);
return (PyObject *)(self);
}
static void
OptionsDestructor(PyObject *self)
{
if (((OptionsObject *)(self))->fromObj)
Py_DECREF(((OptionsObject *)(self))->fromObj);
DESTRUCTOR_FINISH(self);
}
static PyMappingMethods OptionsAsMapping = {
(lenfunc) NULL,
(binaryfunc) OptionsItem,
(objobjargproc) OptionsAssItem,
};
/* Window object
*/
typedef struct
{
PyObject_HEAD
win_T *win;
} WindowObject;
static int WindowSetattr(PyObject *, char *, PyObject *);
static PyObject *WindowRepr(PyObject *);
static PyTypeObject WindowType;
static int
CheckWindow(WindowObject *this)
{
if (this->win == INVALID_WINDOW_VALUE)
{
PyErr_SetVim(_("attempt to refer to deleted window"));
return -1;
}
return 0;
}
static PyObject *
WindowNew(win_T *win)
{
/* We need to handle deletion of windows underneath us.
* If we add a "w_python*_ref" field to the win_T structure,
* then we can get at it in win_free() in vim. We then
* need to create only ONE Python object per window - if
* we try to create a second, just INCREF the existing one
* and return it. The (single) Python object referring to
* the window is stored in "w_python*_ref".
* On a win_free() we set the Python object's win_T* field
* to an invalid value. We trap all uses of a window
* object, and reject them if the win_T* field is invalid.
*
* Python2 and Python3 get different fields and different objects:
* w_python_ref and w_python3_ref fields respectively.
*/
WindowObject *self;
if (WIN_PYTHON_REF(win))
{
self = WIN_PYTHON_REF(win);
Py_INCREF(self);
}
else
{
self = PyObject_NEW(WindowObject, &WindowType);
if (self == NULL)
return NULL;
self->win = win;
WIN_PYTHON_REF(win) = self;
}
return (PyObject *)(self);
}
static void
WindowDestructor(PyObject *self)
{
WindowObject *this = (WindowObject *)(self);
if (this->win && this->win != INVALID_WINDOW_VALUE)
WIN_PYTHON_REF(this->win) = NULL;
DESTRUCTOR_FINISH(self);
}
static PyObject *
WindowAttr(WindowObject *this, char *name)
{
if (strcmp(name, "buffer") == 0)
return (PyObject *)BufferNew(this->win->w_buffer);
else if (strcmp(name, "cursor") == 0)
{
pos_T *pos = &this->win->w_cursor;
return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
}
else if (strcmp(name, "height") == 0)
return PyLong_FromLong((long)(this->win->w_height));
#ifdef FEAT_WINDOWS
else if (strcmp(name, "row") == 0)
return PyLong_FromLong((long)(this->win->w_winrow));
#endif
#ifdef FEAT_VERTSPLIT
else if (strcmp(name, "width") == 0)
return PyLong_FromLong((long)(W_WIDTH(this->win)));
else if (strcmp(name, "col") == 0)
return PyLong_FromLong((long)(W_WINCOL(this->win)));
#endif
else if (strcmp(name, "vars") == 0)
return DictionaryNew(this->win->w_vars);
else if (strcmp(name, "options") == 0)
return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
(PyObject *) this);
else if (strcmp(name, "number") == 0)
return PyLong_FromLong((long) get_win_number(this->win));
else if (strcmp(name,"__members__") == 0)
return Py_BuildValue("[ssssssss]", "buffer", "cursor", "height", "vars",
"options", "number", "row", "col");
else
return NULL;
}
static int
WindowSetattr(PyObject *self, char *name, PyObject *val)
{
WindowObject *this = (WindowObject *)(self);
if (CheckWindow(this))
return -1;
if (strcmp(name, "buffer") == 0)
{
PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
return -1;
}
else if (strcmp(name, "cursor") == 0)
{
long lnum;
long col;
if (!PyArg_Parse(val, "(ll)", &lnum, &col))
return -1;
if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
{
PyErr_SetVim(_("cursor position outside buffer"));
return -1;
}
/* Check for keyboard interrupts */
if (VimErrorCheck())
return -1;
this->win->w_cursor.lnum = lnum;
this->win->w_cursor.col = col;
#ifdef FEAT_VIRTUALEDIT
this->win->w_cursor.coladd = 0;
#endif
/* When column is out of range silently correct it. */
check_cursor_col_win(this->win);
update_screen(VALID);
return 0;
}
else if (strcmp(name, "height") == 0)
{
int height;
win_T *savewin;
if (!PyArg_Parse(val, "i", &height))
return -1;
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
savewin = curwin;
curwin = this->win;
win_setheight(height);
curwin = savewin;
/* Check for keyboard interrupts */
if (VimErrorCheck())
return -1;
return 0;
}
#ifdef FEAT_VERTSPLIT
else if (strcmp(name, "width") == 0)
{
int width;
win_T *savewin;
if (!PyArg_Parse(val, "i", &width))
return -1;
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
savewin = curwin;
curwin = this->win;
win_setwidth(width);
curwin = savewin;
/* Check for keyboard interrupts */
if (VimErrorCheck())
return -1;
return 0;
}
#endif
else
{
PyErr_SetString(PyExc_AttributeError, name);
return -1;
}
}
static PyObject *
WindowRepr(PyObject *self)
{
static char repr[100];
WindowObject *this = (WindowObject *)(self);
if (this->win == INVALID_WINDOW_VALUE)
{
vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
return PyString_FromString(repr);
}
else
{
int w = get_win_number(this->win);
if (w == 0)
vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
(self));
else
vim_snprintf(repr, 100, _("<window %d>"), w - 1);
return PyString_FromString(repr);
}
}
static struct PyMethodDef WindowMethods[] = {
/* name, function, calling, documentation */
{ NULL, NULL, 0, NULL }
};
/*
* Window list object
*/
static PyTypeObject WinListType;
static PySequenceMethods WinListAsSeq;
typedef struct
{
PyObject_HEAD
} WinListObject;
static PyInt
WinListLength(PyObject *self UNUSED)
{
win_T *w = firstwin;
PyInt n = 0;
while (w != NULL)
{
++n;
w = W_NEXT(w);
}
return n;
}
static PyObject *
WinListItem(PyObject *self UNUSED, PyInt n)
{
win_T *w;
for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
if (n == 0)
return WindowNew(w);
PyErr_SetString(PyExc_IndexError, _("no such window"));
return NULL;
}
/* Convert a Python string into a Vim line.
*
* The result is in allocated memory. All internal nulls are replaced by
* newline characters. It is an error for the string to contain newline
* characters.
*
* On errors, the Python exception data is set, and NULL is returned.
*/
static char *
StringToLine(PyObject *obj)
{
const char *str;
char *save;
PyObject *bytes;
PyInt len;
PyInt i;
char *p;
if (obj == NULL || !PyString_Check(obj))
{
PyErr_BadArgument();
return NULL;
}
bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
str = PyString_AsString(bytes);
len = PyString_Size(bytes);
/*
* Error checking: String must not contain newlines, as we
* are replacing a single line, and we must replace it with
* a single line.
* A trailing newline is removed, so that append(f.readlines()) works.
*/
p = memchr(str, '\n', len);
if (p != NULL)
{
if (p == str + len - 1)
--len;
else
{
PyErr_SetVim(_("string cannot contain newlines"));
return NULL;
}
}
/* Create a copy of the string, with internal nulls replaced by
* newline characters, as is the vim convention.
*/
save = (char *)alloc((unsigned)(len+1));
if (save == NULL)
{
PyErr_NoMemory();
return NULL;
}
for (i = 0; i < len; ++i)
{
if (str[i] == '\0')
save[i] = '\n';
else
save[i] = str[i];
}
save[i] = '\0';
PyString_FreeBytes(bytes); /* Python 2 does nothing here */
return save;
}
/* Get a line from the specified buffer. The line number is
* in Vim format (1-based). The line is returned as a Python
* string object.
*/
static PyObject *
GetBufferLine(buf_T *buf, PyInt n)
{
return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
}
/* Get a list of lines from the specified buffer. The line numbers
* are in Vim format (1-based). The range is from lo up to, but not
* including, hi. The list is returned as a Python list of string objects.
*/
static PyObject *
GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
{
PyInt i;
PyInt n = hi - lo;
PyObject *list = PyList_New(n);
if (list == NULL)
return NULL;
for (i = 0; i < n; ++i)
{
PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
/* Error check - was the Python string creation OK? */
if (str == NULL)
{
Py_DECREF(list);
return NULL;
}
/* Set the list item */
if (PyList_SetItem(list, i, str))
{
Py_DECREF(str);
Py_DECREF(list);
return NULL;
}
}
/* The ownership of the Python list is passed to the caller (ie,
* the caller should Py_DECREF() the object when it is finished
* with it).
*/
return list;
}
/*
* Check if deleting lines made the cursor position invalid.
* Changed the lines from "lo" to "hi" and added "extra" lines (negative if
* deleted).
*/
static void
py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
{
if (curwin->w_cursor.lnum >= lo)
{
/* Adjust the cursor position if it's in/after the changed
* lines. */
if (curwin->w_cursor.lnum >= hi)
{
curwin->w_cursor.lnum += extra;
check_cursor_col();
}
else if (extra < 0)
{
curwin->w_cursor.lnum = lo;
check_cursor();
}
else
check_cursor_col();
changed_cline_bef_curs();
}
invalidate_botline();
}
/*
* Replace a line in the specified buffer. The line number is
* in Vim format (1-based). The replacement line is given as
* a Python string object. The object is checked for validity
* and correct format. Errors are returned as a value of FAIL.
* The return value is OK on success.
* If OK is returned and len_change is not NULL, *len_change
* is set to the change in the buffer length.
*/
static int
SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
{
/* First of all, we check the type of the supplied Python object.
* There are three cases:
* 1. NULL, or None - this is a deletion.
* 2. A string - this is a replacement.
* 3. Anything else - this is an error.
*/
if (line == Py_None || line == NULL)
{
buf_T *savebuf = curbuf;
PyErr_Clear();
curbuf = buf;
if (u_savedel((linenr_T)n, 1L) == FAIL)
PyErr_SetVim(_("cannot save undo information"));
else if (ml_delete((linenr_T)n, FALSE) == FAIL)
PyErr_SetVim(_("cannot delete line"));
else
{
if (buf == curwin->w_buffer)
py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
deleted_lines_mark((linenr_T)n, 1L);
}
curbuf = savebuf;
if (PyErr_Occurred() || VimErrorCheck())
return FAIL;
if (len_change)
*len_change = -1;
return OK;
}
else if (PyString_Check(line))
{
char *save = StringToLine(line);
buf_T *savebuf = curbuf;
if (save == NULL)
return FAIL;
/* We do not need to free "save" if ml_replace() consumes it. */
PyErr_Clear();
curbuf = buf;
if (u_savesub((linenr_T)n) == FAIL)
{
PyErr_SetVim(_("cannot save undo information"));
vim_free(save);
}
else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
{
PyErr_SetVim(_("cannot replace line"));
vim_free(save);
}
else
changed_bytes((linenr_T)n, 0);
curbuf = savebuf;
/* Check that the cursor is not beyond the end of the line now. */
if (buf == curwin->w_buffer)
check_cursor_col();
if (PyErr_Occurred() || VimErrorCheck())
return FAIL;
if (len_change)
*len_change = 0;
return OK;
}
else
{
PyErr_BadArgument();
return FAIL;
}
}
/* Replace a range of lines in the specified buffer. The line numbers are in
* Vim format (1-based). The range is from lo up to, but not including, hi.
* The replacement lines are given as a Python list of string objects. The
* list is checked for validity and correct format. Errors are returned as a
* value of FAIL. The return value is OK on success.
* If OK is returned and len_change is not NULL, *len_change
* is set to the change in the buffer length.
*/
static int
SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
{
/* First of all, we check the type of the supplied Python object.
* There are three cases:
* 1. NULL, or None - this is a deletion.
* 2. A list - this is a replacement.
* 3. Anything else - this is an error.
*/
if (list == Py_None || list == NULL)
{
PyInt i;
PyInt n = (int)(hi - lo);
buf_T *savebuf = curbuf;
PyErr_Clear();
curbuf = buf;
if (u_savedel((linenr_T)lo, (long)n) == FAIL)
PyErr_SetVim(_("cannot save undo information"));
else
{
for (i = 0; i < n; ++i)
{
if (ml_delete((linenr_T)lo, FALSE) == FAIL)
{
PyErr_SetVim(_("cannot delete line"));
break;
}
}
if (buf == curwin->w_buffer)
py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
deleted_lines_mark((linenr_T)lo, (long)i);
}
curbuf = savebuf;
if (PyErr_Occurred() || VimErrorCheck())
return FAIL;
if (len_change)
*len_change = -n;
return OK;
}
else if (PyList_Check(list))
{
PyInt i;
PyInt new_len = PyList_Size(list);
PyInt old_len = hi - lo;
PyInt extra = 0; /* lines added to text, can be negative */
char **array;
buf_T *savebuf;
if (new_len == 0) /* avoid allocating zero bytes */
array = NULL;
else
{
array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
if (array == NULL)
{
PyErr_NoMemory();
return FAIL;
}
}
for (i = 0; i < new_len; ++i)
{
PyObject *line = PyList_GetItem(list, i);
array[i] = StringToLine(line);
if (array[i] == NULL)
{
while (i)
vim_free(array[--i]);
vim_free(array);
return FAIL;
}
}
savebuf = curbuf;
PyErr_Clear();
curbuf = buf;
if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
PyErr_SetVim(_("cannot save undo information"));
/* If the size of the range is reducing (ie, new_len < old_len) we
* need to delete some old_len. We do this at the start, by
* repeatedly deleting line "lo".
*/
if (!PyErr_Occurred())
{
for (i = 0; i < old_len - new_len; ++i)
if (ml_delete((linenr_T)lo, FALSE) == FAIL)
{
PyErr_SetVim(_("cannot delete line"));
break;
}
extra -= i;
}
/* For as long as possible, replace the existing old_len with the
* new old_len. This is a more efficient operation, as it requires
* less memory allocation and freeing.
*/
if (!PyErr_Occurred())
{
for (i = 0; i < old_len && i < new_len; ++i)
if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
== FAIL)
{
PyErr_SetVim(_("cannot replace line"));
break;
}
}
else
i = 0;
/* Now we may need to insert the remaining new old_len. If we do, we
* must free the strings as we finish with them (we can't pass the
* responsibility to vim in this case).
*/
if (!PyErr_Occurred())
{
while (i < new_len)
{
if (ml_append((linenr_T)(lo + i - 1),
(char_u *)array[i], 0, FALSE) == FAIL)
{
PyErr_SetVim(_("cannot insert line"));
break;
}
vim_free(array[i]);
++i;
++extra;
}
}
/* Free any left-over old_len, as a result of an error */
while (i < new_len)
{
vim_free(array[i]);
++i;
}
/* Free the array of old_len. All of its contents have now
* been dealt with (either freed, or the responsibility passed
* to vim.
*/
vim_free(array);
/* Adjust marks. Invalidate any which lie in the
* changed range, and move any in the remainder of the buffer.
*/
mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
(long)MAXLNUM, (long)extra);
changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
if (buf == curwin->w_buffer)
py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
curbuf = savebuf;
if (PyErr_Occurred() || VimErrorCheck())
return FAIL;
if (len_change)
*len_change = new_len - old_len;
return OK;
}
else
{
PyErr_BadArgument();
return FAIL;
}
}
/* Insert a number of lines into the specified buffer after the specified line.
* The line number is in Vim format (1-based). The lines to be inserted are
* given as a Python list of string objects or as a single string. The lines
* to be added are checked for validity and correct format. Errors are
* returned as a value of FAIL. The return value is OK on success.
* If OK is returned and len_change is not NULL, *len_change
* is set to the change in the buffer length.
*/
static int
InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
{
/* First of all, we check the type of the supplied Python object.
* It must be a string or a list, or the call is in error.
*/
if (PyString_Check(lines))
{
char *str = StringToLine(lines);
buf_T *savebuf;
if (str == NULL)
return FAIL;
savebuf = curbuf;
PyErr_Clear();
curbuf = buf;
if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
PyErr_SetVim(_("cannot save undo information"));
else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
PyErr_SetVim(_("cannot insert line"));
else
appended_lines_mark((linenr_T)n, 1L);
vim_free(str);
curbuf = savebuf;
update_screen(VALID);
if (PyErr_Occurred() || VimErrorCheck())
return FAIL;
if (len_change)
*len_change = 1;
return OK;
}
else if (PyList_Check(lines))
{
PyInt i;
PyInt size = PyList_Size(lines);
char **array;
buf_T *savebuf;
array = (char **)alloc((unsigned)(size * sizeof(char *)));
if (array == NULL)
{
PyErr_NoMemory();
return FAIL;
}
for (i = 0; i < size; ++i)
{
PyObject *line = PyList_GetItem(lines, i);
array[i] = StringToLine(line);
if (array[i] == NULL)
{
while (i)
vim_free(array[--i]);
vim_free(array);
return FAIL;
}
}
savebuf = curbuf;
PyErr_Clear();
curbuf = buf;
if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
PyErr_SetVim(_("cannot save undo information"));
else
{
for (i = 0; i < size; ++i)
{
if (ml_append((linenr_T)(n + i),
(char_u *)array[i], 0, FALSE) == FAIL)
{
PyErr_SetVim(_("cannot insert line"));
/* Free the rest of the lines */
while (i < size)
vim_free(array[i++]);
break;
}
vim_free(array[i]);
}
if (i > 0)
appended_lines_mark((linenr_T)n, (long)i);
}
/* Free the array of lines. All of its contents have now
* been freed.
*/
vim_free(array);
curbuf = savebuf;
update_screen(VALID);
if (PyErr_Occurred() || VimErrorCheck())
return FAIL;
if (len_change)
*len_change = size;
return OK;
}
else
{
PyErr_BadArgument();
return FAIL;
}
}
/*
* Common routines for buffers and line ranges
* -------------------------------------------
*/
typedef struct
{
PyObject_HEAD
buf_T *buf;
} BufferObject;
static int
CheckBuffer(BufferObject *this)
{
if (this->buf == INVALID_BUFFER_VALUE)
{
PyErr_SetVim(_("attempt to refer to deleted buffer"));
return -1;
}
return 0;
}
static PyObject *
RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
{
if (CheckBuffer(self))
return NULL;
if (end == -1)
end = self->buf->b_ml.ml_line_count;
if (n < 0)
n += end - start + 1;
if (n < 0 || n > end - start)
{
PyErr_SetString(PyExc_IndexError, _("line number out of range"));
return NULL;
}
return GetBufferLine(self->buf, n+start);
}
static PyObject *
RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
{
PyInt size;
if (CheckBuffer(self))
return NULL;
if (end == -1)
end = self->buf->b_ml.ml_line_count;
size = end - start + 1;
if (lo < 0)
lo = 0;
else if (lo > size)
lo = size;
if (hi < 0)
hi = 0;
if (hi < lo)
hi = lo;
else if (hi > size)
hi = size;
return GetBufferLineList(self->buf, lo+start, hi+start);
}
static PyInt
RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
{
PyInt len_change;
if (CheckBuffer(self))
return -1;
if (end == -1)
end = self->buf->b_ml.ml_line_count;
if (n < 0)
n += end - start + 1;
if (n < 0 || n > end - start)
{
PyErr_SetString(PyExc_IndexError, _("line number out of range"));
return -1;
}
if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
return -1;
if (new_end)
*new_end = end + len_change;
return 0;
}
static PyInt
RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
{
PyInt size;
PyInt len_change;
/* Self must be a valid buffer */
if (CheckBuffer(self))
return -1;
if (end == -1)
end = self->buf->b_ml.ml_line_count;
/* Sort out the slice range */
size = end - start + 1;
if (lo < 0)
lo = 0;
else if (lo > size)
lo = size;
if (hi < 0)
hi = 0;
if (hi < lo)
hi = lo;
else if (hi > size)
hi = size;
if (SetBufferLineList(self->buf, lo + start, hi + start,
val, &len_change) == FAIL)
return -1;
if (new_end)
*new_end = end + len_change;
return 0;
}
static PyObject *
RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
{
PyObject *lines;
PyInt len_change;
PyInt max;
PyInt n;
if (CheckBuffer(self))
return NULL;
if (end == -1)
end = self->buf->b_ml.ml_line_count;
max = n = end - start + 1;
if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
return NULL;
if (n < 0 || n > max)
{
PyErr_SetString(PyExc_ValueError, _("line number out of range"));
return NULL;
}
if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
return NULL;
if (new_end)
*new_end = end + len_change;
Py_INCREF(Py_None);
return Py_None;
}
/* Range object
*/
static PyTypeObject RangeType;
static PySequenceMethods RangeAsSeq;
static PyMappingMethods RangeAsMapping;
typedef struct
{
PyObject_HEAD
BufferObject *buf;
PyInt start;
PyInt end;
} RangeObject;
static PyObject *
RangeNew(buf_T *buf, PyInt start, PyInt end)
{
BufferObject *bufr;
RangeObject *self;
self = PyObject_NEW(RangeObject, &RangeType);
if (self == NULL)
return NULL;
bufr = (BufferObject *)BufferNew(buf);
if (bufr == NULL)
{
Py_DECREF(self);
return NULL;
}
Py_INCREF(bufr);
self->buf = bufr;
self->start = start;
self->end = end;
return (PyObject *)(self);
}
static void
RangeDestructor(PyObject *self)
{
Py_DECREF(((RangeObject *)(self))->buf);
DESTRUCTOR_FINISH(self);
}
static PyInt
RangeLength(PyObject *self)
{
/* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
if (CheckBuffer(((RangeObject *)(self))->buf))
return -1; /* ??? */
return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
}
static PyObject *
RangeItem(PyObject *self, PyInt n)
{
return RBItem(((RangeObject *)(self))->buf, n,
((RangeObject *)(self))->start,
((RangeObject *)(self))->end);
}
static PyObject *
RangeSlice(PyObject *self, PyInt lo, PyInt hi)
{
return RBSlice(((RangeObject *)(self))->buf, lo, hi,
((RangeObject *)(self))->start,
((RangeObject *)(self))->end);
}
static PyObject *
RangeAppend(PyObject *self, PyObject *args)
{
return RBAppend(((RangeObject *)(self))->buf, args,
((RangeObject *)(self))->start,
((RangeObject *)(self))->end,
&((RangeObject *)(self))->end);
}
static PyObject *
RangeRepr(PyObject *self)
{
static char repr[100];
RangeObject *this = (RangeObject *)(self);
if (this->buf->buf == INVALID_BUFFER_VALUE)
{
vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
(self));
return PyString_FromString(repr);
}
else
{
char *name = (char *)this->buf->buf->b_fname;
int len;
if (name == NULL)
name = "";
len = (int)strlen(name);
if (len > 45)
name = name + (45 - len);
vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
len > 45 ? "..." : "", name,
this->start, this->end);
return PyString_FromString(repr);
}
}
static struct PyMethodDef RangeMethods[] = {
/* name, function, calling, documentation */
{"append", RangeAppend, 1, "Append data to the Vim range" },
{ NULL, NULL, 0, NULL }
};
static PyTypeObject BufferType;
static PySequenceMethods BufferAsSeq;
static PyMappingMethods BufferAsMapping;
static PyObject *
BufferNew(buf_T *buf)
{
/* We need to handle deletion of buffers underneath us.
* If we add a "b_python*_ref" field to the buf_T structure,
* then we can get at it in buf_freeall() in vim. We then
* need to create only ONE Python object per buffer - if
* we try to create a second, just INCREF the existing one
* and return it. The (single) Python object referring to
* the buffer is stored in "b_python*_ref".
* Question: what to do on a buf_freeall(). We'll probably
* have to either delete the Python object (DECREF it to
* zero - a bad idea, as it leaves dangling refs!) or
* set the buf_T * value to an invalid value (-1?), which
* means we need checks in all access functions... Bah.
*
* Python2 and Python3 get different fields and different objects:
* b_python_ref and b_python3_ref fields respectively.
*/
BufferObject *self;
if (BUF_PYTHON_REF(buf) != NULL)
{
self = BUF_PYTHON_REF(buf);
Py_INCREF(self);
}
else
{
self = PyObject_NEW(BufferObject, &BufferType);
if (self == NULL)
return NULL;
self->buf = buf;
BUF_PYTHON_REF(buf) = self;
}
return (PyObject *)(self);
}
static void
BufferDestructor(PyObject *self)
{
BufferObject *this = (BufferObject *)(self);
if (this->buf && this->buf != INVALID_BUFFER_VALUE)
BUF_PYTHON_REF(this->buf) = NULL;
DESTRUCTOR_FINISH(self);
}
static PyInt
BufferLength(PyObject *self)
{
/* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
if (CheckBuffer((BufferObject *)(self)))
return -1; /* ??? */
return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
}
static PyObject *
BufferItem(PyObject *self, PyInt n)
{
return RBItem((BufferObject *)(self), n, 1, -1);
}
static PyObject *
BufferSlice(PyObject *self, PyInt lo, PyInt hi)
{
return RBSlice((BufferObject *)(self), lo, hi, 1, -1);
}
static PyObject *
BufferAttr(BufferObject *this, char *name)
{
if (strcmp(name, "name") == 0)
return Py_BuildValue("s", this->buf->b_ffname);
else if (strcmp(name, "number") == 0)
return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
else if (strcmp(name, "vars") == 0)
return DictionaryNew(this->buf->b_vars);
else if (strcmp(name, "options") == 0)
return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
(PyObject *) this);
else if (strcmp(name,"__members__") == 0)
return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
else
return NULL;
}
static PyObject *
BufferAppend(PyObject *self, PyObject *args)
{
return RBAppend((BufferObject *)(self), args, 1, -1, NULL);
}
static PyObject *
BufferMark(PyObject *self, PyObject *args)
{
pos_T *posp;
char *pmark;
char mark;
buf_T *curbuf_save;
if (CheckBuffer((BufferObject *)(self)))
return NULL;
if (!PyArg_ParseTuple(args, "s", &pmark))
return NULL;
mark = *pmark;
curbuf_save = curbuf;
curbuf = ((BufferObject *)(self))->buf;
posp = getmark(mark, FALSE);
curbuf = curbuf_save;
if (posp == NULL)
{
PyErr_SetVim(_("invalid mark name"));
return NULL;
}
/* Check for keyboard interrupt */
if (VimErrorCheck())
return NULL;
if (posp->lnum <= 0)
{
/* Or raise an error? */
Py_INCREF(Py_None);
return Py_None;
}
return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
}
static PyObject *
BufferRange(PyObject *self, PyObject *args)
{
PyInt start;
PyInt end;
if (CheckBuffer((BufferObject *)(self)))
return NULL;
if (!PyArg_ParseTuple(args, "nn", &start, &end))
return NULL;
return RangeNew(((BufferObject *)(self))->buf, start, end);
}
static PyObject *
BufferRepr(PyObject *self)
{
static char repr[100];
BufferObject *this = (BufferObject *)(self);
if (this->buf == INVALID_BUFFER_VALUE)
{
vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
return PyString_FromString(repr);
}
else
{
char *name = (char *)this->buf->b_fname;
PyInt len;
if (name == NULL)
name = "";
len = strlen(name);
if (len > 35)
name = name + (35 - len);
vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
return PyString_FromString(repr);
}
}
static struct PyMethodDef BufferMethods[] = {
/* name, function, calling, documentation */
{"append", BufferAppend, 1, "Append data to Vim buffer" },
{"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
{"range", BufferRange, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
#if PY_VERSION_HEX >= 0x03000000
{"__dir__", BufferDir, 4, "List its attributes" },
#endif
{ NULL, NULL, 0, NULL }
};
/*
* Buffer list object - Implementation
*/
static PyTypeObject BufMapType;
typedef struct
{
PyObject_HEAD
} BufMapObject;
static PyInt
BufMapLength(PyObject *self UNUSED)
{
buf_T *b = firstbuf;
PyInt n = 0;
while (b)
{
++n;
b = b->b_next;
}
return n;
}
static PyObject *
BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
{
buf_T *b;
int bnr;
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(keyObject))
bnr = PyInt_AsLong(keyObject);
else
#endif
if (PyLong_Check(keyObject))
bnr = PyLong_AsLong(keyObject);
else
{
PyErr_SetString(PyExc_ValueError, _("key must be integer"));
return NULL;
}
b = buflist_findnr(bnr);
if (b)
return BufferNew(b);
else
{
PyErr_SetString(PyExc_KeyError, _("no such buffer"));
return NULL;
}
}
static void
BufMapIterDestruct(PyObject *buffer)
{
/* Iteration was stopped before all buffers were processed */
if (buffer)
{
Py_DECREF(buffer);
}
}
static PyObject *
BufMapIterNext(PyObject **buffer)
{
PyObject *next;
PyObject *r;
if (!*buffer)
return NULL;
r = *buffer;
if (CheckBuffer((BufferObject *)(r)))
{
*buffer = NULL;
return NULL;
}
if (!((BufferObject *)(r))->buf->b_next)
next = NULL;
else if (!(next = BufferNew(((BufferObject *)(r))->buf->b_next)))
return NULL;
*buffer = next;
/* Do not increment reference: we no longer hold it (decref), but whoever on
* other side will hold (incref). Decref+incref = nothing.
*/
return r;
}
static PyObject *
BufMapIter(PyObject *self UNUSED)
{
PyObject *buffer;
buffer = BufferNew(firstbuf);
return IterNew(buffer,
(destructorfun) BufMapIterDestruct, (nextfun) BufMapIterNext);
}
static PyMappingMethods BufMapAsMapping = {
(lenfunc) BufMapLength,
(binaryfunc) BufMapItem,
(objobjargproc) 0,
};
/* Current items object
*/
static PyObject *
CurrentGetattr(PyObject *self UNUSED, char *name)
{
if (strcmp(name, "buffer") == 0)
return (PyObject *)BufferNew(curbuf);
else if (strcmp(name, "window") == 0)
return (PyObject *)WindowNew(curwin);
else if (strcmp(name, "line") == 0)
return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
else if (strcmp(name, "range") == 0)
return RangeNew(curbuf, RangeStart, RangeEnd);
else if (strcmp(name,"__members__") == 0)
return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
else
{
PyErr_SetString(PyExc_AttributeError, name);
return NULL;
}
}
static int
CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
{
if (strcmp(name, "line") == 0)
{
if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
return -1;
return 0;
}
else
{
PyErr_SetString(PyExc_AttributeError, name);
return -1;
}
}
static void
set_ref_in_py(const int copyID)
{
pylinkedlist_T *cur;
dict_T *dd;
list_T *ll;
if (lastdict != NULL)
for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
{
dd = ((DictionaryObject *) (cur->pll_obj))->dict;
if (dd->dv_copyID != copyID)
{
dd->dv_copyID = copyID;
set_ref_in_ht(&dd->dv_hashtab, copyID);
}
}
if (lastlist != NULL)
for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
{
ll = ((ListObject *) (cur->pll_obj))->list;
if (ll->lv_copyID != copyID)
{
ll->lv_copyID = copyID;
set_ref_in_list(ll, copyID);
}
}
}
static int
set_string_copy(char_u *str, typval_T *tv)
{
tv->vval.v_string = vim_strsave(str);
if (tv->vval.v_string == NULL)
{
PyErr_NoMemory();
return -1;
}
return 0;
}
static int
pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
{
dict_T *d;
char_u *key;
dictitem_T *di;
PyObject *keyObject;
PyObject *valObject;
Py_ssize_t iter = 0;
d = dict_alloc();
if (d == NULL)
{
PyErr_NoMemory();
return -1;
}
tv->v_type = VAR_DICT;
tv->vval.v_dict = d;
while (PyDict_Next(obj, &iter, &keyObject, &valObject))
{
DICTKEY_DECL
if (keyObject == NULL)
return -1;
if (valObject == NULL)
return -1;
DICTKEY_GET_NOTEMPTY(-1)
di = dictitem_alloc(key);
DICTKEY_UNREF
if (di == NULL)
{
PyErr_NoMemory();
return -1;
}
di->di_tv.v_lock = 0;
if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
{
vim_free(di);
return -1;
}
if (dict_add(d, di) == FAIL)
{
vim_free(di);
PyErr_SetVim(_("failed to add key to dictionary"));
return -1;
}
}
return 0;
}
static int
pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
{
dict_T *d;
char_u *key;
dictitem_T *di;
PyObject *list;
PyObject *litem;
PyObject *keyObject;
PyObject *valObject;
Py_ssize_t lsize;
d = dict_alloc();
if (d == NULL)
{
PyErr_NoMemory();
return -1;
}
tv->v_type = VAR_DICT;
tv->vval.v_dict = d;
list = PyMapping_Items(obj);
if (list == NULL)
return -1;
lsize = PyList_Size(list);
while (lsize--)
{
DICTKEY_DECL
litem = PyList_GetItem(list, lsize);
if (litem == NULL)
{
Py_DECREF(list);
return -1;
}
keyObject = PyTuple_GetItem(litem, 0);
if (keyObject == NULL)
{
Py_DECREF(list);
Py_DECREF(litem);
return -1;
}
DICTKEY_GET_NOTEMPTY(-1)
valObject = PyTuple_GetItem(litem, 1);
if (valObject == NULL)
{
Py_DECREF(list);
Py_DECREF(litem);
return -1;
}
di = dictitem_alloc(key);
DICTKEY_UNREF
if (di == NULL)
{
Py_DECREF(list);
Py_DECREF(litem);
PyErr_NoMemory();
return -1;
}
di->di_tv.v_lock = 0;
if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
{
vim_free(di);
Py_DECREF(list);
Py_DECREF(litem);
return -1;
}
if (dict_add(d, di) == FAIL)
{
vim_free(di);
Py_DECREF(list);
Py_DECREF(litem);
PyErr_SetVim(_("failed to add key to dictionary"));
return -1;
}
Py_DECREF(litem);
}
Py_DECREF(list);
return 0;
}
static int
pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
{
list_T *l;
l = list_alloc();
if (l == NULL)
{
PyErr_NoMemory();
return -1;
}
tv->v_type = VAR_LIST;
tv->vval.v_list = l;
if (list_py_concat(l, obj, lookupDict) == -1)
return -1;
return 0;
}
static int
pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
{
PyObject *iterator = PyObject_GetIter(obj);
PyObject *item;
list_T *l;
listitem_T *li;
l = list_alloc();
if (l == NULL)
{
PyErr_NoMemory();
return -1;
}
tv->vval.v_list = l;
tv->v_type = VAR_LIST;
if (iterator == NULL)
return -1;
while ((item = PyIter_Next(obj)))
{
li = listitem_alloc();
if (li == NULL)
{
PyErr_NoMemory();
return -1;
}
li->li_tv.v_lock = 0;
if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
return -1;
list_append(l, li);
Py_DECREF(item);
}
Py_DECREF(iterator);
return 0;
}
typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
static int
convert_dl(PyObject *obj, typval_T *tv,
pytotvfunc py_to_tv, PyObject *lookupDict)
{
PyObject *capsule;
char hexBuf[sizeof(void *) * 2 + 3];
sprintf(hexBuf, "%p", obj);
# ifdef PY_USE_CAPSULE
capsule = PyDict_GetItemString(lookupDict, hexBuf);
# else
capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
# endif
if (capsule == NULL)
{
# ifdef PY_USE_CAPSULE
capsule = PyCapsule_New(tv, NULL, NULL);
# else
capsule = PyCObject_FromVoidPtr(tv, NULL);
# endif
PyDict_SetItemString(lookupDict, hexBuf, capsule);
Py_DECREF(capsule);
if (py_to_tv(obj, tv, lookupDict) == -1)
{
tv->v_type = VAR_UNKNOWN;
return -1;
}
/* As we are not using copy_tv which increments reference count we must
* do it ourself. */
switch(tv->v_type)
{
case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
}
}
else
{
typval_T *v;
# ifdef PY_USE_CAPSULE
v = PyCapsule_GetPointer(capsule, NULL);
# else
v = PyCObject_AsVoidPtr(capsule);
# endif
copy_tv(v, tv);
}
return 0;
}
static int
ConvertFromPyObject(PyObject *obj, typval_T *tv)
{
PyObject *lookup_dict;
int r;
lookup_dict = PyDict_New();
r = _ConvertFromPyObject(obj, tv, lookup_dict);
Py_DECREF(lookup_dict);
return r;
}
static int
_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
{
if (obj->ob_type == &DictionaryType)
{
tv->v_type = VAR_DICT;
tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
++tv->vval.v_dict->dv_refcount;
}
else if (obj->ob_type == &ListType)
{
tv->v_type = VAR_LIST;
tv->vval.v_list = (((ListObject *)(obj))->list);
++tv->vval.v_list->lv_refcount;
}
else if (obj->ob_type == &FunctionType)
{
if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
return -1;
tv->v_type = VAR_FUNC;
func_ref(tv->vval.v_string);
}
else if (PyBytes_Check(obj))
{
char_u *result;
if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
return -1;
if (result == NULL)
return -1;
if (set_string_copy(result, tv) == -1)
return -1;
tv->v_type = VAR_STRING;
}
else if (PyUnicode_Check(obj))
{
PyObject *bytes;
char_u *result;
bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
if (bytes == NULL)
return -1;
if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
return -1;
if (result == NULL)
return -1;
if (set_string_copy(result, tv) == -1)
{
Py_XDECREF(bytes);
return -1;
}
Py_XDECREF(bytes);
tv->v_type = VAR_STRING;
}
#if PY_MAJOR_VERSION < 3
else if (PyInt_Check(obj))
{
tv->v_type = VAR_NUMBER;
tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
}
#endif
else if (PyLong_Check(obj))
{
tv->v_type = VAR_NUMBER;
tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
}
else if (PyDict_Check(obj))
return convert_dl(obj, tv, pydict_to_tv, lookupDict);
#ifdef FEAT_FLOAT
else if (PyFloat_Check(obj))
{
tv->v_type = VAR_FLOAT;
tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
}
#endif
else if (PyIter_Check(obj))
return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
else if (PySequence_Check(obj))
return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
else if (PyMapping_Check(obj))
return convert_dl(obj, tv, pymap_to_tv, lookupDict);
else
{
PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
return -1;
}
return 0;
}
static PyObject *
ConvertToPyObject(typval_T *tv)
{
if (tv == NULL)
{
PyErr_SetVim(_("NULL reference passed"));
return NULL;
}
switch (tv->v_type)
{
case VAR_STRING:
return PyBytes_FromString(tv->vval.v_string == NULL
? "" : (char *)tv->vval.v_string);
case VAR_NUMBER:
return PyLong_FromLong((long) tv->vval.v_number);
#ifdef FEAT_FLOAT
case VAR_FLOAT:
return PyFloat_FromDouble((double) tv->vval.v_float);
#endif
case VAR_LIST:
return ListNew(tv->vval.v_list);
case VAR_DICT:
return DictionaryNew(tv->vval.v_dict);
case VAR_FUNC:
return FunctionNew(tv->vval.v_string == NULL
? (char_u *)"" : tv->vval.v_string);
case VAR_UNKNOWN:
Py_INCREF(Py_None);
return Py_None;
default:
PyErr_SetVim(_("internal error: invalid value type"));
return NULL;
}
}
typedef struct
{
PyObject_HEAD
} CurrentObject;
static PyTypeObject CurrentType;
static void
init_structs(void)
{
vim_memset(&OutputType, 0, sizeof(OutputType));
OutputType.tp_name = "vim.message";
OutputType.tp_basicsize = sizeof(OutputObject);
OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
OutputType.tp_doc = "vim message object";
OutputType.tp_methods = OutputMethods;
#if PY_MAJOR_VERSION >= 3
OutputType.tp_getattro = OutputGetattro;
OutputType.tp_setattro = OutputSetattro;
OutputType.tp_alloc = call_PyType_GenericAlloc;
OutputType.tp_new = call_PyType_GenericNew;
OutputType.tp_free = call_PyObject_Free;
#else
OutputType.tp_getattr = OutputGetattr;
OutputType.tp_setattr = OutputSetattr;
#endif
vim_memset(&IterType, 0, sizeof(IterType));
IterType.tp_name = "vim.iter";
IterType.tp_basicsize = sizeof(IterObject);
IterType.tp_flags = Py_TPFLAGS_DEFAULT;
IterType.tp_doc = "generic iterator object";
IterType.tp_iter = IterIter;
IterType.tp_iternext = IterNext;
vim_memset(&BufferType, 0, sizeof(BufferType));
BufferType.tp_name = "vim.buffer";
BufferType.tp_basicsize = sizeof(BufferType);
BufferType.tp_dealloc = BufferDestructor;
BufferType.tp_repr = BufferRepr;
BufferType.tp_as_sequence = &BufferAsSeq;
BufferType.tp_as_mapping = &BufferAsMapping;
BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
BufferType.tp_doc = "vim buffer object";
BufferType.tp_methods = BufferMethods;
#if PY_MAJOR_VERSION >= 3
BufferType.tp_getattro = BufferGetattro;
BufferType.tp_alloc = call_PyType_GenericAlloc;
BufferType.tp_new = call_PyType_GenericNew;
BufferType.tp_free = call_PyObject_Free;
#else
BufferType.tp_getattr = BufferGetattr;
#endif
vim_memset(&WindowType, 0, sizeof(WindowType));
WindowType.tp_name = "vim.window";
WindowType.tp_basicsize = sizeof(WindowObject);
WindowType.tp_dealloc = WindowDestructor;
WindowType.tp_repr = WindowRepr;
WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
WindowType.tp_doc = "vim Window object";
WindowType.tp_methods = WindowMethods;
#if PY_MAJOR_VERSION >= 3
WindowType.tp_getattro = WindowGetattro;
WindowType.tp_setattro = WindowSetattro;
WindowType.tp_alloc = call_PyType_GenericAlloc;
WindowType.tp_new = call_PyType_GenericNew;
WindowType.tp_free = call_PyObject_Free;
#else
WindowType.tp_getattr = WindowGetattr;
WindowType.tp_setattr = WindowSetattr;
#endif
vim_memset(&BufMapType, 0, sizeof(BufMapType));
BufMapType.tp_name = "vim.bufferlist";
BufMapType.tp_basicsize = sizeof(BufMapObject);
BufMapType.tp_as_mapping = &BufMapAsMapping;
BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
BufMapType.tp_iter = BufMapIter;
BufferType.tp_doc = "vim buffer list";
vim_memset(&WinListType, 0, sizeof(WinListType));
WinListType.tp_name = "vim.windowlist";
WinListType.tp_basicsize = sizeof(WinListType);
WinListType.tp_as_sequence = &WinListAsSeq;
WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
WinListType.tp_doc = "vim window list";
vim_memset(&RangeType, 0, sizeof(RangeType));
RangeType.tp_name = "vim.range";
RangeType.tp_basicsize = sizeof(RangeObject);
RangeType.tp_dealloc = RangeDestructor;
RangeType.tp_repr = RangeRepr;
RangeType.tp_as_sequence = &RangeAsSeq;
RangeType.tp_as_mapping = &RangeAsMapping;
RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
RangeType.tp_doc = "vim Range object";
RangeType.tp_methods = RangeMethods;
#if PY_MAJOR_VERSION >= 3
RangeType.tp_getattro = RangeGetattro;
RangeType.tp_alloc = call_PyType_GenericAlloc;
RangeType.tp_new = call_PyType_GenericNew;
RangeType.tp_free = call_PyObject_Free;
#else
RangeType.tp_getattr = RangeGetattr;
#endif
vim_memset(&CurrentType, 0, sizeof(CurrentType));
CurrentType.tp_name = "vim.currentdata";
CurrentType.tp_basicsize = sizeof(CurrentObject);
CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
CurrentType.tp_doc = "vim current object";
#if PY_MAJOR_VERSION >= 3
CurrentType.tp_getattro = CurrentGetattro;
CurrentType.tp_setattro = CurrentSetattro;
#else
CurrentType.tp_getattr = CurrentGetattr;
CurrentType.tp_setattr = CurrentSetattr;
#endif
vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
DictionaryType.tp_name = "vim.dictionary";
DictionaryType.tp_basicsize = sizeof(DictionaryObject);
DictionaryType.tp_dealloc = DictionaryDestructor;
DictionaryType.tp_as_mapping = &DictionaryAsMapping;
DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
DictionaryType.tp_methods = DictionaryMethods;
#if PY_MAJOR_VERSION >= 3
DictionaryType.tp_getattro = DictionaryGetattro;
DictionaryType.tp_setattro = DictionarySetattro;
#else
DictionaryType.tp_getattr = DictionaryGetattr;
DictionaryType.tp_setattr = DictionarySetattr;
#endif
vim_memset(&ListType, 0, sizeof(ListType));
ListType.tp_name = "vim.list";
ListType.tp_dealloc = ListDestructor;
ListType.tp_basicsize = sizeof(ListObject);
ListType.tp_as_sequence = &ListAsSeq;
ListType.tp_as_mapping = &ListAsMapping;
ListType.tp_flags = Py_TPFLAGS_DEFAULT;
ListType.tp_doc = "list pushing modifications to vim structure";
ListType.tp_methods = ListMethods;
ListType.tp_iter = ListIter;
#if PY_MAJOR_VERSION >= 3
ListType.tp_getattro = ListGetattro;
ListType.tp_setattro = ListSetattro;
#else
ListType.tp_getattr = ListGetattr;
ListType.tp_setattr = ListSetattr;
#endif
vim_memset(&FunctionType, 0, sizeof(FunctionType));
FunctionType.tp_name = "vim.function";
FunctionType.tp_basicsize = sizeof(FunctionObject);
FunctionType.tp_dealloc = FunctionDestructor;
FunctionType.tp_call = FunctionCall;
FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
FunctionType.tp_doc = "object that calls vim function";
FunctionType.tp_methods = FunctionMethods;
#if PY_MAJOR_VERSION >= 3
FunctionType.tp_getattro = FunctionGetattro;
#else
FunctionType.tp_getattr = FunctionGetattr;
#endif
vim_memset(&OptionsType, 0, sizeof(OptionsType));
OptionsType.tp_name = "vim.options";
OptionsType.tp_basicsize = sizeof(OptionsObject);
OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
OptionsType.tp_doc = "object for manipulating options";
OptionsType.tp_as_mapping = &OptionsAsMapping;
OptionsType.tp_dealloc = OptionsDestructor;
#if PY_MAJOR_VERSION >= 3
vim_memset(&vimmodule, 0, sizeof(vimmodule));
vimmodule.m_name = "vim";
vimmodule.m_doc = "Vim Python interface\n";
vimmodule.m_size = -1;
vimmodule.m_methods = VimMethods;
#endif
}
|