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
|
/* This file is part of the KDE libraries
Copyright (C) 2001-2004 Christoph Cullmann <[email protected]>
Copyright (C) 2001 Joseph Wenninger <[email protected]>
Copyright (C) 1999 Jochen Wilhelmy <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02111-13020, USA.
*/
//BEGIN includes
#include "katedocument.h"
#include "katedocument.moc"
#include "katekeyinterceptorfunctor.h"
#include "katefactory.h"
#include "katedialogs.h"
#include "katehighlight.h"
#include "kateview.h"
#include "katesearch.h"
#include "kateautoindent.h"
#include "katetextline.h"
#include "katedocumenthelpers.h"
#include "kateprinter.h"
#include "katelinerange.h"
#include "katesupercursor.h"
#include "katearbitraryhighlight.h"
#include "katerenderer.h"
#include "kateattribute.h"
#include "kateconfig.h"
#include "katefiletype.h"
#include "kateschema.h"
#include "katetemplatehandler.h"
#include <tdetexteditor/plugin.h>
#include <tdeio/job.h>
#include <tdeio/netaccess.h>
#include <tdeio/tdefileitem.h>
#include <tdeparts/event.h>
#include <tdelocale.h>
#include <tdeglobal.h>
#include <tdeapplication.h>
#include <tdepopupmenu.h>
#include <tdeconfig.h>
#include <tdefiledialog.h>
#include <tdemessagebox.h>
#include <kstdaction.h>
#include <kiconloader.h>
#include <kxmlguifactory.h>
#include <kdialogbase.h>
#include <kdebug.h>
#include <tdeglobalsettings.h>
#include <klibloader.h>
#include <kdirwatch.h>
#include <twin.h>
#include <kencodingfiledialog.h>
#include <tdetempfile.h>
#include <kmdcodec.h>
#include <kstandarddirs.h>
#include <tqtimer.h>
#include <tqfile.h>
#include <tqclipboard.h>
#include <tqtextstream.h>
#include <tqtextcodec.h>
#include <tqmap.h>
//END includes
//BEGIN PRIVATE CLASSES
class KatePartPluginItem
{
public:
KTextEditor::Plugin *plugin;
};
//END PRIVATE CLASSES
//BEGIN d'tor, c'tor
//
// KateDocument Constructor
//
KateDocument::KateDocument ( bool bSingleViewMode, bool bBrowserView,
bool bReadOnly, TQWidget *parentWidget,
const char *widgetName, TQObject *parent, const char *name)
: Kate::Document(parent, name),
m_plugins (KateFactory::self()->plugins().count()),
m_undoDontMerge(false),
m_undoIgnoreCancel(false),
lastUndoGroupWhenSaved( 0 ),
lastRedoGroupWhenSaved( 0 ),
docWasSavedWhenUndoWasEmpty( true ),
docWasSavedWhenRedoWasEmpty( true ),
m_modOnHd (false),
m_modOnHdReason (0),
m_job (0),
m_tempFile (0),
m_tabInterceptor(0)
{
m_undoComplexMerge=false;
m_isInUndo = false;
// my dcop object
setObjId ("KateDocument#"+documentDCOPSuffix());
// tdetexteditor interfaces
setBlockSelectionInterfaceDCOPSuffix (documentDCOPSuffix());
setConfigInterfaceDCOPSuffix (documentDCOPSuffix());
setConfigInterfaceExtensionDCOPSuffix (documentDCOPSuffix());
setCursorInterfaceDCOPSuffix (documentDCOPSuffix());
setEditInterfaceDCOPSuffix (documentDCOPSuffix());
setEncodingInterfaceDCOPSuffix (documentDCOPSuffix());
setHighlightingInterfaceDCOPSuffix (documentDCOPSuffix());
setMarkInterfaceDCOPSuffix (documentDCOPSuffix());
setMarkInterfaceExtensionDCOPSuffix (documentDCOPSuffix());
setPrintInterfaceDCOPSuffix (documentDCOPSuffix());
setSearchInterfaceDCOPSuffix (documentDCOPSuffix());
setSelectionInterfaceDCOPSuffix (documentDCOPSuffix());
setSelectionInterfaceExtDCOPSuffix (documentDCOPSuffix());
setSessionConfigInterfaceDCOPSuffix (documentDCOPSuffix());
setUndoInterfaceDCOPSuffix (documentDCOPSuffix());
setWordWrapInterfaceDCOPSuffix (documentDCOPSuffix());
// init local plugin array
m_plugins.fill (0);
// register doc at factory
KateFactory::self()->registerDocument (this);
m_reloading = false;
m_loading = false;
m_encodingSticky = false;
m_buffer = new KateBuffer (this);
// init the config object, be careful not to use it
// until the initial readConfig() call is done
m_config = new KateDocumentConfig (this);
// init some more vars !
m_activeView = 0L;
hlSetByUser = false;
m_fileType = -1;
m_fileTypeSetByUser = false;
setInstance( KateFactory::self()->instance() );
editSessionNumber = 0;
editIsRunning = false;
m_editCurrentUndo = 0L;
editWithUndo = false;
m_docNameNumber = 0;
m_bSingleViewMode = bSingleViewMode;
m_bBrowserView = bBrowserView;
m_bReadOnly = bReadOnly;
m_marks.setAutoDelete( true );
m_markPixmaps.setAutoDelete( true );
m_markDescriptions.setAutoDelete( true );
setMarksUserChangable( markType01 );
m_undoMergeTimer = new TQTimer(this);
connect(m_undoMergeTimer, TQT_SIGNAL(timeout()), TQT_SLOT(undoCancel()));
clearMarks ();
clearUndo ();
clearRedo ();
setModified (false);
docWasSavedWhenUndoWasEmpty = true;
// normal hl
m_buffer->setHighlight (0);
m_extension = new KateBrowserExtension( this );
m_arbitraryHL = new KateArbitraryHighlight();
m_indenter = KateAutoIndent::createIndenter ( this, 0 );
m_indenter->updateConfig ();
// some nice signals from the buffer
connect(m_buffer, TQT_SIGNAL(tagLines(int,int)), this, TQT_SLOT(tagLines(int,int)));
connect(m_buffer, TQT_SIGNAL(codeFoldingUpdated()),this,TQT_SIGNAL(codeFoldingUpdated()));
// if the user changes the highlight with the dialog, notify the doc
connect(KateHlManager::self(),TQT_SIGNAL(changed()),TQT_SLOT(internalHlChanged()));
// signal for the arbitrary HL
connect(m_arbitraryHL, TQT_SIGNAL(tagLines(KateView*, KateSuperRange*)), TQT_SLOT(tagArbitraryLines(KateView*, KateSuperRange*)));
// signals for mod on hd
connect( KateFactory::self()->dirWatch(), TQT_SIGNAL(dirty (const TQString &)),
this, TQT_SLOT(slotModOnHdDirty (const TQString &)) );
connect( KateFactory::self()->dirWatch(), TQT_SIGNAL(created (const TQString &)),
this, TQT_SLOT(slotModOnHdCreated (const TQString &)) );
connect( KateFactory::self()->dirWatch(), TQT_SIGNAL(deleted (const TQString &)),
this, TQT_SLOT(slotModOnHdDeleted (const TQString &)) );
// update doc name
setDocName ("");
// if single view mode, like in the konqui embedding, create a default view ;)
if ( m_bSingleViewMode )
{
KTextEditor::View *view = createView( parentWidget, widgetName );
insertChildClient( view );
view->show();
setWidget( view );
}
connect(this,TQT_SIGNAL(sigQueryClose(bool *, bool*)),this,TQT_SLOT(slotQueryClose_save(bool *, bool*)));
m_isasking = 0;
// plugins
for (uint i=0; i<KateFactory::self()->plugins().count(); i++)
{
if (config()->plugin (i))
loadPlugin (i);
}
}
//
// KateDocument Destructor
//
KateDocument::~KateDocument()
{
// remove file from dirwatch
deactivateDirWatch ();
if (!singleViewMode())
{
// clean up remaining views
m_views.setAutoDelete( true );
m_views.clear();
}
delete m_editCurrentUndo;
delete m_arbitraryHL;
// cleanup the undo items, very important, truee :/
undoItems.setAutoDelete(true);
undoItems.clear();
// clean up plugins
unloadAllPlugins ();
delete m_config;
delete m_indenter;
KateFactory::self()->deregisterDocument (this);
}
//END
//BEGIN Plugins
void KateDocument::unloadAllPlugins ()
{
for (uint i=0; i<m_plugins.count(); i++)
unloadPlugin (i);
}
void KateDocument::enableAllPluginsGUI (KateView *view)
{
for (uint i=0; i<m_plugins.count(); i++)
enablePluginGUI (m_plugins[i], view);
}
void KateDocument::disableAllPluginsGUI (KateView *view)
{
for (uint i=0; i<m_plugins.count(); i++)
disablePluginGUI (m_plugins[i], view);
}
void KateDocument::loadPlugin (uint pluginIndex)
{
if (m_plugins[pluginIndex]) return;
m_plugins[pluginIndex] = KTextEditor::createPlugin (TQFile::encodeName((KateFactory::self()->plugins())[pluginIndex]->library()), this);
enablePluginGUI (m_plugins[pluginIndex]);
}
void KateDocument::unloadPlugin (uint pluginIndex)
{
if (!m_plugins[pluginIndex]) return;
disablePluginGUI (m_plugins[pluginIndex]);
delete m_plugins[pluginIndex];
m_plugins[pluginIndex] = 0L;
}
void KateDocument::enablePluginGUI (KTextEditor::Plugin *plugin, KateView *view)
{
if (!plugin) return;
if (!KTextEditor::pluginViewInterface(plugin)) return;
KXMLGUIFactory *factory = view->factory();
if ( factory )
factory->removeClient( view );
KTextEditor::pluginViewInterface(plugin)->addView(view);
if ( factory )
factory->addClient( view );
}
void KateDocument::enablePluginGUI (KTextEditor::Plugin *plugin)
{
if (!plugin) return;
if (!KTextEditor::pluginViewInterface(plugin)) return;
for (uint i=0; i< m_views.count(); i++)
enablePluginGUI (plugin, m_views.at(i));
}
void KateDocument::disablePluginGUI (KTextEditor::Plugin *plugin, KateView *view)
{
if (!plugin) return;
if (!KTextEditor::pluginViewInterface(plugin)) return;
KXMLGUIFactory *factory = view->factory();
if ( factory )
factory->removeClient( view );
KTextEditor::pluginViewInterface( plugin )->removeView( view );
if ( factory )
factory->addClient( view );
}
void KateDocument::disablePluginGUI (KTextEditor::Plugin *plugin)
{
if (!plugin) return;
if (!KTextEditor::pluginViewInterface(plugin)) return;
for (uint i=0; i< m_views.count(); i++)
disablePluginGUI (plugin, m_views.at(i));
}
//END
//BEGIN KTextEditor::Document stuff
KTextEditor::View *KateDocument::createView( TQWidget *parent, const char *name )
{
KateView* newView = new KateView( this, parent, name);
connect(newView, TQT_SIGNAL(cursorPositionChanged()), TQT_SLOT(undoCancel()));
if ( s_fileChangedDialogsActivated )
connect( newView, TQT_SIGNAL(gotFocus( Kate::View * )), this, TQT_SLOT(slotModifiedOnDisk()) );
return newView;
}
TQPtrList<KTextEditor::View> KateDocument::views () const
{
return m_textEditViews;
}
void KateDocument::setActiveView( KateView *view )
{
if ( m_activeView == view ) return;
m_activeView = view;
}
//END
//BEGIN KTextEditor::ConfigInterfaceExtension stuff
uint KateDocument::configPages () const
{
return 10;
}
KTextEditor::ConfigPage *KateDocument::configPage (uint number, TQWidget *parent, const char * )
{
switch( number )
{
case 0:
return new KateViewDefaultsConfig (parent);
case 1:
return new KateSchemaConfigPage (parent, this);
case 2:
return new KateSelectConfigTab (parent);
case 3:
return new KateEditConfigTab (parent);
case 4:
return new KateIndentConfigTab (parent);
case 5:
return new KateSaveConfigTab (parent);
case 6:
return new KateHlConfigPage (parent, this);
case 7:
return new KateFileTypeConfigTab (parent);
case 8:
return new KateEditKeyConfiguration (parent, this);
case 9:
return new KatePartPluginConfigPage (parent);
default:
return 0;
}
return 0;
}
TQString KateDocument::configPageName (uint number) const
{
switch( number )
{
case 0:
return i18n ("Appearance");
case 1:
return i18n ("Fonts & Colors");
case 2:
return i18n ("Cursor & Selection");
case 3:
return i18n ("Editing");
case 4:
return i18n ("Indentation");
case 5:
return i18n("Open/Save");
case 6:
return i18n ("Highlighting");
case 7:
return i18n("Filetypes");
case 8:
return i18n ("Shortcuts");
case 9:
return i18n ("Plugins");
default:
return TQString ("");
}
return TQString ("");
}
TQString KateDocument::configPageFullName (uint number) const
{
switch( number )
{
case 0:
return i18n("Appearance");
case 1:
return i18n ("Font & Color Schemas");
case 2:
return i18n ("Cursor & Selection Behavior");
case 3:
return i18n ("Editing Options");
case 4:
return i18n ("Indentation Rules");
case 5:
return i18n("File Opening & Saving");
case 6:
return i18n ("Highlighting Rules");
case 7:
return i18n("Filetype Specific Settings");
case 8:
return i18n ("Shortcuts Configuration");
case 9:
return i18n ("Plugin Manager");
default:
return TQString ("");
}
return TQString ("");
}
TQPixmap KateDocument::configPagePixmap (uint number, int size) const
{
switch( number )
{
case 0:
return BarIcon("view_text",size);
case 1:
return BarIcon("colorize", size);
case 2:
return BarIcon("frame_edit", size);
case 3:
return BarIcon("edit", size);
case 4:
return BarIcon("rightjust", size);
case 5:
return BarIcon("filesave", size);
case 6:
return BarIcon("source", size);
case 7:
return BarIcon("edit", size);
case 8:
return BarIcon("key_enter", size);
case 9:
return BarIcon("connect_established", size);
default:
return BarIcon("edit", size);
}
return BarIcon("edit", size);
}
//END
//BEGIN KTextEditor::EditInterface stuff
TQString KateDocument::text() const
{
TQString s;
for (uint i = 0; i < m_buffer->count(); i++)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(i);
if (textLine)
{
s.append (textLine->string());
if ((i+1) < m_buffer->count())
s.append('\n');
}
}
return s;
}
TQString KateDocument::text ( uint startLine, uint startCol, uint endLine, uint endCol ) const
{
return text(startLine, startCol, endLine, endCol, false);
}
TQString KateDocument::text ( uint startLine, uint startCol, uint endLine, uint endCol, bool blockwise) const
{
if ( blockwise && (startCol > endCol) )
return TQString ();
TQString s;
if (startLine == endLine)
{
if (startCol > endCol)
return TQString ();
KateTextLine::Ptr textLine = m_buffer->plainLine(startLine);
if ( !textLine )
return TQString ();
return textLine->string(startCol, endCol-startCol);
}
else
{
for (uint i = startLine; (i <= endLine) && (i < m_buffer->count()); i++)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(i);
if ( !blockwise )
{
if (i == startLine)
s.append (textLine->string(startCol, textLine->length()-startCol));
else if (i == endLine)
s.append (textLine->string(0, endCol));
else
s.append (textLine->string());
}
else
{
s.append( textLine->string( startCol, endCol-startCol));
}
if ( i < endLine )
s.append('\n');
}
}
return s;
}
TQString KateDocument::textLine( uint line ) const
{
KateTextLine::Ptr l = m_buffer->plainLine(line);
if (!l)
return TQString();
return l->string();
}
bool KateDocument::setText(const TQString &s)
{
if (!isReadWrite())
return false;
TQPtrList<KTextEditor::Mark> m = marks ();
TQValueList<KTextEditor::Mark> msave;
for (uint i=0; i < m.count(); i++)
msave.append (*m.at(i));
editStart ();
// delete the text
clear();
// insert the new text
insertText (0, 0, s);
editEnd ();
for (uint i=0; i < msave.count(); i++)
setMark (msave[i].line, msave[i].type);
return true;
}
bool KateDocument::clear()
{
if (!isReadWrite())
return false;
for (KateView * view = m_views.first(); view != 0L; view = m_views.next() ) {
view->clear();
view->tagAll();
view->update();
}
clearMarks ();
return removeText (0,0,lastLine()+1, 0);
}
bool KateDocument::insertText( uint line, uint col, const TQString &s)
{
return insertText (line, col, s, false);
}
bool KateDocument::insertText( uint line, uint col, const TQString &s, bool blockwise )
{
if (!isReadWrite())
return false;
if (s.isEmpty())
return true;
if (line == numLines())
editInsertLine(line,"");
else if (line > lastLine())
return false;
editStart ();
uint insertPos = col;
uint len = s.length();
TQString buf;
bool replacetabs = ( config()->configFlags() & KateDocumentConfig::cfReplaceTabsDyn && ! m_isInUndo );
uint tw = config()->tabWidth();
uint insertPosExpanded = insertPos;
KateTextLine::Ptr l = m_buffer->line( line );
if (l != 0)
insertPosExpanded = l->cursorX( insertPos, tw );
for (uint pos = 0; pos < len; pos++)
{
TQChar ch = s[pos];
if (ch == '\n')
{
editInsertText (line, insertPos, buf);
if ( !blockwise )
{
editWrapLine (line, insertPos + buf.length());
insertPos = insertPosExpanded = 0;
}
else
{
if ( line == lastLine() )
editWrapLine (line, insertPos + buf.length());
}
line++;
buf.truncate(0);
l = m_buffer->line( line );
if (l)
insertPosExpanded = l->cursorX( insertPos, tw );
}
else
{
if ( replacetabs && ch == '\t' )
{
uint tr = tw - ( insertPosExpanded+buf.length() )%tw;
for ( uint i=0; i < tr; i++ )
buf += ' ';
}
else
buf += ch; // append char to buffer
}
}
editInsertText (line, insertPos, buf);
editEnd ();
emit textInserted(line,insertPos);
return true;
}
bool KateDocument::removeText ( uint startLine, uint startCol, uint endLine, uint endCol )
{
return removeText (startLine, startCol, endLine, endCol, false);
}
bool KateDocument::removeText ( uint startLine, uint startCol, uint endLine, uint endCol, bool blockwise)
{
if (!isReadWrite())
return false;
if ( blockwise && (startCol > endCol) )
return false;
if ( startLine > endLine )
return false;
if ( startLine > lastLine() )
return false;
if (!blockwise) {
emit aboutToRemoveText(KateTextRange(startLine,startCol,endLine,endCol));
}
editStart ();
if ( !blockwise )
{
if ( endLine > lastLine() )
{
endLine = lastLine()+1;
endCol = 0;
}
if (startLine == endLine)
{
editRemoveText (startLine, startCol, endCol-startCol);
}
else if ((startLine+1) == endLine)
{
if ( (m_buffer->plainLine(startLine)->length()-startCol) > 0 )
editRemoveText (startLine, startCol, m_buffer->plainLine(startLine)->length()-startCol);
editRemoveText (startLine+1, 0, endCol);
editUnWrapLine (startLine);
}
else
{
for (uint line = endLine; line >= startLine; line--)
{
if ((line > startLine) && (line < endLine))
{
editRemoveLine (line);
}
else
{
if (line == endLine)
{
if ( endLine <= lastLine() )
editRemoveText (line, 0, endCol);
}
else
{
if ( (m_buffer->plainLine(line)->length()-startCol) > 0 )
editRemoveText (line, startCol, m_buffer->plainLine(line)->length()-startCol);
editUnWrapLine (startLine);
}
}
if ( line == 0 )
break;
}
}
} // if ( ! blockwise )
else
{
if ( endLine > lastLine() )
endLine = lastLine ();
for (uint line = endLine; line >= startLine; line--)
{
editRemoveText (line, startCol, endCol-startCol);
if ( line == 0 )
break;
}
}
editEnd ();
emit textRemoved();
return true;
}
bool KateDocument::insertLine( uint l, const TQString &str )
{
if (!isReadWrite())
return false;
if (l > numLines())
return false;
return editInsertLine (l, str);
}
bool KateDocument::removeLine( uint line )
{
if (!isReadWrite())
return false;
if (line > lastLine())
return false;
return editRemoveLine (line);
}
uint KateDocument::length() const
{
uint l = 0;
for (uint i = 0; i < m_buffer->count(); i++)
{
KateTextLine::Ptr line = m_buffer->plainLine(i);
if (line)
l += line->length();
}
return l;
}
uint KateDocument::numLines() const
{
return m_buffer->count();
}
uint KateDocument::numVisLines() const
{
return m_buffer->countVisible ();
}
int KateDocument::lineLength ( uint line ) const
{
KateTextLine::Ptr l = m_buffer->plainLine(line);
if (!l)
return -1;
return l->length();
}
//END
//BEGIN KTextEditor::EditInterface internal stuff
//
// Starts an edit session with (or without) undo, update of view disabled during session
//
void KateDocument::editStart (bool withUndo)
{
editSessionNumber++;
if (editSessionNumber > 1)
return;
editIsRunning = true;
editWithUndo = withUndo;
if (editWithUndo)
undoStart();
else
undoCancel();
for (uint z = 0; z < m_views.count(); z++)
{
m_views.at(z)->editStart ();
}
m_buffer->editStart ();
}
void KateDocument::undoStart()
{
if (m_editCurrentUndo || (m_activeView && m_activeView->imComposeEvent())) return;
// Make sure the buffer doesn't get bigger than requested
if ((config()->undoSteps() > 0) && (undoItems.count() > config()->undoSteps()))
{
undoItems.setAutoDelete(true);
undoItems.removeFirst();
undoItems.setAutoDelete(false);
docWasSavedWhenUndoWasEmpty = false;
}
// new current undo item
m_editCurrentUndo = new KateUndoGroup(this);
}
void KateDocument::undoEnd()
{
if (m_activeView && m_activeView->imComposeEvent())
return;
if (m_editCurrentUndo)
{
bool changedUndo = false;
if (m_editCurrentUndo->isEmpty())
delete m_editCurrentUndo;
else if (!m_undoDontMerge && undoItems.last() && undoItems.last()->merge(m_editCurrentUndo,m_undoComplexMerge))
delete m_editCurrentUndo;
else
{
undoItems.append(m_editCurrentUndo);
changedUndo = true;
}
m_undoDontMerge = false;
m_undoIgnoreCancel = true;
m_editCurrentUndo = 0L;
// (Re)Start the single-shot timer to cancel the undo merge
// the user has 5 seconds to input more data, or undo merging gets canceled for the current undo item.
m_undoMergeTimer->start(5000, true);
if (changedUndo)
emit undoChanged();
}
}
void KateDocument::undoCancel()
{
if (m_undoIgnoreCancel) {
m_undoIgnoreCancel = false;
return;
}
m_undoDontMerge = true;
Q_ASSERT(!m_editCurrentUndo);
// As you can see by the above assert, neither of these should really be required
delete m_editCurrentUndo;
m_editCurrentUndo = 0L;
}
void KateDocument::undoSafePoint() {
Q_ASSERT(m_editCurrentUndo);
if (!m_editCurrentUndo) return;
m_editCurrentUndo->safePoint();
}
//
// End edit session and update Views
//
void KateDocument::editEnd ()
{
if (editSessionNumber == 0)
return;
// wrap the new/changed text, if something really changed!
if (m_buffer->editChanged() && (editSessionNumber == 1))
if (editWithUndo && config()->wordWrap())
wrapText (m_buffer->editTagStart(), m_buffer->editTagEnd());
editSessionNumber--;
if (editSessionNumber > 0)
return;
// end buffer edit, will trigger hl update
// this will cause some possible adjustment of tagline start/end
m_buffer->editEnd ();
if (editWithUndo)
undoEnd();
// edit end for all views !!!!!!!!!
for (uint z = 0; z < m_views.count(); z++)
m_views.at(z)->editEnd (m_buffer->editTagStart(), m_buffer->editTagEnd(), m_buffer->editTagFrom());
if (m_buffer->editChanged())
{
setModified(true);
emit textChanged ();
}
editIsRunning = false;
}
bool KateDocument::wrapText (uint startLine, uint endLine)
{
uint col = config()->wordWrapAt();
if (col == 0)
return false;
editStart ();
for (uint line = startLine; (line <= endLine) && (line < numLines()); line++)
{
KateTextLine::Ptr l = m_buffer->line(line);
if (!l)
return false;
kdDebug (13020) << "try wrap line: " << line << endl;
if (l->lengthWithTabs(m_buffer->tabWidth()) > col)
{
KateTextLine::Ptr nextl = m_buffer->line(line+1);
kdDebug (13020) << "do wrap line: " << line << endl;
const TQChar *text = l->text();
uint eolPosition = l->length()-1;
// take tabs into account here, too
uint x = 0;
const TQString & t = l->string();
uint z2 = 0;
for ( ; z2 < l->length(); z2++)
{
if (t[z2] == TQChar('\t'))
x += m_buffer->tabWidth() - (x % m_buffer->tabWidth());
else
x++;
if (x > col)
break;
}
uint searchStart = kMin (z2, l->length()-1);
// If where we are wrapping is an end of line and is a space we don't
// want to wrap there
if (searchStart == eolPosition && text[searchStart].isSpace())
searchStart--;
// Scan backwards looking for a place to break the line
// We are not interested in breaking at the first char
// of the line (if it is a space), but we are at the second
// anders: if we can't find a space, try breaking on a word
// boundry, using KateHighlight::canBreakAt().
// This could be a priority (setting) in the hl/filetype/document
int z = 0;
uint nw = 0; // alternative position, a non word character
for (z=searchStart; z > 0; z--)
{
if (text[z].isSpace()) break;
if ( ! nw && highlight()->canBreakAt( text[z] , l->attribute(z) ) )
nw = z;
}
if (z > 0)
{
// cu space
editRemoveText (line, z, 1);
}
else
{
// There was no space to break at so break at a nonword character if
// found, or at the wrapcolumn ( that needs be configurable )
// Don't try and add any white space for the break
if ( nw && nw < col ) nw++; // break on the right side of the character
z = nw ? nw : col;
}
if (nextl && !nextl->isAutoWrapped())
{
editWrapLine (line, z, true);
editMarkLineAutoWrapped (line+1, true);
endLine++;
}
else
{
if (nextl && (nextl->length() > 0) && !nextl->getChar(0).isSpace() && ((l->length() < 1) || !l->getChar(l->length()-1).isSpace()))
editInsertText (line+1, 0, TQString (" "));
bool newLineAdded = false;
editWrapLine (line, z, false, &newLineAdded);
editMarkLineAutoWrapped (line+1, true);
endLine++;
}
}
}
editEnd ();
return true;
}
void KateDocument::editAddUndo (KateUndoGroup::UndoType type, uint line, uint col, uint len, const TQString &text)
{
if (editIsRunning && editWithUndo && m_editCurrentUndo) {
m_editCurrentUndo->addItem(type, line, col, len, text);
// Clear redo buffer
if (redoItems.count()) {
redoItems.setAutoDelete(true);
redoItems.clear();
redoItems.setAutoDelete(false);
}
}
}
bool KateDocument::editInsertText ( uint line, uint col, const TQString &str )
{
if (!isReadWrite())
return false;
TQString s = str;
KateTextLine::Ptr l = m_buffer->line(line);
if (!l)
return false;
if ( config()->configFlags() & KateDocumentConfig::cfReplaceTabsDyn && ! m_isInUndo )
{
uint tw = config()->tabWidth();
int pos = 0;
uint l = 0;
while ( (pos = s.find('\t')) > -1 )
{
l = tw - ( (col + pos)%tw );
s.replace( pos, 1, TQString().fill( ' ', l ) );
}
}
editStart ();
editAddUndo (KateUndoGroup::editInsertText, line, col, s.length(), s);
l->insertText (col, s.length(), s.unicode());
// removeTrailingSpace(line); // ### nessecary?
m_buffer->changeLine(line);
for( TQPtrListIterator<KateSuperCursor> it (m_superCursors); it.current(); ++it )
it.current()->editTextInserted (line, col, s.length());
editEnd ();
return true;
}
bool KateDocument::editRemoveText ( uint line, uint col, uint len )
{
if (!isReadWrite())
return false;
KateTextLine::Ptr l = m_buffer->line(line);
if (!l)
return false;
editStart ();
editAddUndo (KateUndoGroup::editRemoveText, line, col, len, l->string().mid(col, len));
l->removeText (col, len);
removeTrailingSpace( line );
m_buffer->changeLine(line);
for( TQPtrListIterator<KateSuperCursor> it (m_superCursors); it.current(); ++it )
it.current()->editTextRemoved (line, col, len);
editEnd ();
return true;
}
bool KateDocument::editMarkLineAutoWrapped ( uint line, bool autowrapped )
{
if (!isReadWrite())
return false;
KateTextLine::Ptr l = m_buffer->line(line);
if (!l)
return false;
editStart ();
editAddUndo (KateUndoGroup::editMarkLineAutoWrapped, line, autowrapped ? 1 : 0, 0, TQString::null);
l->setAutoWrapped (autowrapped);
m_buffer->changeLine(line);
editEnd ();
return true;
}
bool KateDocument::editWrapLine ( uint line, uint col, bool newLine, bool *newLineAdded)
{
if (!isReadWrite())
return false;
KateTextLine::Ptr l = m_buffer->line(line);
if (!l)
return false;
editStart ();
KateTextLine::Ptr nextLine = m_buffer->line(line+1);
int pos = l->length() - col;
if (pos < 0)
pos = 0;
editAddUndo (KateUndoGroup::editWrapLine, line, col, pos, (!nextLine || newLine) ? "1" : "0");
if (!nextLine || newLine)
{
KateTextLine::Ptr textLine = new KateTextLine();
textLine->insertText (0, pos, l->text()+col, l->attributes()+col);
l->truncate(col);
m_buffer->insertLine (line+1, textLine);
m_buffer->changeLine(line);
TQPtrList<KTextEditor::Mark> list;
for( TQIntDictIterator<KTextEditor::Mark> it( m_marks ); it.current(); ++it )
{
if( it.current()->line >= line )
{
if ((col == 0) || (it.current()->line > line))
list.append( it.current() );
}
}
for( TQPtrListIterator<KTextEditor::Mark> it( list ); it.current(); ++it )
{
KTextEditor::Mark* mark = m_marks.take( it.current()->line );
mark->line++;
m_marks.insert( mark->line, mark );
}
if( !list.isEmpty() )
emit marksChanged();
// yes, we added a new line !
if (newLineAdded)
(*newLineAdded) = true;
}
else
{
nextLine->insertText (0, pos, l->text()+col, l->attributes()+col);
l->truncate(col);
m_buffer->changeLine(line);
m_buffer->changeLine(line+1);
// no, no new line added !
if (newLineAdded)
(*newLineAdded) = false;
}
for( TQPtrListIterator<KateSuperCursor> it (m_superCursors); it.current(); ++it )
it.current()->editLineWrapped (line, col, !nextLine || newLine);
editEnd ();
return true;
}
bool KateDocument::editUnWrapLine ( uint line, bool removeLine, uint length )
{
if (!isReadWrite())
return false;
KateTextLine::Ptr l = m_buffer->line(line);
KateTextLine::Ptr nextLine = m_buffer->line(line+1);
if (!l || !nextLine)
return false;
editStart ();
uint col = l->length ();
editAddUndo (KateUndoGroup::editUnWrapLine, line, col, length, removeLine ? "1" : "0");
if (removeLine)
{
l->insertText (col, nextLine->length(), nextLine->text(), nextLine->attributes());
m_buffer->changeLine(line);
m_buffer->removeLine(line+1);
}
else
{
l->insertText (col, (nextLine->length() < length) ? nextLine->length() : length,
nextLine->text(), nextLine->attributes());
nextLine->removeText (0, (nextLine->length() < length) ? nextLine->length() : length);
m_buffer->changeLine(line);
m_buffer->changeLine(line+1);
}
TQPtrList<KTextEditor::Mark> list;
for( TQIntDictIterator<KTextEditor::Mark> it( m_marks ); it.current(); ++it )
{
if( it.current()->line >= line+1 )
list.append( it.current() );
if ( it.current()->line == line+1 )
{
KTextEditor::Mark* mark = m_marks.take( line );
if (mark)
{
it.current()->type |= mark->type;
}
}
}
for( TQPtrListIterator<KTextEditor::Mark> it( list ); it.current(); ++it )
{
KTextEditor::Mark* mark = m_marks.take( it.current()->line );
mark->line--;
m_marks.insert( mark->line, mark );
}
if( !list.isEmpty() )
emit marksChanged();
for( TQPtrListIterator<KateSuperCursor> it (m_superCursors); it.current(); ++it )
it.current()->editLineUnWrapped (line, col, removeLine, length);
editEnd ();
return true;
}
bool KateDocument::editInsertLine ( uint line, const TQString &s )
{
if (!isReadWrite())
return false;
if ( line > numLines() )
return false;
editStart ();
editAddUndo (KateUndoGroup::editInsertLine, line, 0, s.length(), s);
removeTrailingSpace( line ); // old line
KateTextLine::Ptr tl = new KateTextLine();
tl->insertText (0, s.length(), s.unicode(), 0);
m_buffer->insertLine(line, tl);
m_buffer->changeLine(line);
removeTrailingSpace( line ); // new line
TQPtrList<KTextEditor::Mark> list;
for( TQIntDictIterator<KTextEditor::Mark> it( m_marks ); it.current(); ++it )
{
if( it.current()->line >= line )
list.append( it.current() );
}
for( TQPtrListIterator<KTextEditor::Mark> it( list ); it.current(); ++it )
{
KTextEditor::Mark* mark = m_marks.take( it.current()->line );
mark->line++;
m_marks.insert( mark->line, mark );
}
if( !list.isEmpty() )
emit marksChanged();
for( TQPtrListIterator<KateSuperCursor> it (m_superCursors); it.current(); ++it )
it.current()->editLineInserted (line);
editEnd ();
return true;
}
bool KateDocument::editRemoveLine ( uint line )
{
if (!isReadWrite())
return false;
if ( line > lastLine() )
return false;
if ( numLines() == 1 )
return editRemoveText (0, 0, m_buffer->line(0)->length());
editStart ();
editAddUndo (KateUndoGroup::editRemoveLine, line, 0, lineLength(line), textLine(line));
m_buffer->removeLine(line);
TQPtrList<KTextEditor::Mark> list;
KTextEditor::Mark* rmark = 0;
for( TQIntDictIterator<KTextEditor::Mark> it( m_marks ); it.current(); ++it )
{
if ( (it.current()->line > line) )
list.append( it.current() );
else if ( (it.current()->line == line) )
rmark = it.current();
}
if (rmark)
delete (m_marks.take (rmark->line));
for( TQPtrListIterator<KTextEditor::Mark> it( list ); it.current(); ++it )
{
KTextEditor::Mark* mark = m_marks.take( it.current()->line );
mark->line--;
m_marks.insert( mark->line, mark );
}
if( !list.isEmpty() )
emit marksChanged();
for( TQPtrListIterator<KateSuperCursor> it (m_superCursors); it.current(); ++it )
it.current()->editLineRemoved (line);
editEnd();
return true;
}
//END
//BEGIN KTextEditor::UndoInterface stuff
uint KateDocument::undoCount () const
{
return undoItems.count ();
}
uint KateDocument::redoCount () const
{
return redoItems.count ();
}
uint KateDocument::undoSteps () const
{
return m_config->undoSteps();
}
void KateDocument::setUndoSteps(uint steps)
{
m_config->setUndoSteps (steps);
}
void KateDocument::undo()
{
m_isInUndo = true;
if ((undoItems.count() > 0) && undoItems.last())
{
clearSelection ();
undoItems.last()->undo();
redoItems.append (undoItems.last());
undoItems.removeLast ();
updateModified();
emit undoChanged ();
}
m_isInUndo = false;
}
void KateDocument::redo()
{
m_isInUndo = true;
if ((redoItems.count() > 0) && redoItems.last())
{
clearSelection ();
redoItems.last()->redo();
undoItems.append (redoItems.last());
redoItems.removeLast ();
updateModified();
emit undoChanged ();
}
m_isInUndo = false;
}
void KateDocument::updateModified()
{
/*
How this works:
After noticing that there where to many scenarios to take into
consideration when using 'if's to toggle the "Modified" flag
I came up with this baby, flexible and repetitive calls are
minimal.
A numeric unique pattern is generated by toggleing a set of bits,
each bit symbolizes a different state in the Undo Redo structure.
undoItems.isEmpty() != null BIT 1
redoItems.isEmpty() != null BIT 2
docWasSavedWhenUndoWasEmpty == true BIT 3
docWasSavedWhenRedoWasEmpty == true BIT 4
lastUndoGroupWhenSavedIsLastUndo BIT 5
lastUndoGroupWhenSavedIsLastRedo BIT 6
lastRedoGroupWhenSavedIsLastUndo BIT 7
lastRedoGroupWhenSavedIsLastRedo BIT 8
If you find a new pattern, please add it to the patterns array
*/
unsigned char currentPattern = 0;
const unsigned char patterns[] = {5,16,24,26,88,90,93,133,144,149,165};
const unsigned char patternCount = sizeof(patterns);
KateUndoGroup* undoLast = 0;
KateUndoGroup* redoLast = 0;
if (undoItems.isEmpty())
{
currentPattern |= 1;
}
else
{
undoLast = undoItems.last();
}
if (redoItems.isEmpty())
{
currentPattern |= 2;
}
else
{
redoLast = redoItems.last();
}
if (docWasSavedWhenUndoWasEmpty) currentPattern |= 4;
if (docWasSavedWhenRedoWasEmpty) currentPattern |= 8;
if (lastUndoGroupWhenSaved == undoLast) currentPattern |= 16;
if (lastUndoGroupWhenSaved == redoLast) currentPattern |= 32;
if (lastRedoGroupWhenSaved == undoLast) currentPattern |= 64;
if (lastRedoGroupWhenSaved == redoLast) currentPattern |= 128;
// This will print out the pattern information
kdDebug(13020) << k_funcinfo
<< "Pattern:" << static_cast<unsigned int>(currentPattern) << endl;
for (uint patternIndex = 0; patternIndex < patternCount; ++patternIndex)
{
if ( currentPattern == patterns[patternIndex] )
{
setModified( false );
kdDebug(13020) << k_funcinfo << "setting modified to false!" << endl;
break;
}
}
}
void KateDocument::clearUndo()
{
undoItems.setAutoDelete (true);
undoItems.clear ();
undoItems.setAutoDelete (false);
lastUndoGroupWhenSaved = 0;
docWasSavedWhenUndoWasEmpty = false;
emit undoChanged ();
}
void KateDocument::clearRedo()
{
redoItems.setAutoDelete (true);
redoItems.clear ();
redoItems.setAutoDelete (false);
lastRedoGroupWhenSaved = 0;
docWasSavedWhenRedoWasEmpty = false;
emit undoChanged ();
}
TQPtrList<KTextEditor::Cursor> KateDocument::cursors () const
{
return myCursors;
}
//END
//BEGIN KTextEditor::SearchInterface stuff
bool KateDocument::searchText (unsigned int startLine, unsigned int startCol, const TQString &text, unsigned int *foundAtLine, unsigned int *foundAtCol, unsigned int *matchLen, bool casesensitive, bool backwards)
{
if (text.isEmpty())
return false;
int line = startLine;
int col = startCol;
if (!backwards)
{
int searchEnd = lastLine();
while (line <= searchEnd)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(line);
if (!textLine)
return false;
uint foundAt, myMatchLen;
bool found = textLine->searchText (col, text, &foundAt, &myMatchLen, casesensitive, false);
if (found)
{
(*foundAtLine) = line;
(*foundAtCol) = foundAt;
(*matchLen) = myMatchLen;
return true;
}
col = 0;
line++;
}
}
else
{
// backward search
int searchEnd = 0;
while (line >= searchEnd)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(line);
if (!textLine)
return false;
uint foundAt, myMatchLen;
bool found = textLine->searchText (col, text, &foundAt, &myMatchLen, casesensitive, true);
if (found)
{
/* if ((uint) line == startLine && foundAt + myMatchLen >= (uint) col
&& line == selectStart.line() && foundAt == (uint) selectStart.col()
&& line == selectEnd.line() && foundAt + myMatchLen == (uint) selectEnd.col())
{
// To avoid getting stuck at one match we skip a match if it is already
// selected (most likely because it has just been found).
if (foundAt > 0)
col = foundAt - 1;
else {
if (--line >= 0)
col = lineLength(line);
}
continue;
}*/
(*foundAtLine) = line;
(*foundAtCol) = foundAt;
(*matchLen) = myMatchLen;
return true;
}
if (line >= 1)
col = lineLength(line-1);
line--;
}
}
return false;
}
bool KateDocument::searchText (unsigned int startLine, unsigned int startCol, const TQRegExp ®exp, unsigned int *foundAtLine, unsigned int *foundAtCol, unsigned int *matchLen, bool backwards)
{
kdDebug(13020)<<"KateDocument::searchText( "<<startLine<<", "<<startCol<<", "<<TQString(regexp.pattern())<<", "<<backwards<<" )"<<endl;
if (regexp.isEmpty() || !regexp.isValid())
return false;
int line = startLine;
int col = startCol;
if (!backwards)
{
int searchEnd = lastLine();
while (line <= searchEnd)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(line);
if (!textLine)
return false;
uint foundAt, myMatchLen;
bool found = textLine->searchText (col, regexp, &foundAt, &myMatchLen, false);
if (found)
{
// A special case which can only occur when searching with a regular expression consisting
// only of a lookahead (e.g. ^(?=\{) for a function beginning without selecting '{').
if (myMatchLen == 0 && (uint) line == startLine && foundAt == (uint) col)
{
if (col < lineLength(line))
col++;
else {
line++;
col = 0;
}
continue;
}
(*foundAtLine) = line;
(*foundAtCol) = foundAt;
(*matchLen) = myMatchLen;
return true;
}
col = 0;
line++;
}
}
else
{
// backward search
int searchEnd = 0;
while (line >= searchEnd)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(line);
if (!textLine)
return false;
uint foundAt, myMatchLen;
bool found = textLine->searchText (col, regexp, &foundAt, &myMatchLen, true);
if (found)
{
/*if ((uint) line == startLine && foundAt + myMatchLen >= (uint) col
&& line == selectStart.line() && foundAt == (uint) selectStart.col()
&& line == selectEnd.line() && foundAt + myMatchLen == (uint) selectEnd.col())
{
// To avoid getting stuck at one match we skip a match if it is already
// selected (most likely because it has just been found).
if (foundAt > 0)
col = foundAt - 1;
else {
if (--line >= 0)
col = lineLength(line);
}
continue;
}*/
(*foundAtLine) = line;
(*foundAtCol) = foundAt;
(*matchLen) = myMatchLen;
return true;
}
if (line >= 1)
col = lineLength(line-1);
line--;
}
}
return false;
}
//END
//BEGIN KTextEditor::HighlightingInterface stuff
uint KateDocument::hlMode ()
{
return KateHlManager::self()->findHl(highlight());
}
bool KateDocument::setHlMode (uint mode)
{
m_buffer->setHighlight (mode);
if (true)
{
setDontChangeHlOnSave();
return true;
}
return false;
}
void KateDocument::bufferHlChanged ()
{
// update all views
makeAttribs(false);
emit hlChanged();
}
uint KateDocument::hlModeCount ()
{
return KateHlManager::self()->highlights();
}
TQString KateDocument::hlModeName (uint mode)
{
return KateHlManager::self()->hlName (mode);
}
TQString KateDocument::hlModeSectionName (uint mode)
{
return KateHlManager::self()->hlSection (mode);
}
void KateDocument::setDontChangeHlOnSave()
{
hlSetByUser = true;
}
//END
//BEGIN KTextEditor::ConfigInterface stuff
void KateDocument::readConfig(TDEConfig *config)
{
config->setGroup("Kate Document Defaults");
// read max loadable blocks, more blocks will be swapped out
KateBuffer::setMaxLoadedBlocks (config->readNumEntry("Maximal Loaded Blocks", KateBuffer::maxLoadedBlocks()));
KateDocumentConfig::global()->readConfig (config);
config->setGroup("Kate View Defaults");
KateViewConfig::global()->readConfig (config);
config->setGroup("Kate Renderer Defaults");
KateRendererConfig::global()->readConfig (config);
}
void KateDocument::writeConfig(TDEConfig *config)
{
config->setGroup("Kate Document Defaults");
// write max loadable blocks, more blocks will be swapped out
config->writeEntry("Maximal Loaded Blocks", KateBuffer::maxLoadedBlocks());
KateDocumentConfig::global()->writeConfig (config);
config->setGroup("Kate View Defaults");
KateViewConfig::global()->writeConfig (config);
config->setGroup("Kate Renderer Defaults");
KateRendererConfig::global()->writeConfig (config);
}
void KateDocument::readConfig()
{
TDEConfig *config = kapp->config();
readConfig (config);
}
void KateDocument::writeConfig()
{
TDEConfig *config = kapp->config();
writeConfig (config);
config->sync();
}
void KateDocument::readSessionConfig(TDEConfig *tdeconfig)
{
// restore the url
KURL url (tdeconfig->readEntry("URL"));
// get the encoding
TQString tmpenc=tdeconfig->readEntry("Encoding");
if (!tmpenc.isEmpty() && (tmpenc != encoding()))
setEncoding(tmpenc);
// open the file if url valid
if (!url.isEmpty() && url.isValid())
openURL (url);
// restore the hl stuff
m_buffer->setHighlight(KateHlManager::self()->nameFind(tdeconfig->readEntry("Highlighting")));
if (hlMode() > 0)
hlSetByUser = true;
// indent mode
config()->setIndentationMode( (uint)tdeconfig->readNumEntry("Indentation Mode", config()->indentationMode() ) );
// Restore Bookmarks
TQValueList<int> marks = tdeconfig->readIntListEntry("Bookmarks");
for( uint i = 0; i < marks.count(); i++ )
addMark( marks[i], KateDocument::markType01 );
}
void KateDocument::writeSessionConfig(TDEConfig *tdeconfig)
{
if ( m_url.isLocalFile() && !TDEGlobal::dirs()->relativeLocation("tmp", m_url.path()).startsWith("/"))
return;
// save url
tdeconfig->writeEntry("URL", m_url.prettyURL() );
// save encoding
tdeconfig->writeEntry("Encoding",encoding());
// save hl
tdeconfig->writeEntry("Highlighting", highlight()->name());
tdeconfig->writeEntry("Indentation Mode", config()->indentationMode() );
// Save Bookmarks
TQValueList<int> marks;
for( TQIntDictIterator<KTextEditor::Mark> it( m_marks );
it.current() && it.current()->type & KTextEditor::MarkInterface::markType01;
++it )
marks << it.current()->line;
tdeconfig->writeEntry( "Bookmarks", marks );
}
void KateDocument::configDialog()
{
KDialogBase *kd = new KDialogBase ( KDialogBase::IconList,
i18n("Configure"),
KDialogBase::Ok | KDialogBase::Cancel | KDialogBase::Help,
KDialogBase::Ok,
kapp->mainWidget() );
#ifndef Q_WS_WIN //TODO: reenable
KWin::setIcons( kd->winId(), kapp->icon(), kapp->miniIcon() );
#endif
TQPtrList<KTextEditor::ConfigPage> editorPages;
for (uint i = 0; i < KTextEditor::configInterfaceExtension (this)->configPages (); i++)
{
TQStringList path;
path.clear();
path << KTextEditor::configInterfaceExtension (this)->configPageName (i);
TQVBox *page = kd->addVBoxPage(path, KTextEditor::configInterfaceExtension (this)->configPageFullName (i),
KTextEditor::configInterfaceExtension (this)->configPagePixmap(i, TDEIcon::SizeMedium) );
editorPages.append (KTextEditor::configInterfaceExtension (this)->configPage(i, page));
}
if (kd->exec())
{
KateDocumentConfig::global()->configStart ();
KateViewConfig::global()->configStart ();
KateRendererConfig::global()->configStart ();
for (uint i=0; i<editorPages.count(); i++)
{
editorPages.at(i)->apply();
}
KateDocumentConfig::global()->configEnd ();
KateViewConfig::global()->configEnd ();
KateRendererConfig::global()->configEnd ();
writeConfig ();
}
delete kd;
}
uint KateDocument::mark( uint line )
{
if( !m_marks[line] )
return 0;
return m_marks[line]->type;
}
void KateDocument::setMark( uint line, uint markType )
{
clearMark( line );
addMark( line, markType );
}
void KateDocument::clearMark( uint line )
{
if( line > lastLine() )
return;
if( !m_marks[line] )
return;
KTextEditor::Mark* mark = m_marks.take( line );
emit markChanged( *mark, MarkRemoved );
emit marksChanged();
delete mark;
tagLines( line, line );
repaintViews(true);
}
void KateDocument::addMark( uint line, uint markType )
{
if( line > lastLine())
return;
if( markType == 0 )
return;
if( m_marks[line] ) {
KTextEditor::Mark* mark = m_marks[line];
// Remove bits already set
markType &= ~mark->type;
if( markType == 0 )
return;
// Add bits
mark->type |= markType;
} else {
KTextEditor::Mark *mark = new KTextEditor::Mark;
mark->line = line;
mark->type = markType;
m_marks.insert( line, mark );
}
// Emit with a mark having only the types added.
KTextEditor::Mark temp;
temp.line = line;
temp.type = markType;
emit markChanged( temp, MarkAdded );
emit marksChanged();
tagLines( line, line );
repaintViews(true);
}
void KateDocument::removeMark( uint line, uint markType )
{
if( line > lastLine() )
return;
if( !m_marks[line] )
return;
KTextEditor::Mark* mark = m_marks[line];
// Remove bits not set
markType &= mark->type;
if( markType == 0 )
return;
// Subtract bits
mark->type &= ~markType;
// Emit with a mark having only the types removed.
KTextEditor::Mark temp;
temp.line = line;
temp.type = markType;
emit markChanged( temp, MarkRemoved );
if( mark->type == 0 )
m_marks.remove( line );
emit marksChanged();
tagLines( line, line );
repaintViews(true);
}
TQPtrList<KTextEditor::Mark> KateDocument::marks()
{
TQPtrList<KTextEditor::Mark> list;
for( TQIntDictIterator<KTextEditor::Mark> it( m_marks );
it.current(); ++it ) {
list.append( it.current() );
}
return list;
}
void KateDocument::clearMarks()
{
for( TQIntDictIterator<KTextEditor::Mark> it( m_marks );
it.current(); ++it ) {
KTextEditor::Mark* mark = it.current();
emit markChanged( *mark, MarkRemoved );
tagLines( mark->line, mark->line );
}
m_marks.clear();
emit marksChanged();
repaintViews(true);
}
void KateDocument::setPixmap( MarkInterface::MarkTypes type, const TQPixmap& pixmap )
{
m_markPixmaps.replace( type, new TQPixmap( pixmap ) );
}
void KateDocument::setDescription( MarkInterface::MarkTypes type, const TQString& description )
{
m_markDescriptions.replace( type, new TQString( description ) );
}
TQPixmap *KateDocument::markPixmap( MarkInterface::MarkTypes type )
{
return m_markPixmaps[type];
}
TQColor KateDocument::markColor( MarkInterface::MarkTypes type )
{
uint reserved = (0x1 << KTextEditor::MarkInterface::reservedMarkersCount()) - 1;
if ((uint)type >= (uint)markType01 && (uint)type <= reserved) {
return KateRendererConfig::global()->lineMarkerColor(type);
} else {
return TQColor();
}
}
TQString KateDocument::markDescription( MarkInterface::MarkTypes type )
{
if( m_markDescriptions[type] )
return *m_markDescriptions[type];
return TQString::null;
}
void KateDocument::setMarksUserChangable( uint markMask )
{
m_editableMarks = markMask;
}
uint KateDocument::editableMarks()
{
return m_editableMarks;
}
//END
//BEGIN KTextEditor::PrintInterface stuff
bool KateDocument::printDialog ()
{
return KatePrinter::print (this);
}
bool KateDocument::print ()
{
return KatePrinter::print (this);
}
//END
//BEGIN KTextEditor::DocumentInfoInterface (### unfinished)
TQString KateDocument::mimeType()
{
KMimeType::Ptr result = KMimeType::defaultMimeTypePtr();
// if the document has a URL, try KMimeType::findByURL
if ( ! m_url.isEmpty() )
result = KMimeType::findByURL( m_url );
else if ( m_url.isEmpty() || ! m_url.isLocalFile() )
result = mimeTypeForContent();
return result->name();
}
// TODO implement this -- how to calculate?
long KateDocument::fileSize()
{
return 0;
}
// TODO implement this
TQString KateDocument::niceFileSize()
{
return "UNKNOWN";
}
KMimeType::Ptr KateDocument::mimeTypeForContent()
{
TQByteArray buf (1024);
uint bufpos = 0;
for (uint i=0; i < numLines(); i++)
{
TQString line = textLine( i );
uint len = line.length() + 1;
if (bufpos + len > 1024)
len = 1024 - bufpos;
memcpy(&buf[bufpos], (line + "\n").latin1(), len);
bufpos += len;
if (bufpos >= 1024)
break;
}
buf.resize( bufpos );
int accuracy = 0;
return KMimeType::findByContent( buf, &accuracy );
}
//END KTextEditor::DocumentInfoInterface
//BEGIN KParts::ReadWrite stuff
bool KateDocument::openURL( const KURL &url )
{
// kdDebug(13020)<<"KateDocument::openURL( "<<url.prettyURL()<<")"<<endl;
// no valid URL
if ( !url.isValid() )
return false;
// could not close old one
if ( !closeURL() )
return false;
// set my url
m_url = url;
if ( m_url.isLocalFile() )
{
// local mode, just like in kpart
m_file = m_url.path();
emit started( 0 );
if (openFile())
{
emit completed();
emit setWindowCaption( m_url.prettyURL() );
return true;
}
return false;
}
else
{
// remote mode
m_bTemp = true;
m_tempFile = new KTempFile ();
m_file = m_tempFile->name();
m_job = TDEIO::get ( url, false, isProgressInfoEnabled() );
// connect to slots
connect( m_job, TQT_SIGNAL( data( TDEIO::Job*, const TQByteArray& ) ),
TQT_SLOT( slotDataKate( TDEIO::Job*, const TQByteArray& ) ) );
connect( m_job, TQT_SIGNAL( result( TDEIO::Job* ) ),
TQT_SLOT( slotFinishedKate( TDEIO::Job* ) ) );
TQWidget *w = widget ();
if (!w && !m_views.isEmpty ())
w = m_views.first();
if (w)
m_job->setWindow (w->topLevelWidget());
emit started( m_job );
return true;
}
}
void KateDocument::slotDataKate ( TDEIO::Job *, const TQByteArray &data )
{
// kdDebug(13020) << "KateDocument::slotData" << endl;
if (!m_tempFile || !m_tempFile->file())
return;
m_tempFile->file()->writeBlock (data);
}
void KateDocument::slotFinishedKate ( TDEIO::Job * job )
{
// kdDebug(13020) << "KateDocument::slotJobFinished" << endl;
if (!m_tempFile)
return;
delete m_tempFile;
m_tempFile = 0;
m_job = 0;
if (job->error())
emit canceled( job->errorString() );
else
{
if ( openFile(job) )
emit setWindowCaption( m_url.prettyURL() );
emit completed();
}
}
void KateDocument::abortLoadKate()
{
if ( m_job )
{
kdDebug(13020) << "Aborting job " << m_job << endl;
m_job->kill();
m_job = 0;
}
delete m_tempFile;
m_tempFile = 0;
}
bool KateDocument::openFile()
{
return openFile (0);
}
bool KateDocument::openFile(TDEIO::Job * job)
{
m_loading = true;
// add new m_file to dirwatch
activateDirWatch ();
//
// use metadata
//
if (job)
{
TQString metaDataCharset = job->queryMetaData("charset");
// only overwrite config if nothing set
if (!metaDataCharset.isEmpty () && (!m_config->isSetEncoding() || m_config->encoding().isEmpty()))
setEncoding (metaDataCharset);
}
//
// service type magic to get encoding right
//
TQString serviceType = m_extension->urlArgs().serviceType.simplifyWhiteSpace();
int pos = serviceType.find(';');
if (pos != -1)
setEncoding (serviceType.mid(pos+1));
// if the encoding is set here - on the command line/from the dialog/from TDEIO
// we prevent file type and document variables from changing it
bool encodingSticky = m_encodingSticky;
m_encodingSticky = m_config->isSetEncoding();
// Try getting the filetype here, so that variables does not have to be reset.
int fileTypeFound = KateFactory::self()->fileTypeManager()->fileType (this);
if ( fileTypeFound > -1 )
updateFileType( fileTypeFound );
// read dir config (if possible and wanted)
if (!m_reloading)
readDirConfig ();
// do we have success ?
bool success = m_buffer->openFile (m_file);
//
// yeah, success
//
m_loading = false; // done reading file.
if (success)
{
/*if (highlight() && !m_url.isLocalFile()) {
// The buffer's highlighting gets nuked by KateBuffer::clear()
m_buffer->setHighlight(m_highlight);
}*/
// update our hl type if needed
if (!hlSetByUser)
{
int hl (KateHlManager::self()->detectHighlighting (this));
if (hl >= 0)
m_buffer->setHighlight(hl);
}
// update file type if we haven't allready done so.
if ( fileTypeFound < 0 )
updateFileType (KateFactory::self()->fileTypeManager()->fileType (this));
// read vars
readVariables();
// update the md5 digest
createDigest( m_digest );
}
//
// update views
//
for (KateView * view = m_views.first(); view != 0L; view = m_views.next() )
{
view->updateView(true);
}
//
// emit the signal we need for example for kate app
//
emit fileNameChanged ();
//
// set doc name, dummy value as arg, don't need it
//
setDocName (TQString::null);
//
// to houston, we are not modified
//
if (m_modOnHd)
{
m_modOnHd = false;
m_modOnHdReason = 0;
emit modifiedOnDisc (this, m_modOnHd, 0);
}
//
// display errors
//
if (s_openErrorDialogsActivated)
{
if (!success && m_buffer->loadingBorked())
KMessageBox::error (widget(), i18n ("The file %1 could not be loaded completely, as there is not enough temporary disk storage for it.").arg(m_url.url()));
else if (!success)
KMessageBox::error (widget(), i18n ("The file %1 could not be loaded, as it was not possible to read from it.\n\nCheck if you have read access to this file.").arg(m_url.url()));
}
// warn -> opened binary file!!!!!!!
if (m_buffer->binary())
{
// this file can't be saved again without killing it
setReadWrite( false );
KMessageBox::information (widget()
, i18n ("The file %1 is a binary, saving it will result in a corrupt file.").arg(m_url.url())
, i18n ("Binary File Opened")
, "Binary File Opened Warning");
}
m_encodingSticky = encodingSticky;
//
// return the success
//
return success;
}
bool KateDocument::save()
{
bool l ( url().isLocalFile() );
if ( ( l && config()->backupFlags() & KateDocumentConfig::LocalFiles )
|| ( ! l && config()->backupFlags() & KateDocumentConfig::RemoteFiles ) )
{
KURL u( url() );
u.setFileName( config()->backupPrefix() + url().fileName() + config()->backupSuffix() );
kdDebug () << "backup src file name: " << url() << endl;
kdDebug () << "backup dst file name: " << u << endl;
// get the right permissions, start with safe default
mode_t perms = 0600;
TDEIO::UDSEntry fentry;
if (TDEIO::NetAccess::stat (url(), fentry, kapp->mainWidget()))
{
kdDebug () << "stating succesfull: " << url() << endl;
KFileItem item (fentry, url());
perms = item.permissions();
}
// first del existing file if any, than copy over the file we have
// failure if a: the existing file could not be deleted, b: the file could not be copied
if ( (!TDEIO::NetAccess::exists( u, false, kapp->mainWidget() ) || TDEIO::NetAccess::del( u, kapp->mainWidget() ))
&& TDEIO::NetAccess::file_copy( url(), u, perms, true, false, kapp->mainWidget() ) )
{
kdDebug(13020)<<"backing up successfull ("<<url().prettyURL()<<" -> "<<u.prettyURL()<<")"<<endl;
}
else
{
kdDebug(13020)<<"backing up failed ("<<url().prettyURL()<<" -> "<<u.prettyURL()<<")"<<endl;
// FIXME: notify user for real ;)
}
}
return KParts::ReadWritePart::save();
}
bool KateDocument::saveFile()
{
//
// we really want to save this file ?
//
if (m_buffer->loadingBorked() && (KMessageBox::warningContinueCancel(widget(),
i18n("This file could not be loaded correctly due to lack of temporary disk space. Saving it could cause data loss.\n\nDo you really want to save it?"),i18n("Possible Data Loss"),i18n("Save Nevertheless")) != KMessageBox::Continue))
return false;
//
// warn -> try to save binary file!!!!!!!
//
if (m_buffer->binary() && (KMessageBox::warningContinueCancel (widget()
, i18n ("The file %1 is a binary, saving it will result in a corrupt file.").arg(m_url.url())
, i18n ("Trying to Save Binary File")
, i18n("Save Nevertheless"), "Binary File Save Warning") != KMessageBox::Continue))
return false;
if ( !url().isEmpty() )
{
if (s_fileChangedDialogsActivated && m_modOnHd)
{
TQString str = reasonedMOHString() + "\n\n";
if (!isModified())
{
if (KMessageBox::warningContinueCancel(0,
str + i18n("Do you really want to save this unmodified file? You could overwrite changed data in the file on disk."),i18n("Trying to Save Unmodified File"),i18n("Save Nevertheless")) != KMessageBox::Continue)
return false;
}
else
{
if (KMessageBox::warningContinueCancel(0,
str + i18n("Do you really want to save this file? Both your open file and the file on disk were changed. There could be some data lost."),i18n("Possible Data Loss"),i18n("Save Nevertheless")) != KMessageBox::Continue)
return false;
}
}
}
//
// can we encode it if we want to save it ?
//
if (!m_buffer->canEncode ()
&& (KMessageBox::warningContinueCancel(0,
i18n("The selected encoding cannot encode every unicode character in this document. Do you really want to save it? There could be some data lost."),i18n("Possible Data Loss"),i18n("Save Nevertheless")) != KMessageBox::Continue))
{
return false;
}
// remove file from dirwatch
deactivateDirWatch ();
//
// try to save
//
bool success = m_buffer->saveFile (m_file);
// update the md5 digest
createDigest( m_digest );
// add m_file again to dirwatch
activateDirWatch ();
//
// hurray, we had success, do stuff we need
//
if (success)
{
// update our hl type if needed
if (!hlSetByUser)
{
int hl (KateHlManager::self()->detectHighlighting (this));
if (hl >= 0)
m_buffer->setHighlight(hl);
}
// read our vars
readVariables();
}
//
// we are not modified
//
if (success && m_modOnHd)
{
m_modOnHd = false;
m_modOnHdReason = 0;
emit modifiedOnDisc (this, m_modOnHd, 0);
}
//
// display errors
//
if (!success)
KMessageBox::error (widget(), i18n ("The document could not be saved, as it was not possible to write to %1.\n\nCheck that you have write access to this file or that enough disk space is available.").arg(m_url.url()));
//
// return success
//
return success;
}
bool KateDocument::saveAs( const KURL &u )
{
TQString oldDir = url().directory();
if ( KParts::ReadWritePart::saveAs( u ) )
{
// null means base on filename
setDocName( TQString::null );
if ( u.directory() != oldDir )
readDirConfig();
emit fileNameChanged();
emit nameChanged((Kate::Document *) this);
return true;
}
return false;
}
void KateDocument::readDirConfig ()
{
int depth = config()->searchDirConfigDepth ();
if (m_url.isLocalFile() && (depth > -1))
{
TQString currentDir = TQFileInfo (m_file).dirPath();
// only search as deep as specified or not at all ;)
while (depth > -1)
{
kdDebug (13020) << "search for config file in path: " << currentDir << endl;
// try to open config file in this dir
TQFile f (currentDir + "/.kateconfig");
if (f.open (IO_ReadOnly))
{
TQTextStream stream (&f);
uint linesRead = 0;
TQString line = stream.readLine();
while ((linesRead < 32) && !line.isNull())
{
readVariableLine( line );
line = stream.readLine();
linesRead++;
}
break;
}
TQString newDir = TQFileInfo (currentDir).dirPath();
// bail out on looping (for example reached /)
if (currentDir == newDir)
break;
currentDir = newDir;
--depth;
}
}
}
void KateDocument::activateDirWatch ()
{
// same file as we are monitoring, return
if (m_file == m_dirWatchFile)
return;
// remove the old watched file
deactivateDirWatch ();
// add new file if needed
if (m_url.isLocalFile() && !m_file.isEmpty())
{
KateFactory::self()->dirWatch ()->addFile (m_file);
m_dirWatchFile = m_file;
}
}
void KateDocument::deactivateDirWatch ()
{
if (!m_dirWatchFile.isEmpty())
KateFactory::self()->dirWatch ()->removeFile (m_dirWatchFile);
m_dirWatchFile = TQString::null;
}
bool KateDocument::closeURL()
{
abortLoadKate();
//
// file mod on hd
//
if ( !m_reloading && !url().isEmpty() )
{
if (s_fileChangedDialogsActivated && m_modOnHd)
{
if (!(KMessageBox::warningContinueCancel(
widget(),
reasonedMOHString() + "\n\n" + i18n("Do you really want to continue to close this file? Data loss may occur."),
i18n("Possible Data Loss"), i18n("Close Nevertheless"),
TQString("kate_close_modonhd_%1").arg( m_modOnHdReason ) ) == KMessageBox::Continue))
return false;
}
}
//
// first call the normal tdeparts implementation
//
if (!KParts::ReadWritePart::closeURL ())
return false;
// remove file from dirwatch
deactivateDirWatch ();
//
// empty url + filename
//
m_url = KURL ();
m_file = TQString::null;
// we are not modified
if (m_modOnHd)
{
m_modOnHd = false;
m_modOnHdReason = 0;
emit modifiedOnDisc (this, m_modOnHd, 0);
}
// clear the buffer
m_buffer->clear();
// remove all marks
clearMarks ();
// clear undo/redo history
clearUndo();
clearRedo();
// no, we are no longer modified
setModified(false);
// we have no longer any hl
m_buffer->setHighlight(0);
// update all our views
for (KateView * view = m_views.first(); view != 0L; view = m_views.next() )
{
// Explicitly call the internal version because we don't want this to look like
// an external request (and thus have the view not TQWidget::scroll()ed.
view->setCursorPositionInternal(0, 0, 1, false);
view->clearSelection();
view->updateView(true);
}
// uh, filename changed
emit fileNameChanged ();
// update doc name
setDocName (TQString::null);
// success
return true;
}
void KateDocument::setReadWrite( bool rw )
{
if (isReadWrite() != rw)
{
KParts::ReadWritePart::setReadWrite (rw);
for( KateView* view = m_views.first(); view != 0L; view = m_views.next() )
{
view->slotUpdate();
view->slotReadWriteChanged ();
}
}
}
void KateDocument::setModified(bool m) {
if (isModified() != m) {
KParts::ReadWritePart::setModified (m);
for( KateView* view = m_views.first(); view != 0L; view = m_views.next() )
{
view->slotUpdate();
}
emit modifiedChanged ();
emit modStateChanged ((Kate::Document *)this);
}
if ( m == false )
{
if ( ! undoItems.isEmpty() )
{
lastUndoGroupWhenSaved = undoItems.last();
}
if ( ! redoItems.isEmpty() )
{
lastRedoGroupWhenSaved = redoItems.last();
}
docWasSavedWhenUndoWasEmpty = undoItems.isEmpty();
docWasSavedWhenRedoWasEmpty = redoItems.isEmpty();
}
}
//END
//BEGIN Kate specific stuff ;)
void KateDocument::makeAttribs(bool needInvalidate)
{
for (uint z = 0; z < m_views.count(); z++)
m_views.at(z)->renderer()->updateAttributes ();
if (needInvalidate)
m_buffer->invalidateHighlighting();
tagAll ();
}
// the attributes of a hl have changed, update
void KateDocument::internalHlChanged()
{
makeAttribs();
}
void KateDocument::addView(KTextEditor::View *view) {
if (!view)
return;
m_views.append( (KateView *) view );
m_textEditViews.append( view );
// apply the view & renderer vars from the file type
const KateFileType *t = 0;
if ((m_fileType > -1) && (t = KateFactory::self()->fileTypeManager()->fileType(m_fileType)))
readVariableLine (t->varLine, true);
// apply the view & renderer vars from the file
readVariables (true);
m_activeView = (KateView *) view;
}
void KateDocument::removeView(KTextEditor::View *view) {
if (!view)
return;
if (m_activeView == view)
m_activeView = 0L;
m_views.removeRef( (KateView *) view );
m_textEditViews.removeRef( view );
}
void KateDocument::addSuperCursor(KateSuperCursor *cursor, bool privateC) {
if (!cursor)
return;
m_superCursors.append( cursor );
if (!privateC)
myCursors.append( cursor );
}
void KateDocument::removeSuperCursor(KateSuperCursor *cursor, bool privateC) {
if (!cursor)
return;
if (!privateC)
myCursors.removeRef( cursor );
m_superCursors.removeRef( cursor );
}
bool KateDocument::ownedView(KateView *view) {
// do we own the given view?
return (m_views.containsRef(view) > 0);
}
bool KateDocument::isLastView(int numViews) {
return ((int) m_views.count() == numViews);
}
uint KateDocument::currentColumn( const KateTextCursor& cursor )
{
KateTextLine::Ptr textLine = m_buffer->plainLine(cursor.line());
if (textLine)
return textLine->cursorX(cursor.col(), config()->tabWidth());
else
return 0;
}
bool KateDocument::typeChars ( KateView *view, const TQString &chars )
{
KateTextLine::Ptr textLine = m_buffer->plainLine(view->cursorLine ());
if (!textLine)
return false;
bool bracketInserted = false;
TQString buf;
TQChar c;
for( uint z = 0; z < chars.length(); z++ )
{
TQChar ch = c = chars[z];
if (ch.isPrint() || ch == '\t')
{
buf.append (ch);
if (!bracketInserted && (config()->configFlags() & KateDocument::cfAutoBrackets))
{
TQChar end_ch;
bool complete = true;
TQChar prevChar = textLine->getChar(view->cursorColumnReal()-1);
TQChar nextChar = textLine->getChar(view->cursorColumnReal());
switch(ch) {
case '(': end_ch = ')'; break;
case '[': end_ch = ']'; break;
case '{': end_ch = '}'; break;
case '\'':end_ch = '\'';break;
case '"': end_ch = '"'; break;
default: complete = false;
}
if (complete)
{
if (view->hasSelection())
{ // there is a selection, enclose the selection
buf.append (view->selection());
buf.append (end_ch);
bracketInserted = true;
}
else
{ // no selection, check whether we should better refuse to complete
if ( ( (ch == '\'' || ch == '"') &&
(prevChar.isLetterOrNumber() || prevChar == ch) )
|| nextChar.isLetterOrNumber()
|| (nextChar == end_ch && prevChar != ch) )
{
kdDebug(13020) << "AutoBracket refused before: " << nextChar << "\n";
}
else
{
buf.append (end_ch);
bracketInserted = true;
}
}
}
}
}
}
if (buf.isEmpty())
return false;
editStart ();
if (!view->config()->persistentSelection() && view->hasSelection() )
view->removeSelectedText();
int oldLine = view->cursorLine ();
int oldCol = view->cursorColumnReal ();
if (config()->configFlags() & KateDocument::cfOvr)
removeText (view->cursorLine(), view->cursorColumnReal(), view->cursorLine(), kMin( view->cursorColumnReal()+buf.length(), textLine->length() ) );
insertText (view->cursorLine(), view->cursorColumnReal(), buf);
m_indenter->processChar(c);
editEnd ();
if (bracketInserted)
view->setCursorPositionInternal (view->cursorLine(), view->cursorColumnReal()-1);
emit charactersInteractivelyInserted (oldLine, oldCol, chars);
return true;
}
void KateDocument::newLine( KateTextCursor& c, KateViewInternal *v )
{
editStart();
if( !v->view()->config()->persistentSelection() && v->view()->hasSelection() )
v->view()->removeSelectedText();
// temporary hack to get the cursor pos right !!!!!!!!!
c = v->getCursor ();
if (c.line() > (int)lastLine())
c.setLine(lastLine());
if ( c.line() < 0 )
c.setLine( 0 );
uint ln = c.line();
KateTextLine::Ptr textLine = kateTextLine(c.line());
if (c.col() > (int)textLine->length())
c.setCol(textLine->length());
if (m_indenter->canProcessNewLine ())
{
int pos = textLine->firstChar();
// length should do the job better
if (pos < 0)
pos = textLine->length();
if (c.col() < pos)
c.setCol(pos); // place cursor on first char if before
editWrapLine (c.line(), c.col());
KateDocCursor cursor (c.line() + 1, pos, this);
m_indenter->processNewline(cursor, true);
c.setPos(cursor);
}
else
{
editWrapLine (c.line(), c.col());
c.setPos(c.line() + 1, 0);
}
removeTrailingSpace( ln );
editEnd();
}
void KateDocument::transpose( const KateTextCursor& cursor)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(cursor.line());
if (!textLine || (textLine->length() < 2))
return;
uint col = cursor.col();
if (col > 0)
col--;
if ((textLine->length() - col) < 2)
return;
uint line = cursor.line();
TQString s;
//clever swap code if first character on the line swap right&left
//otherwise left & right
s.append (textLine->getChar(col+1));
s.append (textLine->getChar(col));
//do the swap
// do it right, never ever manipulate a textline
editStart ();
editRemoveText (line, col, 2);
editInsertText (line, col, s);
editEnd ();
}
void KateDocument::backspace( KateView *view, const KateTextCursor& c )
{
if ( !view->config()->persistentSelection() && view->hasSelection() ) {
view->removeSelectedText();
return;
}
uint col = kMax( c.col(), 0 );
uint line = kMax( c.line(), 0 );
if ((col == 0) && (line == 0))
return;
int complement = 0;
if (col > 0)
{
if (config()->configFlags() & KateDocument::cfAutoBrackets)
{
// if inside empty (), {}, [], '', "" delete both
KateTextLine::Ptr tl = m_buffer->plainLine(line);
if(!tl) return;
TQChar prevChar = tl->getChar(col-1);
TQChar nextChar = tl->getChar(col);
if ( (prevChar == '"' && nextChar == '"') ||
(prevChar == '\'' && nextChar == '\'') ||
(prevChar == '(' && nextChar == ')') ||
(prevChar == '[' && nextChar == ']') ||
(prevChar == '{' && nextChar == '}') )
{
complement = 1;
}
}
if (!(config()->configFlags() & KateDocument::cfBackspaceIndents))
{
// ordinary backspace
//c.cursor.col--;
removeText(line, col-1, line, col+complement);
}
else
{
// backspace indents: erase to next indent position
KateTextLine::Ptr textLine = m_buffer->plainLine(line);
// don't forget this check!!!! really!!!!
if (!textLine)
return;
int colX = textLine->cursorX(col, config()->tabWidth());
int pos = textLine->firstChar();
if (pos > 0)
pos = textLine->cursorX(pos, config()->tabWidth());
if (pos < 0 || pos >= (int)colX)
{
// only spaces on left side of cursor
indent( view, line, -1);
}
else
removeText(line, col-1, line, col+complement);
}
}
else
{
// col == 0: wrap to previous line
if (line >= 1)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(line-1);
// don't forget this check!!!! really!!!!
if (!textLine)
return;
if (config()->wordWrap() && textLine->endingWith(TQString::fromLatin1(" ")))
{
// gg: in hard wordwrap mode, backspace must also eat the trailing space
removeText (line-1, textLine->length()-1, line, 0);
}
else
removeText (line-1, textLine->length(), line, 0);
}
}
emit backspacePressed();
}
void KateDocument::del( KateView *view, const KateTextCursor& c )
{
if ( !view->config()->persistentSelection() && view->hasSelection() ) {
view->removeSelectedText();
return;
}
if( c.col() < (int) m_buffer->plainLine(c.line())->length())
{
removeText(c.line(), c.col(), c.line(), c.col()+1);
}
else if ( (uint)c.line() < lastLine() )
{
removeText(c.line(), c.col(), c.line()+1, 0);
}
}
void KateDocument::paste ( KateView* view )
{
TQString s = TQApplication::clipboard()->text();
if (s.isEmpty())
return;
uint lines = s.contains (TQChar ('\n'));
m_undoDontMerge = true;
editStart ();
if (!view->config()->persistentSelection() && view->hasSelection() )
view->removeSelectedText();
uint line = view->cursorLine ();
uint column = view->cursorColumnReal ();
insertText ( line, column, s, view->blockSelectionMode() );
editEnd();
// move cursor right for block select, as the user is moved right internal
// even in that case, but user expects other behavior in block selection
// mode !
if (view->blockSelectionMode())
view->setCursorPositionInternal (line+lines, column);
if (m_indenter->canProcessLine()
&& config()->configFlags() & KateDocumentConfig::cfIndentPastedText)
{
editStart();
KateDocCursor begin(line, 0, this);
KateDocCursor end(line + lines, 0, this);
m_indenter->processSection (begin, end);
editEnd();
}
if (!view->blockSelectionMode()) emit charactersSemiInteractivelyInserted (line, column, s);
m_undoDontMerge = true;
}
void KateDocument::insertIndentChars ( KateView *view )
{
editStart ();
TQString s;
if (config()->configFlags() & KateDocument::cfSpaceIndent)
{
int width = config()->indentationWidth();
s.fill (' ', width - (view->cursorColumnReal() % width));
}
else
s.append ('\t');
insertText (view->cursorLine(), view->cursorColumnReal(), s);
editEnd ();
}
void KateDocument::indent ( KateView *v, uint line, int change)
{
editStart ();
if (!hasSelection())
{
// single line
optimizeLeadingSpace(line, config()->configFlags(), change);
}
else
{
int sl = v->selStartLine();
int el = v->selEndLine();
int ec = v->selEndCol();
if ((ec == 0) && ((el-1) >= 0))
{
el--; /* */
}
if (config()->configFlags() & KateDocument::cfKeepIndentProfile && change < 0) {
// unindent so that the existing indent profile doesn't get screwed
// if any line we may unindent is already full left, don't do anything
int adjustedChange = -change;
for (line = sl; (int) line <= el && adjustedChange > 0; line++) {
KateTextLine::Ptr textLine = m_buffer->plainLine(line);
int firstChar = textLine->firstChar();
if (firstChar >= 0 && (v->lineSelected(line) || v->lineHasSelected(line))) {
int maxUnindent = textLine->cursorX(firstChar, config()->tabWidth()) / config()->indentationWidth();
if (maxUnindent < adjustedChange)
adjustedChange = maxUnindent;
}
}
change = -adjustedChange;
}
const bool rts = config()->configFlags() & KateDocumentConfig::cfRemoveTrailingDyn;
for (line = sl; (int) line <= el; line++) {
if ((v->lineSelected(line) || v->lineHasSelected(line))
&& (!rts || lineLength(line) > 0)) {
optimizeLeadingSpace(line, config()->configFlags(), change);
}
}
}
editEnd ();
}
void KateDocument::align(KateView *view, uint line)
{
if (m_indenter->canProcessLine())
{
editStart ();
if (!view->hasSelection())
{
KateDocCursor curLine(line, 0, this);
m_indenter->processLine (curLine);
editEnd ();
activeView()->setCursorPosition (line, curLine.col());
}
else
{
m_indenter->processSection (view->selStart(), view->selEnd());
editEnd ();
}
}
}
/*
Optimize the leading whitespace for a single line.
If change is > 0, it adds indentation units (indentationChars)
if change is == 0, it only optimizes
If change is < 0, it removes indentation units
This will be used to indent, unindent, and optimal-fill a line.
If excess space is removed depends on the flag cfKeepExtraSpaces
which has to be set by the user
*/
void KateDocument::optimizeLeadingSpace(uint line, int flags, int change)
{
KateTextLine::Ptr textline = m_buffer->plainLine(line);
int first_char = textline->firstChar();
int w = 0;
if (flags & KateDocument::cfSpaceIndent)
w = config()->indentationWidth();
else
w = config()->tabWidth();
if (first_char < 0)
first_char = textline->length();
int space = textline->cursorX(first_char, config()->tabWidth()) + change * w;
if (space < 0)
space = 0;
if (!(flags & KateDocument::cfKeepExtraSpaces))
{
uint extra = space % w;
space -= extra;
if (extra && change < 0) {
// otherwise it unindents too much (e.g. 12 chars when indentation is 8 chars wide)
space += w;
}
}
//kdDebug(13020) << "replace With Op: " << line << " " << first_char << " " << space << endl;
replaceWithOptimizedSpace(line, first_char, space, flags);
}
void KateDocument::replaceWithOptimizedSpace(uint line, uint upto_column, uint space, int flags)
{
uint length;
TQString new_space;
if (flags & KateDocument::cfSpaceIndent && ! (flags & KateDocumentConfig::cfMixedIndent) ) {
length = space;
new_space.fill(' ', length);
}
else {
length = space / config()->tabWidth();
new_space.fill('\t', length);
TQString extra_space;
extra_space.fill(' ', space % config()->tabWidth());
length += space % config()->tabWidth();
new_space += extra_space;
}
KateTextLine::Ptr textline = m_buffer->plainLine(line);
uint change_from;
for (change_from = 0; change_from < upto_column && change_from < length; change_from++) {
if (textline->getChar(change_from) != new_space[change_from])
break;
}
editStart();
if (change_from < upto_column)
removeText(line, change_from, line, upto_column);
if (change_from < length)
insertText(line, change_from, new_space.right(length - change_from));
editEnd();
}
/*
Remove a given string at the begining
of the current line.
*/
bool KateDocument::removeStringFromBegining(int line, TQString &str)
{
KateTextLine::Ptr textline = m_buffer->plainLine(line);
int index = 0;
bool there = false;
if (textline->startingWith(str))
there = true;
else
{
index = textline->firstChar ();
if ((index >= 0) && (textline->length() >= (index + str.length())) && (textline->string(index, str.length()) == str))
there = true;
}
if (there)
{
// Remove some chars
removeText (line, index, line, index+str.length());
}
return there;
}
/*
Remove a given string at the end
of the current line.
*/
bool KateDocument::removeStringFromEnd(int line, TQString &str)
{
KateTextLine::Ptr textline = m_buffer->plainLine(line);
int index = 0;
bool there = false;
if(textline->endingWith(str))
{
index = textline->length() - str.length();
there = true;
}
else
{
index = textline->lastChar ()-str.length()+1;
if ((index >= 0) && (textline->length() >= (index + str.length())) && (textline->string(index, str.length()) == str))
there = true;
}
if (there)
{
// Remove some chars
removeText (line, index, line, index+str.length());
}
return there;
}
/*
Add to the current line a comment line mark at
the begining.
*/
void KateDocument::addStartLineCommentToSingleLine( int line, int attrib )
{
if (highlight()->getCommentSingleLinePosition(attrib)==KateHighlighting::CSLPosColumn0)
{
TQString commentLineMark = highlight()->getCommentSingleLineStart( attrib ) + " ";
insertText (line, 0, commentLineMark);
}
else
{
TQString commentLineMark=highlight()->getCommentSingleLineStart(attrib);
KateTextLine::Ptr l = m_buffer->line(line);
int pos=l->firstChar();
if (pos >=0)
insertText(line,pos,commentLineMark);
}
}
/*
Remove from the current line a comment line mark at
the begining if there is one.
*/
bool KateDocument::removeStartLineCommentFromSingleLine( int line, int attrib )
{
TQString shortCommentMark = highlight()->getCommentSingleLineStart( attrib );
TQString longCommentMark = shortCommentMark + " ";
editStart();
// Try to remove the long comment mark first
bool removed = (removeStringFromBegining(line, longCommentMark)
|| removeStringFromBegining(line, shortCommentMark));
editEnd();
return removed;
}
/*
Add to the current line a start comment mark at the
begining and a stop comment mark at the end.
*/
void KateDocument::addStartStopCommentToSingleLine( int line, int attrib )
{
TQString startCommentMark = highlight()->getCommentStart( attrib ) + " ";
TQString stopCommentMark = " " + highlight()->getCommentEnd( attrib );
editStart();
// Add the start comment mark
insertText (line, 0, startCommentMark);
// Go to the end of the line
int col = m_buffer->plainLine(line)->length();
// Add the stop comment mark
insertText (line, col, stopCommentMark);
editEnd();
}
/*
Remove from the current line a start comment mark at
the begining and a stop comment mark at the end.
*/
bool KateDocument::removeStartStopCommentFromSingleLine( int line, int attrib )
{
TQString shortStartCommentMark = highlight()->getCommentStart( attrib );
TQString longStartCommentMark = shortStartCommentMark + " ";
TQString shortStopCommentMark = highlight()->getCommentEnd( attrib );
TQString longStopCommentMark = " " + shortStopCommentMark;
editStart();
#ifdef __GNUC__
#warning "that's a bad idea, can lead to stray endings, FIXME"
#endif
// Try to remove the long start comment mark first
bool removedStart = (removeStringFromBegining(line, longStartCommentMark)
|| removeStringFromBegining(line, shortStartCommentMark));
bool removedStop = false;
if (removedStart)
{
// Try to remove the long stop comment mark first
removedStop = (removeStringFromEnd(line, longStopCommentMark)
|| removeStringFromEnd(line, shortStopCommentMark));
}
editEnd();
return (removedStart || removedStop);
}
/*
Add to the current selection a start comment
mark at the begining and a stop comment mark
at the end.
*/
void KateDocument::addStartStopCommentToSelection( KateView *view, int attrib )
{
TQString startComment = highlight()->getCommentStart( attrib );
TQString endComment = highlight()->getCommentEnd( attrib );
int sl = view->selStartLine();
int el = view->selEndLine();
int sc = view->selStartCol();
int ec = view->selEndCol();
if ((ec == 0) && ((el-1) >= 0))
{
el--;
ec = m_buffer->plainLine (el)->length();
}
editStart();
insertText (el, ec, endComment);
insertText (sl, sc, startComment);
editEnd ();
// Set the new selection
ec += endComment.length() + ( (el == sl) ? startComment.length() : 0 );
view->setSelection(sl, sc, el, ec);
}
/*
Add to the current selection a comment line
mark at the begining of each line.
*/
void KateDocument::addStartLineCommentToSelection( KateView *view, int attrib )
{
TQString commentLineMark = highlight()->getCommentSingleLineStart( attrib ) + " ";
int sl = view->selStartLine();
int el = view->selEndLine();
if ((view->selEndCol() == 0) && ((el-1) >= 0))
{
el--;
}
editStart();
// For each line of the selection
for (int z = el; z >= sl; z--) {
//insertText (z, 0, commentLineMark);
addStartLineCommentToSingleLine(z, attrib );
}
editEnd ();
// Set the new selection
KateDocCursor end (view->selEnd());
end.setCol(view->selEndCol() + ((el == view->selEndLine()) ? commentLineMark.length() : 0) );
view->setSelection(view->selStartLine(), 0, end.line(), end.col());
}
bool KateDocument::nextNonSpaceCharPos(int &line, int &col)
{
for(; line < (int)m_buffer->count(); line++) {
KateTextLine::Ptr textLine = m_buffer->plainLine(line);
if (!textLine)
break;
col = textLine->nextNonSpaceChar(col);
if(col != -1)
return true; // Next non-space char found
col = 0;
}
// No non-space char found
line = -1;
col = -1;
return false;
}
bool KateDocument::previousNonSpaceCharPos(int &line, int &col)
{
while(true)
{
KateTextLine::Ptr textLine = m_buffer->plainLine(line);
if (!textLine)
break;
col = textLine->previousNonSpaceChar(col);
if(col != -1) return true;
if(line == 0) return false;
--line;
col = textLine->length();
}
// No non-space char found
line = -1;
col = -1;
return false;
}
/*
Remove from the selection a start comment mark at
the begining and a stop comment mark at the end.
*/
bool KateDocument::removeStartStopCommentFromSelection( KateView *view, int attrib )
{
TQString startComment = highlight()->getCommentStart( attrib );
TQString endComment = highlight()->getCommentEnd( attrib );
int sl = kMax<int> (0, view->selStartLine());
int el = kMin<int> (view->selEndLine(), lastLine());
int sc = view->selStartCol();
int ec = view->selEndCol();
// The selection ends on the char before selectEnd
if (ec != 0) {
ec--;
} else {
if (el > 0) {
el--;
ec = m_buffer->plainLine(el)->length() - 1;
}
}
int startCommentLen = startComment.length();
int endCommentLen = endComment.length();
// had this been perl or sed: s/^\s*$startComment(.+?)$endComment\s*/$1/
bool remove = nextNonSpaceCharPos(sl, sc)
&& m_buffer->plainLine(sl)->stringAtPos(sc, startComment)
&& previousNonSpaceCharPos(el, ec)
&& ( (ec - endCommentLen + 1) >= 0 )
&& m_buffer->plainLine(el)->stringAtPos(ec - endCommentLen + 1, endComment);
if (remove) {
editStart();
removeText (el, ec - endCommentLen + 1, el, ec + 1);
removeText (sl, sc, sl, sc + startCommentLen);
editEnd ();
// set new selection not necessary, as the selection cursors are KateSuperCursors
}
return remove;
}
bool KateDocument::removeStartStopCommentFromRegion(const KateTextCursor &start,const KateTextCursor &end,int attrib)
{
TQString startComment = highlight()->getCommentStart( attrib );
TQString endComment = highlight()->getCommentEnd( attrib );
int startCommentLen = startComment.length();
int endCommentLen = endComment.length();
bool remove = m_buffer->plainLine(start.line())->stringAtPos(start.col(), startComment)
&& ( (end.col() - endCommentLen ) >= 0 )
&& m_buffer->plainLine(end.line())->stringAtPos(end.col() - endCommentLen , endComment);
if (remove) {
editStart();
removeText(end.line(),end.col()-endCommentLen,end.line(),end.col());
removeText(start.line(),start.col(),start.line(),start.col()+startCommentLen);
editEnd();
}
return remove;
}
/*
Remove from the begining of each line of the
selection a start comment line mark.
*/
bool KateDocument::removeStartLineCommentFromSelection( KateView *view, int attrib )
{
TQString shortCommentMark = highlight()->getCommentSingleLineStart( attrib );
TQString longCommentMark = shortCommentMark + " ";
int sl = view->selStartLine();
int el = view->selEndLine();
if ((view->selEndCol() == 0) && ((el-1) >= 0))
{
el--;
}
// Find out how many char will be removed from the last line
int removeLength = 0;
if (m_buffer->plainLine(el)->startingWith(longCommentMark))
removeLength = longCommentMark.length();
else if (m_buffer->plainLine(el)->startingWith(shortCommentMark))
removeLength = shortCommentMark.length();
bool removed = false;
editStart();
// For each line of the selection
for (int z = el; z >= sl; z--)
{
// Try to remove the long comment mark first
removed = (removeStringFromBegining(z, longCommentMark)
|| removeStringFromBegining(z, shortCommentMark)
|| removed);
}
editEnd();
// updating selection already done by the KateSuperCursors
return removed;
}
/*
Comment or uncomment the selection or the current
line if there is no selection.
*/
void KateDocument::comment( KateView *v, uint line,uint column, int change)
{
// We need to check that we can sanely comment the selectino or region.
// It is if the attribute of the first and last character of the range to
// comment belongs to the same language definition.
// for lines with no text, we need the attribute for the lines context.
bool hassel = v->hasSelection();
int startAttrib, endAttrib;
if ( hassel )
{
KateTextLine::Ptr ln = kateTextLine( v->selStartLine() );
int l = v->selStartLine(), c = v->selStartCol();
startAttrib = nextNonSpaceCharPos( l, c ) ? kateTextLine( l )->attribute( c ) : 0;
ln = kateTextLine( v->selEndLine() );
l = v->selEndLine(), c = v->selEndCol();
endAttrib = previousNonSpaceCharPos( l, c ) ? kateTextLine( l )->attribute( c ) : 0;
}
else
{
KateTextLine::Ptr ln = kateTextLine( line );
if ( ln->length() )
{
startAttrib = ln->attribute( ln->firstChar() );
endAttrib = ln->attribute( ln->lastChar() );
}
else
{
int l = line, c = 0;
if ( nextNonSpaceCharPos( l, c ) || previousNonSpaceCharPos( l, c ) )
startAttrib = endAttrib = kateTextLine( l )->attribute( c );
else
startAttrib = endAttrib = 0;
}
}
if ( ! highlight()->canComment( startAttrib, endAttrib ) )
{
kdDebug(13020)<<"canComment( "<<startAttrib<<", "<<endAttrib<<" ) returned false!"<<endl;
return;
}
bool hasStartLineCommentMark = !(highlight()->getCommentSingleLineStart( startAttrib ).isEmpty());
bool hasStartStopCommentMark = ( !(highlight()->getCommentStart( startAttrib ).isEmpty())
&& !(highlight()->getCommentEnd( endAttrib ).isEmpty()) );
bool removed = false;
if (change > 0) // comment
{
if ( !hassel )
{
if ( hasStartLineCommentMark )
addStartLineCommentToSingleLine( line, startAttrib );
else if ( hasStartStopCommentMark )
addStartStopCommentToSingleLine( line, startAttrib );
}
else
{
// anders: prefer single line comment to avoid nesting probs
// If the selection starts after first char in the first line
// or ends before the last char of the last line, we may use
// multiline comment markers.
// TODO We should try to detect nesting.
// - if selection ends at col 0, most likely she wanted that
// line ignored
if ( hasStartStopCommentMark &&
( !hasStartLineCommentMark || (
( v->selStartCol() > m_buffer->plainLine( v->selStartLine() )->firstChar() ) ||
( v->selEndCol() < ((int)m_buffer->plainLine( v->selEndLine() )->length()) )
) ) )
addStartStopCommentToSelection( v, startAttrib );
else if ( hasStartLineCommentMark )
addStartLineCommentToSelection( v, startAttrib );
}
}
else // uncomment
{
if ( !hassel )
{
removed = ( hasStartLineCommentMark
&& removeStartLineCommentFromSingleLine( line, startAttrib ) )
|| ( hasStartStopCommentMark
&& removeStartStopCommentFromSingleLine( line, startAttrib ) );
if ((!removed) && foldingTree()) {
kdDebug(13020)<<"easy approach for uncommenting did not work, trying harder (folding tree)"<<endl;
int commentRegion=(highlight()->commentRegion(startAttrib));
if (commentRegion){
KateCodeFoldingNode *n=foldingTree()->findNodeForPosition(line,column);
if (n) {
KateTextCursor start,end;
if ((n->nodeType()==commentRegion) && n->getBegin(foldingTree(), &start) && n->getEnd(foldingTree(), &end)) {
kdDebug(13020)<<"Enclosing region found:"<<start.col()<<"/"<<start.line()<<"-"<<end.col()<<"/"<<end.line()<<endl;
removeStartStopCommentFromRegion(start,end,startAttrib);
} else {
kdDebug(13020)<<"Enclosing region found, but not valid"<<endl;
kdDebug(13020)<<"Region found: "<<n->nodeType()<<" region needed: "<<commentRegion<<endl;
}
//perhaps nested regions should be hadled here too...
} else kdDebug(13020)<<"No enclosing region found"<<endl;
} else kdDebug(13020)<<"No comment region specified for current hl"<<endl;
}
}
else
{
// anders: this seems like it will work with above changes :)
removed = ( hasStartLineCommentMark
&& removeStartLineCommentFromSelection( v, startAttrib ) )
|| ( hasStartStopCommentMark
&& removeStartStopCommentFromSelection( v, startAttrib ) );
}
}
}
void KateDocument::transform( KateView *v, const KateTextCursor &c,
KateDocument::TextTransform t )
{
editStart();
uint cl( c.line() ), cc( c.col() );
bool selectionRestored = false;
if ( hasSelection() )
{
// cache the selection and cursor, so we can be sure to restore.
KateTextCursor selstart = v->selStart();
KateTextCursor selend = v->selEnd();
int ln = v->selStartLine();
while ( ln <= selend.line() )
{
uint start, end;
start = (ln == selstart.line() || v->blockSelectionMode()) ?
selstart.col() : 0;
end = (ln == selend.line() || v->blockSelectionMode()) ?
selend.col() : lineLength( ln );
if ( start > end )
{
uint t = start;
start = end;
end = t;
}
TQString s = text( ln, start, ln, end );
TQString o = s;
if ( t == Uppercase )
s = s.upper();
else if ( t == Lowercase )
s = s.lower();
else // Capitalize
{
KateTextLine::Ptr l = m_buffer->plainLine( ln );
uint p ( 0 );
while( p < s.length() )
{
// If bol or the character before is not in a word, up this one:
// 1. if both start and p is 0, upper char.
// 2. if blockselect or first line, and p == 0 and start-1 is not in a word, upper
// 3. if p-1 is not in a word, upper.
if ( ( ! start && ! p ) ||
( ( ln == selstart.line() || v->blockSelectionMode() ) &&
! p && ! highlight()->isInWord( l->getChar( start - 1 )) ) ||
( p && ! highlight()->isInWord( s.at( p-1 ) ) )
)
s[p] = s.at(p).upper();
p++;
}
}
if ( o != s )
{
removeText( ln, start, ln, end );
insertText( ln, start, s );
}
ln++;
}
// restore selection
v->setSelection( selstart, selend );
selectionRestored = true;
} else { // no selection
TQString o = text( cl, cc, cl, cc + 1 );
TQString s;
int n ( cc );
switch ( t ) {
case Uppercase:
s = o.upper();
break;
case Lowercase:
s = o.lower();
break;
case Capitalize:
{
KateTextLine::Ptr l = m_buffer->plainLine( cl );
while ( n > 0 && highlight()->isInWord( l->getChar( n-1 ), l->attribute( n-1 ) ) )
n--;
o = text( cl, n, cl, n + 1 );
s = o.upper();
}
break;
default:
break;
}
if ( s != o )
{
removeText( cl, n, cl, n+1 );
insertText( cl, n, s );
}
}
editEnd();
if ( ! selectionRestored )
v->setCursorPosition( cl, cc );
}
void KateDocument::joinLines( uint first, uint last )
{
// if ( first == last ) last += 1;
editStart();
int line( first );
while ( first < last )
{
// Normalize the whitespace in the joined lines by making sure there's
// always exactly one space between the joined lines
// This cannot be done in editUnwrapLine, because we do NOT want this
// behaviour when deleting from the start of a line, just when explicitly
// calling the join command
KateTextLine::Ptr l = m_buffer->line( line );
KateTextLine::Ptr tl = m_buffer->line( line + 1 );
if ( !l || !tl )
{
editEnd();
return;
}
int pos = tl->firstChar();
if ( pos >= 0 )
{
if (pos != 0)
editRemoveText( line + 1, 0, pos );
if ( !( l->length() == 0 || l->getChar( l->length() - 1 ).isSpace() ) )
editInsertText( line + 1, 0, " " );
}
else
{
// Just remove the whitespace and let Kate handle the rest
editRemoveText( line + 1, 0, tl->length() );
}
editUnWrapLine( line );
first++;
}
editEnd();
}
TQString KateDocument::getWord( const KateTextCursor& cursor ) {
int start, end, len;
KateTextLine::Ptr textLine = m_buffer->plainLine(cursor.line());
len = textLine->length();
start = end = cursor.col();
if (start > len) // Probably because of non-wrapping cursor mode.
return TQString("");
while (start > 0 && highlight()->isInWord(textLine->getChar(start - 1), textLine->attribute(start - 1))) start--;
while (end < len && highlight()->isInWord(textLine->getChar(end), textLine->attribute(end))) end++;
len = end - start;
return TQString(&textLine->text()[start], len);
}
void KateDocument::tagLines(int start, int end)
{
for (uint z = 0; z < m_views.count(); z++)
m_views.at(z)->tagLines (start, end, true);
}
void KateDocument::tagLines(KateTextCursor start, KateTextCursor end)
{
// May need to switch start/end cols if in block selection mode
if (blockSelectionMode() && start.col() > end.col()) {
int sc = start.col();
start.setCol(end.col());
end.setCol(sc);
}
for (uint z = 0; z < m_views.count(); z++)
m_views.at(z)->tagLines(start, end, true);
}
void KateDocument::repaintViews(bool paintOnlyDirty)
{
for (uint z = 0; z < m_views.count(); z++)
m_views.at(z)->repaintText(paintOnlyDirty);
}
void KateDocument::tagAll()
{
for (uint z = 0; z < m_views.count(); z++)
{
m_views.at(z)->tagAll();
m_views.at(z)->updateView (true);
}
}
uint KateDocument::configFlags ()
{
return config()->configFlags();
}
void KateDocument::setConfigFlags (uint flags)
{
config()->setConfigFlags(flags);
}
inline bool isStartBracket( const TQChar& c ) { return c == '{' || c == '[' || c == '('; }
inline bool isEndBracket ( const TQChar& c ) { return c == '}' || c == ']' || c == ')'; }
inline bool isBracket ( const TQChar& c ) { return isStartBracket( c ) || isEndBracket( c ); }
/*
Bracket matching uses the following algorithm:
If in overwrite mode, match the bracket currently underneath the cursor.
Otherwise, if the character to the right of the cursor is an starting bracket,
match it. Otherwise if the character to the left of the cursor is a
ending bracket, match it. Otherwise, if the the character to the left
of the cursor is an starting bracket, match it. Otherwise, if the character
to the right of the cursor is an ending bracket, match it. Otherwise, don't
match anything.
*/
void KateDocument::newBracketMark( const KateTextCursor& cursor, KateBracketRange& bm, int maxLines )
{
bm.setValid(false);
bm.start() = cursor;
if( !findMatchingBracket( bm.start(), bm.end(), maxLines ) )
return;
bm.setValid(true);
const int tw = config()->tabWidth();
const int indentStart = m_buffer->plainLine(bm.start().line())->indentDepth(tw);
const int indentEnd = m_buffer->plainLine(bm.end().line())->indentDepth(tw);
bm.setIndentMin(kMin(indentStart, indentEnd));
}
bool KateDocument::findMatchingBracket( KateTextCursor& start, KateTextCursor& end, int maxLines )
{
KateTextLine::Ptr textLine = m_buffer->plainLine( start.line() );
if( !textLine )
return false;
TQChar right = textLine->getChar( start.col() );
TQChar left = textLine->getChar( start.col() - 1 );
TQChar bracket;
if ( config()->configFlags() & cfOvr ) {
if( isBracket( right ) ) {
bracket = right;
} else {
return false;
}
} else if ( isStartBracket( right ) ) {
bracket = right;
} else if ( isEndBracket( left ) ) {
start.setCol(start.col() - 1);
bracket = left;
} else if ( isBracket( left ) ) {
start.setCol(start.col() - 1);
bracket = left;
} else if ( isBracket( right ) ) {
bracket = right;
} else {
return false;
}
TQChar opposite;
switch( bracket ) {
case '{': opposite = '}'; break;
case '}': opposite = '{'; break;
case '[': opposite = ']'; break;
case ']': opposite = '['; break;
case '(': opposite = ')'; break;
case ')': opposite = '('; break;
default: return false;
}
bool forward = isStartBracket( bracket );
int startAttr = textLine->attribute( start.col() );
uint count = 0;
int lines = 0;
end = start;
while( true ) {
/* Increment or decrement, check base cases */
if( forward ) {
end.setCol(end.col() + 1);
if( end.col() >= lineLength( end.line() ) ) {
if( end.line() >= (int)lastLine() )
return false;
end.setPos(end.line() + 1, 0);
textLine = m_buffer->plainLine( end.line() );
lines++;
}
} else {
end.setCol(end.col() - 1);
if( end.col() < 0 ) {
if( end.line() <= 0 )
return false;
end.setLine(end.line() - 1);
end.setCol(lineLength( end.line() ) - 1);
textLine = m_buffer->plainLine( end.line() );
lines++;
}
}
if ((maxLines != -1) && (lines > maxLines))
return false;
/* Easy way to skip comments */
if( textLine->attribute( end.col() ) != startAttr )
continue;
/* Check for match */
TQChar c = textLine->getChar( end.col() );
if( c == bracket ) {
count++;
} else if( c == opposite ) {
if( count == 0 )
return true;
count--;
}
}
}
void KateDocument::guiActivateEvent( KParts::GUIActivateEvent *ev )
{
KParts::ReadWritePart::guiActivateEvent( ev );
if ( ev->activated() )
emit selectionChanged();
}
void KateDocument::setDocName (TQString name )
{
if ( name == m_docName )
return;
if ( !name.isEmpty() )
{
// TODO check for similarly named documents
m_docName = name;
updateFileType (KateFactory::self()->fileTypeManager()->fileType (this));
emit nameChanged((Kate::Document *) this);
return;
}
// if the name is set, and starts with FILENAME, it should not be changed!
if ( ! url().isEmpty() && m_docName.startsWith( url().filename() ) ) return;
int count = -1;
for (uint z=0; z < KateFactory::self()->documents()->count(); z++)
{
if ( (KateFactory::self()->documents()->at(z) != this) && (KateFactory::self()->documents()->at(z)->url().filename() == url().filename()) )
if ( KateFactory::self()->documents()->at(z)->m_docNameNumber > count )
count = KateFactory::self()->documents()->at(z)->m_docNameNumber;
}
m_docNameNumber = count + 1;
m_docName = url().filename();
if (m_docName.isEmpty())
m_docName = i18n ("Untitled");
if (m_docNameNumber > 0)
m_docName = TQString(m_docName + " (%1)").arg(m_docNameNumber+1);
updateFileType (KateFactory::self()->fileTypeManager()->fileType (this));
emit nameChanged ((Kate::Document *) this);
}
void KateDocument::slotModifiedOnDisk( Kate::View * /*v*/ )
{
if ( m_isasking < 0 )
{
m_isasking = 0;
return;
}
if ( !s_fileChangedDialogsActivated || m_isasking )
return;
if (m_modOnHd && !url().isEmpty())
{
m_isasking = 1;
KateModOnHdPrompt p( this, m_modOnHdReason, reasonedMOHString(), widget() );
switch ( p.exec() )
{
case KateModOnHdPrompt::Save:
{
m_modOnHd = false;
KEncodingFileDialog::Result res=KEncodingFileDialog::getSaveURLAndEncoding(config()->encoding(),
url().url(),TQString::null,widget(),i18n("Save File"));
kdDebug(13020)<<"got "<<res.URLs.count()<<" URLs"<<endl;
if( ! res.URLs.isEmpty() && ! res.URLs.first().isEmpty() && checkOverwrite( res.URLs.first() ) )
{
setEncoding( res.encoding );
if( ! saveAs( res.URLs.first() ) )
{
KMessageBox::error( widget(), i18n("Save failed") );
m_modOnHd = true;
}
else
emit modifiedOnDisc( this, false, 0 );
}
else // the save as dialog was cancelled, we are still modified on disk
{
m_modOnHd = true;
}
m_isasking = 0;
break;
}
case KateModOnHdPrompt::Reload:
m_modOnHd = false;
emit modifiedOnDisc( this, false, 0 );
reloadFile();
m_isasking = 0;
break;
case KateModOnHdPrompt::Ignore:
m_modOnHd = false;
emit modifiedOnDisc( this, false, 0 );
m_isasking = 0;
break;
case KateModOnHdPrompt::Overwrite:
m_modOnHd = false;
emit modifiedOnDisc( this, false, 0 );
m_isasking = 0;
save();
break;
default: // cancel: ignore next focus event
m_isasking = -1;
}
}
}
void KateDocument::setModifiedOnDisk( int reason )
{
m_modOnHdReason = reason;
m_modOnHd = (reason > 0);
emit modifiedOnDisc( this, (reason > 0), reason );
}
class KateDocumentTmpMark
{
public:
TQString line;
KTextEditor::Mark mark;
};
void KateDocument::reloadFile()
{
if ( !url().isEmpty() )
{
if (m_modOnHd && s_fileChangedDialogsActivated)
{
int i = KMessageBox::warningYesNoCancel
(0, reasonedMOHString() + "\n\n" + i18n("What do you want to do?"),
i18n("File Was Changed on Disk"), i18n("&Reload File"), i18n("&Ignore Changes"));
if ( i != KMessageBox::Yes)
{
if (i == KMessageBox::No)
{
m_modOnHd = false;
m_modOnHdReason = 0;
emit modifiedOnDisc (this, m_modOnHd, 0);
}
return;
}
}
TQValueList<KateDocumentTmpMark> tmp;
for( TQIntDictIterator<KTextEditor::Mark> it( m_marks ); it.current(); ++it )
{
KateDocumentTmpMark m;
m.line = textLine (it.current()->line);
m.mark = *it.current();
tmp.append (m);
}
uint mode = hlMode ();
bool byUser = hlSetByUser;
m_storedVariables.clear();
m_reloading = true;
TQValueList<int> lines, cols;
for ( uint i=0; i < m_views.count(); i++ )
{
lines.append( m_views.at( i )->cursorLine() );
cols.append( m_views.at( i )->cursorColumn() );
}
KateDocument::openURL( url() );
for ( uint i=0; i < m_views.count(); i++ )
m_views.at( i )->setCursorPositionInternal( lines[ i ], cols[ i ], m_config->tabWidth(), false );
m_reloading = false;
for ( TQValueList<int>::size_type z=0; z < tmp.size(); z++ )
{
if (z < numLines())
{
if (textLine(tmp[z].mark.line) == tmp[z].line)
setMark (tmp[z].mark.line, tmp[z].mark.type);
}
}
if (byUser)
setHlMode (mode);
}
}
void KateDocument::flush ()
{
closeURL ();
}
void KateDocument::setWordWrap (bool on)
{
config()->setWordWrap (on);
}
bool KateDocument::wordWrap ()
{
return config()->wordWrap ();
}
void KateDocument::setWordWrapAt (uint col)
{
config()->setWordWrapAt (col);
}
unsigned int KateDocument::wordWrapAt ()
{
return config()->wordWrapAt ();
}
void KateDocument::applyWordWrap ()
{
// dummy to make the API happy
}
void KateDocument::setPageUpDownMovesCursor (bool on)
{
config()->setPageUpDownMovesCursor (on);
}
bool KateDocument::pageUpDownMovesCursor ()
{
return config()->pageUpDownMovesCursor ();
}
void KateDocument::dumpRegionTree()
{
m_buffer->foldingTree()->debugDump();
}
//END
//BEGIN KTextEditor::CursorInterface stuff
KTextEditor::Cursor *KateDocument::createCursor ( )
{
return new KateSuperCursor (this, false, 0, 0, this);
}
void KateDocument::tagArbitraryLines(KateView* view, KateSuperRange* range)
{
if (view)
view->tagLines(range->start(), range->end());
else
tagLines(range->start(), range->end());
}
void KateDocument::lineInfo (KateLineInfo *info, unsigned int line)
{
m_buffer->lineInfo(info,line);
}
KateCodeFoldingTree *KateDocument::foldingTree ()
{
return m_buffer->foldingTree();
}
void KateDocument::setEncoding (const TQString &e)
{
if ( m_encodingSticky )
return;
TQString ce = m_config->encoding().lower();
if ( e.lower() == ce )
return;
m_config->setEncoding( e );
if ( ! m_loading )
reloadFile();
}
TQString KateDocument::encoding() const
{
return m_config->encoding();
}
void KateDocument::updateConfig ()
{
emit undoChanged ();
tagAll();
for (KateView * view = m_views.first(); view != 0L; view = m_views.next() )
{
view->updateDocumentConfig ();
}
// switch indenter if needed
if (m_indenter->modeNumber() != m_config->indentationMode())
{
delete m_indenter;
m_indenter = KateAutoIndent::createIndenter ( this, m_config->indentationMode() );
}
m_indenter->updateConfig();
m_buffer->setTabWidth (config()->tabWidth());
// plugins
for (uint i=0; i<KateFactory::self()->plugins().count(); i++)
{
if (config()->plugin (i))
loadPlugin (i);
else
unloadPlugin (i);
}
}
//BEGIN Variable reader
// "local variable" feature by anders, 2003
/* TODO
add config options (how many lines to read, on/off)
add interface for plugins/apps to set/get variables
add view stuff
*/
TQRegExp KateDocument::kvLine = TQRegExp("kate:(.*)");
TQRegExp KateDocument::kvLineWildcard = TQRegExp("kate-wildcard\\((.*)\\):(.*)");
TQRegExp KateDocument::kvLineMime = TQRegExp("kate-mimetype\\((.*)\\):(.*)");
TQRegExp KateDocument::kvVar = TQRegExp("([\\w\\-]+)\\s+([^;]+)");
void KateDocument::readVariables(bool onlyViewAndRenderer)
{
if (!onlyViewAndRenderer)
m_config->configStart();
// views!
KateView *v;
for (v = m_views.first(); v != 0L; v= m_views.next() )
{
v->config()->configStart();
v->renderer()->config()->configStart();
}
// read a number of lines in the top/bottom of the document
for (uint i=0; i < kMin( 9U, numLines() ); ++i )
{
readVariableLine( textLine( i ), onlyViewAndRenderer );
}
if ( numLines() > 10 )
{
for ( uint i = kMax(10U, numLines() - 10); i < numLines(); ++i )
{
readVariableLine( textLine( i ), onlyViewAndRenderer );
}
}
if (!onlyViewAndRenderer)
m_config->configEnd();
for (v = m_views.first(); v != 0L; v= m_views.next() )
{
v->config()->configEnd();
v->renderer()->config()->configEnd();
}
}
void KateDocument::readVariableLine( TQString t, bool onlyViewAndRenderer )
{
// simple check first, no regex
// no kate inside, no vars, simple...
if (t.find("kate") < 0)
return;
// found vars, if any
TQString s;
if ( kvLine.search( t ) > -1 )
{
s = kvLine.cap(1);
kdDebug (13020) << "normal variable line kate: matched: " << s << endl;
}
else if (kvLineWildcard.search( t ) > -1) // regex given
{
TQStringList wildcards (TQStringList::split(';', kvLineWildcard.cap(1)));
TQString nameOfFile = url().fileName();
bool found = false;
for (TQStringList::size_type i = 0; !found && i < wildcards.size(); ++i)
{
TQRegExp wildcard (wildcards[i], true/*Qt::CaseSensitive*/, true/*TQRegExp::Wildcard*/);
found = wildcard.exactMatch (nameOfFile);
}
// nothing usable found...
if (!found)
return;
s = kvLineWildcard.cap(2);
kdDebug (13020) << "guarded variable line kate-wildcard: matched: " << s << endl;
}
else if (kvLineMime.search( t ) > -1) // mime-type given
{
TQStringList types (TQStringList::split(';', kvLineMime.cap(1)));
// no matching type found
if (!types.contains (mimeType ()))
return;
s = kvLineMime.cap(2);
kdDebug (13020) << "guarded variable line kate-mimetype: matched: " << s << endl;
}
else // nothing found
{
return;
}
TQStringList vvl; // view variable names
vvl << "dynamic-word-wrap" << "dynamic-word-wrap-indicators"
<< "line-numbers" << "icon-border" << "folding-markers"
<< "bookmark-sorting" << "auto-center-lines"
<< "icon-bar-color"
// renderer
<< "background-color" << "selection-color"
<< "current-line-color" << "bracket-highlight-color"
<< "word-wrap-marker-color"
<< "font" << "font-size" << "scheme";
int p( 0 );
TQString var, val;
while ( (p = kvVar.search( s, p )) > -1 )
{
p += kvVar.matchedLength();
var = kvVar.cap( 1 );
val = TQString(kvVar.cap( 2 )).stripWhiteSpace();
bool state; // store booleans here
int n; // store ints here
// only apply view & renderer config stuff
if (onlyViewAndRenderer)
{
if ( vvl.contains( var ) ) // FIXME define above
setViewVariable( var, val );
}
else
{
// BOOL SETTINGS
if ( var == "word-wrap" && checkBoolValue( val, &state ) )
setWordWrap( state ); // ??? FIXME CHECK
else if ( var == "block-selection" && checkBoolValue( val, &state ) )
setBlockSelectionMode( state );
// KateConfig::configFlags
// FIXME should this be optimized to only a few calls? how?
else if ( var == "backspace-indents" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfBackspaceIndents, state );
else if ( var == "replace-tabs" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfReplaceTabsDyn, state );
else if ( var == "remove-trailing-space" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfRemoveTrailingDyn, state );
else if ( var == "wrap-cursor" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfWrapCursor, state );
else if ( var == "auto-brackets" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfAutoBrackets, state );
else if ( var == "overwrite-mode" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfOvr, state );
else if ( var == "keep-indent-profile" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfKeepIndentProfile, state );
else if ( var == "keep-extra-spaces" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfKeepExtraSpaces, state );
else if ( var == "tab-indents" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfTabIndents, state );
else if ( var == "show-tabs" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfShowTabs, state );
else if ( var == "space-indent" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfSpaceIndent, state );
else if ( var == "smart-home" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfSmartHome, state );
else if ( var == "replace-trailing-space-save" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfRemoveSpaces, state );
else if ( var == "auto-insert-doxygen" && checkBoolValue( val, &state) )
m_config->setConfigFlags( KateDocumentConfig::cfDoxygenAutoTyping, state);
else if ( var == "mixed-indent" && checkBoolValue( val, &state ) )
m_config->setConfigFlags( KateDocumentConfig::cfMixedIndent, state );
// INTEGER SETTINGS
else if ( var == "tab-width" && checkIntValue( val, &n ) )
m_config->setTabWidth( n );
else if ( var == "indent-width" && checkIntValue( val, &n ) )
m_config->setIndentationWidth( n );
else if ( var == "indent-mode" )
{
if ( checkIntValue( val, &n ) )
m_config->setIndentationMode( n );
else
m_config->setIndentationMode( KateAutoIndent::modeNumber( val) );
}
else if ( var == "word-wrap-column" && checkIntValue( val, &n ) && n > 0 ) // uint, but hard word wrap at 0 will be no fun ;)
m_config->setWordWrapAt( n );
else if ( var == "undo-steps" && checkIntValue( val, &n ) && n >= 0 )
setUndoSteps( n );
// STRING SETTINGS
else if ( var == "eol" || var == "end-of-line" )
{
TQStringList l;
l << "unix" << "dos" << "mac";
if ( (n = l.findIndex( val.lower() )) != -1 )
m_config->setEol( n );
}
else if ( var == "encoding" )
m_config->setEncoding( val );
else if ( var == "syntax" || var == "hl" )
{
for ( uint i=0; i < hlModeCount(); i++ )
{
if ( hlModeName( i ).lower() == val.lower() )
{
setHlMode( i );
break;
}
}
}
// VIEW SETTINGS
else if ( vvl.contains( var ) )
setViewVariable( var, val );
else
{
m_storedVariables.insert( var, val );
emit variableChanged( var, val );
}
}
}
}
void KateDocument::setViewVariable( TQString var, TQString val )
{
KateView *v;
bool state;
int n;
TQColor c;
for (v = m_views.first(); v != 0L; v= m_views.next() )
{
if ( var == "dynamic-word-wrap" && checkBoolValue( val, &state ) )
v->config()->setDynWordWrap( state );
else if ( var == "persistent-selection" && checkBoolValue( val, &state ) )
v->config()->setPersistentSelection( state );
//else if ( var = "dynamic-word-wrap-indicators" )
else if ( var == "line-numbers" && checkBoolValue( val, &state ) )
v->config()->setLineNumbers( state );
else if (var == "icon-border" && checkBoolValue( val, &state ) )
v->config()->setIconBar( state );
else if (var == "folding-markers" && checkBoolValue( val, &state ) )
v->config()->setFoldingBar( state );
else if ( var == "auto-center-lines" && checkIntValue( val, &n ) )
v->config()->setAutoCenterLines( n ); // FIXME uint, > N ??
else if ( var == "icon-bar-color" && checkColorValue( val, c ) )
v->renderer()->config()->setIconBarColor( c );
// RENDERER
else if ( var == "background-color" && checkColorValue( val, c ) )
v->renderer()->config()->setBackgroundColor( c );
else if ( var == "selection-color" && checkColorValue( val, c ) )
v->renderer()->config()->setSelectionColor( c );
else if ( var == "current-line-color" && checkColorValue( val, c ) )
v->renderer()->config()->setHighlightedLineColor( c );
else if ( var == "bracket-highlight-color" && checkColorValue( val, c ) )
v->renderer()->config()->setHighlightedBracketColor( c );
else if ( var == "word-wrap-marker-color" && checkColorValue( val, c ) )
v->renderer()->config()->setWordWrapMarkerColor( c );
else if ( var == "font" || ( var == "font-size" && checkIntValue( val, &n ) ) )
{
TQFont _f( *v->renderer()->config()->font( ) );
if ( var == "font" )
{
_f.setFamily( val );
_f.setFixedPitch( TQFont( val ).fixedPitch() );
}
else
_f.setPointSize( n );
v->renderer()->config()->setFont( _f );
}
else if ( var == "scheme" )
{
v->renderer()->config()->setSchema( KateFactory::self()->schemaManager()->number( val ) );
}
}
}
bool KateDocument::checkBoolValue( TQString val, bool *result )
{
val = val.stripWhiteSpace().lower();
TQStringList l;
l << "1" << "on" << "true";
if ( l.contains( val ) )
{
*result = true;
return true;
}
l.clear();
l << "0" << "off" << "false";
if ( l.contains( val ) )
{
*result = false;
return true;
}
return false;
}
bool KateDocument::checkIntValue( TQString val, int *result )
{
bool ret( false );
*result = val.toInt( &ret );
return ret;
}
bool KateDocument::checkColorValue( TQString val, TQColor &c )
{
c.setNamedColor( val );
return c.isValid();
}
// KTextEditor::variable
TQString KateDocument::variable( const TQString &name ) const
{
if ( m_storedVariables.contains( name ) )
return m_storedVariables[ name ];
return "";
}
//END
void KateDocument::slotModOnHdDirty (const TQString &path)
{
if ((path == m_dirWatchFile) && (!m_modOnHd || m_modOnHdReason != 1))
{
// compare md5 with the one we have (if we have one)
if ( ! m_digest.isEmpty() )
{
TQCString tmp;
if ( createDigest( tmp ) && tmp == m_digest )
return;
}
m_modOnHd = true;
m_modOnHdReason = 1;
// reenable dialog if not running atm
if (m_isasking == -1)
m_isasking = false;
emit modifiedOnDisc (this, m_modOnHd, m_modOnHdReason);
}
}
void KateDocument::slotModOnHdCreated (const TQString &path)
{
if ((path == m_dirWatchFile) && (!m_modOnHd || m_modOnHdReason != 2))
{
m_modOnHd = true;
m_modOnHdReason = 2;
// reenable dialog if not running atm
if (m_isasking == -1)
m_isasking = false;
emit modifiedOnDisc (this, m_modOnHd, m_modOnHdReason);
}
}
void KateDocument::slotModOnHdDeleted (const TQString &path)
{
if ((path == m_dirWatchFile) && (!m_modOnHd || m_modOnHdReason != 3))
{
m_modOnHd = true;
m_modOnHdReason = 3;
// reenable dialog if not running atm
if (m_isasking == -1)
m_isasking = false;
emit modifiedOnDisc (this, m_modOnHd, m_modOnHdReason);
}
}
bool KateDocument::createDigest( TQCString &result )
{
bool ret = false;
result = "";
if ( url().isLocalFile() )
{
TQFile f ( url().path() );
if ( f.open( IO_ReadOnly) )
{
KMD5 md5;
ret = md5.update( TQT_TQIODEVICE_OBJECT(f) );
md5.hexDigest( result );
f.close();
ret = true;
}
}
return ret;
}
TQString KateDocument::reasonedMOHString() const
{
switch( m_modOnHdReason )
{
case 1:
return i18n("The file '%1' was modified by another program.").arg( url().prettyURL() );
break;
case 2:
return i18n("The file '%1' was created by another program.").arg( url().prettyURL() );
break;
case 3:
return i18n("The file '%1' was deleted by another program.").arg( url().prettyURL() );
break;
default:
return TQString();
}
}
void KateDocument::removeTrailingSpace( uint line )
{
// remove trailing spaces from left line if required
if ( config()->configFlags() & KateDocumentConfig::cfRemoveTrailingDyn )
{
KateTextLine::Ptr ln = kateTextLine( line );
if ( ! ln ) return;
if ( line == activeView()->cursorLine()
&& activeView()->cursorColumnReal() >= (uint)kMax(0,ln->lastChar()) )
return;
if ( ln->length() )
{
uint p = ln->lastChar() + 1;
uint l = ln->length() - p;
if ( l )
editRemoveText( line, p, l);
}
}
}
void KateDocument::updateFileType (int newType, bool user)
{
if (user || !m_fileTypeSetByUser)
{
const KateFileType *t = 0;
if ((newType == -1) || (t = KateFactory::self()->fileTypeManager()->fileType (newType)))
{
m_fileType = newType;
if (t)
{
m_config->configStart();
// views!
KateView *v;
for (v = m_views.first(); v != 0L; v= m_views.next() )
{
v->config()->configStart();
v->renderer()->config()->configStart();
}
readVariableLine( t->varLine );
m_config->configEnd();
for (v = m_views.first(); v != 0L; v= m_views.next() )
{
v->config()->configEnd();
v->renderer()->config()->configEnd();
}
}
}
}
}
uint KateDocument::documentNumber () const
{
return KTextEditor::Document::documentNumber ();
}
long KateDocument::documentListPosition () const
{
return KTextEditor::Document::documentListPosition ();
}
void KateDocument::setDocumentListPosition (long pos)
{
KTextEditor::Document::setDocumentListPosition (pos);
}
void KateDocument::slotQueryClose_save(bool *handled, bool* abortClosing) {
*handled=true;
*abortClosing=true;
if (m_url.isEmpty())
{
KEncodingFileDialog::Result res=KEncodingFileDialog::getSaveURLAndEncoding(config()->encoding(),
TQString::null,TQString::null,0,i18n("Save File"));
if( res.URLs.isEmpty() || !checkOverwrite( res.URLs.first() ) ) {
*abortClosing=true;
return;
}
setEncoding( res.encoding );
saveAs( res.URLs.first() );
*abortClosing=false;
}
else
{
save();
*abortClosing=false;
}
}
bool KateDocument::checkOverwrite( KURL u )
{
if( !u.isLocalFile() )
return true;
TQFileInfo info( u.path() );
if( !info.exists() )
return true;
return KMessageBox::Cancel != KMessageBox::warningContinueCancel( 0,
i18n( "A file named \"%1\" already exists. "
"Are you sure you want to overwrite it?" ).arg( info.fileName() ),
i18n( "Overwrite File?" ),
i18n( "&Overwrite" ) );
}
void KateDocument::setDefaultEncoding (const TQString &encoding)
{
s_defaultEncoding = encoding;
}
//BEGIN KTextEditor::TemplateInterface
bool KateDocument::insertTemplateTextImplementation ( uint line, uint column, const TQString &templateString, const TQMap<TQString,TQString> &initialValues, TQWidget *) {
return (new KateTemplateHandler(this,line,column,templateString,initialValues))->initOk();
}
void KateDocument::testTemplateCode() {
int col=activeView()->cursorColumn();
int line=activeView()->cursorLine();
insertTemplateText(line,col,"for ${index} \\${NOPLACEHOLDER} ${index} ${blah} ${fullname} \\$${Placeholder} \\${${PLACEHOLDER2}}\n next line:${ANOTHERPLACEHOLDER} $${DOLLARBEFOREPLACEHOLDER} {NOTHING} {\n${cursor}\n}",TQMap<TQString,TQString>());
}
bool KateDocument::invokeTabInterceptor(KKey key) {
if (m_tabInterceptor) return (*m_tabInterceptor)(key);
return false;
}
bool KateDocument::setTabInterceptor(KateKeyInterceptorFunctor *interceptor) {
if (m_tabInterceptor) return false;
m_tabInterceptor=interceptor;
return true;
}
bool KateDocument::removeTabInterceptor(KateKeyInterceptorFunctor *interceptor) {
if (m_tabInterceptor!=interceptor) return false;
m_tabInterceptor=0;
return true;
}
//END KTextEditor::TemplateInterface
//BEGIN DEPRECATED STUFF
bool KateDocument::setSelection ( uint startLine, uint startCol, uint endLine, uint endCol )
{ if (m_activeView) return m_activeView->setSelection (startLine, startCol, endLine, endCol); return false; }
bool KateDocument::clearSelection ()
{ if (m_activeView) return m_activeView->clearSelection(); return false; }
bool KateDocument::hasSelection () const
{ if (m_activeView) return m_activeView->hasSelection (); return false; }
TQString KateDocument::selection () const
{ if (m_activeView) return m_activeView->selection (); return TQString(""); }
bool KateDocument::removeSelectedText ()
{ if (m_activeView) return m_activeView->removeSelectedText (); return false; }
bool KateDocument::selectAll()
{ if (m_activeView) return m_activeView->selectAll (); return false; }
int KateDocument::selStartLine()
{ if (m_activeView) return m_activeView->selStartLine (); return 0; }
int KateDocument::selStartCol()
{ if (m_activeView) return m_activeView->selStartCol (); return 0; }
int KateDocument::selEndLine()
{ if (m_activeView) return m_activeView->selEndLine (); return 0; }
int KateDocument::selEndCol()
{ if (m_activeView) return m_activeView->selEndCol (); return 0; }
bool KateDocument::blockSelectionMode ()
{ if (m_activeView) return m_activeView->blockSelectionMode (); return false; }
bool KateDocument::setBlockSelectionMode (bool on)
{ if (m_activeView) return m_activeView->setBlockSelectionMode (on); return false; }
bool KateDocument::toggleBlockSelectionMode ()
{ if (m_activeView) return m_activeView->toggleBlockSelectionMode (); return false; }
//END DEPRECATED
//END DEPRECATED STUFF
// kate: space-indent on; indent-width 2; replace-tabs on;
|