~mhall119/ubuntu/precise/geany/add_quicklist

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
/*
 *      editor.c - this file is part of Geany, a fast and lightweight IDE
 *
 *      Copyright 2005-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
 *      Copyright 2006-2010 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
 *      Copyright 2009-2010 Frank Lanitz <frank(at)frank(dot)uvena(dot)de>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: editor.c 5495 2010-12-22 13:44:41Z ntrel $
 */

/**
 * @file editor.h
 * Editor-related functions for @ref GeanyEditor.
 * Geany uses the Scintilla editing widget, and this file is mostly built around
 * Scintilla's functionality.
 * @see sciwrappers.h.
 */
/* Callbacks for the Scintilla widget (ScintillaObject).
 * Most important is the sci-notify callback, handled in on_editor_notification().
 * This includes auto-indentation, comments, auto-completion, calltips, etc.
 * Also some general Scintilla-related functions.
 */


#include <ctype.h>
#include <string.h>

#include <gdk/gdkkeysyms.h>

#include "SciLexer.h"
#include "geany.h"

#ifdef HAVE_REGEX_H
# include <regex.h>
#else
# include "gnuregex.h"
#endif

#include "support.h"
#include "editor.h"
#include "document.h"
#include "documentprivate.h"
#include "filetypes.h"
#include "filetypesprivate.h"
#include "sciwrappers.h"
#include "ui_utils.h"
#include "utils.h"
#include "dialogs.h"
#include "symbols.h"
#include "callbacks.h"
#include "templates.h"
#include "keybindings.h"
#include "project.h"
#include "projectprivate.h"
#include "main.h"
#include "highlighting.h"


/* Note: use sciwrappers.h instead where possible.
 * Do not use SSM in files unrelated to scintilla. */
#define SSM(s, m, w, l) scintilla_send_message(s, m, w, l)


static GHashTable *snippet_hash = NULL;
static GQueue *snippet_offsets = NULL;
static gint snippet_cursor_insert_pos;
static GtkAccelGroup *snippet_accel_group = NULL;

/* holds word under the mouse or keyboard cursor */
static gchar current_word[GEANY_MAX_WORD_LENGTH];

/* Initialised in keyfile.c. */
GeanyEditorPrefs editor_prefs;

EditorInfo editor_info = {current_word, -1};

static struct
{
	gchar *text;
	gboolean set;
	gchar *last_word;
	guint tag_index;
	gint pos;
	ScintillaObject *sci;
} calltip = {NULL, FALSE, NULL, 0, 0, NULL};

static gchar indent[100];


static void on_new_line_added(GeanyEditor *editor);
static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
static void insert_indent_after_line(GeanyEditor *editor, gint line);
static void auto_multiline(GeanyEditor *editor, gint pos);
static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
static void close_block(GeanyEditor *editor, gint pos);
static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
		const gchar *wc, gboolean stem);
static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name);
static gssize snippets_make_replacements(GeanyEditor *editor, GString *pattern,
		gsize indent_size);


void editor_snippets_free(void)
{
	g_hash_table_destroy(snippet_hash);
	g_queue_free(snippet_offsets);
	gtk_window_remove_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
}


static void snippets_load(GKeyFile *sysconfig, GKeyFile *userconfig)
{
	gsize i, j, len = 0, len_keys = 0;
	gchar **groups_user, **groups_sys;
	gchar **keys_user, **keys_sys;
	gchar *value;
	GHashTable *tmp;

	/* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
	snippet_hash =
		g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);

	/* first read all globally defined auto completions */
	groups_sys = g_key_file_get_groups(sysconfig, &len);
	for (i = 0; i < len; i++)
	{
		if (strcmp(groups_sys[i], "Keybindings") == 0)
			continue;
		keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
		/* create new hash table for the read section (=> filetype) */
		tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
		g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);

		for (j = 0; j < len_keys; j++)
		{
			g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
						utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
		}
		g_strfreev(keys_sys);
	}
	g_strfreev(groups_sys);

	/* now read defined completions in user's configuration directory and add / replace them */
	groups_user = g_key_file_get_groups(userconfig, &len);
	for (i = 0; i < len; i++)
	{
		if (strcmp(groups_user[i], "Keybindings") == 0)
			continue;
		keys_user = g_key_file_get_keys(userconfig, groups_user[i], &len_keys, NULL);

		tmp = g_hash_table_lookup(snippet_hash, groups_user[i]);
		if (tmp == NULL)
		{	/* new key found, create hash table */
			tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
			g_hash_table_insert(snippet_hash, g_strdup(groups_user[i]), tmp);
		}
		for (j = 0; j < len_keys; j++)
		{
			value = g_hash_table_lookup(tmp, keys_user[j]);
			if (value == NULL)
			{	/* value = NULL means the key doesn't yet exist, so insert */
				g_hash_table_insert(tmp, g_strdup(keys_user[j]),
						utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
			}
			else
			{	/* old key and value will be freed by destroy function (g_free) */
				g_hash_table_replace(tmp, g_strdup(keys_user[j]),
						utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
			}
		}
		g_strfreev(keys_user);
	}
	g_strfreev(groups_user);
}


static void on_snippet_keybinding_activate(gchar *key)
{
	GeanyDocument *doc = document_get_current();
	const gchar *s;
	GHashTable *specials;

	if (!doc || !GTK_WIDGET_HAS_FOCUS(doc->editor->sci))
		return;

	s = snippets_find_completion_by_name(doc->file_type->name, key);
	if (!s) /* allow user to specify keybindings for "special" snippets */
	{
		specials = g_hash_table_lookup(snippet_hash, "Special");
		if (G_LIKELY(specials != NULL))
			s = g_hash_table_lookup(specials, key);
	}
	if (!s)
	{
		utils_beep();
		return;
	}

	editor_insert_snippet(doc->editor, sci_get_current_position(doc->editor->sci), s);
	sci_scroll_caret(doc->editor->sci);
}


static void add_kb(GKeyFile *keyfile, const gchar *group, gchar **keys)
{
	gsize i;

	if (!keys)
		return;
	for (i = 0; i < g_strv_length(keys); i++)
	{
		guint key;
		GdkModifierType mods;
		gchar *accel_string = g_key_file_get_value(keyfile, group, keys[i], NULL);

		gtk_accelerator_parse(accel_string, &key, &mods);
		g_free(accel_string);

		if (key == 0 && mods == 0)
		{
			g_warning("Can not parse accelerator \"%s\" from user snippets.conf", accel_string);
			continue;
		}
		gtk_accel_group_connect(snippet_accel_group, key, mods, 0,
			g_cclosure_new_swap((GCallback)on_snippet_keybinding_activate,
				g_strdup(keys[i]), (GClosureNotify)g_free));
	}
}


static void load_kb(GKeyFile *sysconfig, GKeyFile *userconfig)
{
	const gchar kb_group[] = "Keybindings";
	gchar **keys = g_key_file_get_keys(userconfig, kb_group, NULL, NULL);
	gchar **ptr;

	/* remove overridden keys from system keyfile */
	foreach_strv(ptr, keys)
		g_key_file_remove_key(sysconfig, kb_group, *ptr, NULL);

	add_kb(userconfig, kb_group, keys);
	g_strfreev(keys);

	keys = g_key_file_get_keys(sysconfig, kb_group, NULL, NULL);
	add_kb(sysconfig, kb_group, keys);
	g_strfreev(keys);
}


void editor_snippets_init(void)
{
	gchar *sysconfigfile, *userconfigfile;
	GKeyFile *sysconfig = g_key_file_new();
	GKeyFile *userconfig = g_key_file_new();

	snippet_offsets = g_queue_new();

	sysconfigfile = g_strconcat(app->datadir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
	userconfigfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);

	/* check for old autocomplete.conf files (backwards compatibility) */
	if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR))
		setptr(userconfigfile,
			g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "autocomplete.conf", NULL));

	/* load the actual config files */
	g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
	g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);

	snippets_load(sysconfig, userconfig);

	/* setup snippet keybindings */
	snippet_accel_group = gtk_accel_group_new();
	gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
	load_kb(sysconfig, userconfig);

	g_free(sysconfigfile);
	g_free(userconfigfile);
	g_key_file_free(sysconfig);
	g_key_file_free(userconfig);
}


static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
											 gpointer data)
{
	GeanyEditor *editor = data;
	GeanyDocument *doc = editor->document;

	/* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
	 * fake event to show the editor menu triggered by a key event where we want to use the
	 * text cursor position. */
	if (event->x > 0.0 && event->y > 0.0)
		editor_info.click_pos = sci_get_position_from_xy(editor->sci,
			(gint)event->x, (gint)event->y, FALSE);
	else
		editor_info.click_pos = sci_get_current_position(editor->sci);

	if (event->button == 1)
	{
		guint state = event->state & gtk_accelerator_get_default_mod_mask();

		if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
		{
			gint ss = sci_get_selection_start(editor->sci);
			sci_set_selection_end(editor->sci, ss);
		}
		if (event->type == GDK_BUTTON_PRESS && state == GDK_CONTROL_MASK)
		{
			sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);

			editor_find_current_word(editor, editor_info.click_pos,
				current_word, sizeof current_word, NULL);
			if (*current_word)
				return symbols_goto_tag(current_word, TRUE);
			else
				keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
			return TRUE;
		}
		return document_check_disk_status(doc, FALSE);
	}

	/* calls the edit popup menu in the editor */
	if (event->button == 3)
	{
		gboolean can_goto;

		editor_find_current_word(editor, editor_info.click_pos,
			current_word, sizeof current_word, NULL);

		can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
		ui_update_popup_goto_items(can_goto);
		ui_update_popup_copy_items(doc);
		ui_update_insert_include_item(doc, 0);

		g_signal_emit_by_name(geany_object, "update-editor-menu",
			current_word, editor_info.click_pos, doc);

		gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
			NULL, NULL, NULL, NULL, event->button, event->time);

		return TRUE;
	}
	return FALSE;
}


static gboolean is_style_php(gint style)
{
	if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
		style == SCE_HPHP_COMPLEX_VARIABLE)
	{
		return TRUE;
	}

	return FALSE;
}


static gint editor_get_long_line_type(void)
{
	if (app->project)
		switch (app->project->long_line_behaviour)
		{
			case 0: /* marker disabled */
				return 2;
			case 1: /* use global settings */
				break;
			case 2: /* custom (enabled) */
				return editor_prefs.long_line_type;
		}

	if (!editor_prefs.long_line_enabled)
		return 2;
	else
		return editor_prefs.long_line_type;
}


static gint editor_get_long_line_column(void)
{
	if (app->project && app->project->long_line_behaviour != 1 /* use global settings */)
		return app->project->long_line_column;
	else
		return editor_prefs.long_line_column;
}


static const GeanyEditorPrefs *
get_default_prefs(void)
{
	static GeanyEditorPrefs eprefs;

	eprefs = editor_prefs;

	/* project overrides */
	eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(NULL);
	eprefs.long_line_type = editor_get_long_line_type();
	eprefs.long_line_column = editor_get_long_line_column();
	return &eprefs;
}


/* Gets the prefs for the editor.
 * Prefs can be different according to project or document.
 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
 * settings may have changed, or if this function has been called for a different editor.
 * @param editor The editor, or @c NULL to get the default prefs.
 * @return The prefs. */
const GeanyEditorPrefs *editor_get_prefs(GeanyEditor *editor)
{
	static GeanyEditorPrefs eprefs;
	const GeanyEditorPrefs *dprefs = get_default_prefs();

	/* Return the address of the default prefs to allow returning default and editor
	 * pref pointers without invalidating the contents of either. */
	if (editor == NULL)
		return dprefs;

	eprefs = *dprefs;
	eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(editor);
	/* add other editor & document overrides as needed */
	return &eprefs;
}


void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
{
	ScintillaObject *sci;

	g_return_if_fail(editor != NULL);

	sci = editor->sci;

	sci_toggle_fold(sci, line);

	/* extra toggling of child fold points
	 * use when editor_prefs.unfold_all_children is set and Shift is NOT pressed or when
	 * editor_prefs.unfold_all_children is NOT set but Shift is pressed */
	if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
		(! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
	{
		gint last_line = SSM(sci, SCI_GETLASTCHILD, line, -1);
		gint i;

		if (sci_get_line_is_visible(sci, line + 1))
		{	/* unfold all children of the current fold point */
			for (i = line; i < last_line; i++)
			{
				if (! sci_get_line_is_visible(sci, i))
				{
					sci_toggle_fold(sci, sci_get_fold_parent(sci, i));
				}
			}
		}
		else
		{	/* fold all children of the current fold point */
			for (i = line; i < last_line; i++)
			{
				gint level = sci_get_fold_level(sci, i);
				if (level & SC_FOLDLEVELHEADERFLAG)
				{
					if (sci_get_fold_expanded(sci, i))
						sci_toggle_fold(sci, i);
				}
			}
		}
	}
}


static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
{
	/* left click to marker margin marks the line */
	if (nt->margin == 1)
	{
		gint line = sci_get_line_from_position(editor->sci, nt->position);

		/*sci_marker_delete_all(editor->sci, 1);*/
		sci_toggle_marker_at_line(editor->sci, line, 1);	/* toggle the marker */
	}
	/* left click on the folding margin to toggle folding state of current line */
	else if (nt->margin == 2 && editor_prefs.folding)
	{
		gint line = sci_get_line_from_position(editor->sci, nt->position);
		editor_toggle_fold(editor, line, nt->modifiers);
	}
}


static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
{
	ScintillaObject *sci = editor->sci;
	gint pos = sci_get_current_position(sci);

	/* undo / redo menu update */
	ui_update_popup_reundo_items(editor->document);

	/* brace highlighting */
	editor_highlight_braces(editor, pos);

	ui_update_statusbar(editor->document, pos);

#if 0
	/** experimental code for inverting selections */
	{
	gint i;
	for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
	{
		/* need to get colour from getstyleat(), but how? */
		SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
		SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
	}

	sci_get_style_at(sci, pos);
	}
#endif
}


static void check_line_breaking(GeanyEditor *editor, gint pos, gchar c)
{
	ScintillaObject *sci = editor->sci;
	gint line, lstart, col;

	if (!editor->line_breaking)
		return;

	col = sci_get_col_from_position(sci, pos);

	if (c == GDK_space)
		pos--;	/* Look for previous space, not the new one */

	line = sci_get_current_line(sci);

	lstart = sci_get_position_from_line(sci, line);

	/* use column instead of position which might be different with multibyte characters */
	if (col < editor_prefs.line_break_column)
		return;

	/* look for the last space before line_break_column */
	pos = MIN(pos, lstart + editor_prefs.line_break_column);

	while (pos > lstart)
	{
		c = sci_get_char_at(sci, --pos);
		if (c == GDK_space)
		{
			gint diff, last_pos, last_col;

			/* remember the distance between the current column and the last column on the line
			 * (we use column position in case the previous line gets altered, such as removing
			 * trailing spaces or in case it contains multibyte characters) */
			last_pos = sci_get_line_end_position(sci, line);
			last_col = sci_get_col_from_position(sci, last_pos);
			diff = last_col - col;

			/* break the line after the space */
			sci_set_current_position(sci, pos + 1, FALSE);
			sci_cancel(sci);	/* don't select from completion list */
			sci_send_command(sci, SCI_NEWLINE);
			line++;

			/* correct cursor position (might not be at line end) */
			last_pos = sci_get_line_end_position(sci, line);
			last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
			/* last column - distance is the desired column, then retrieve its document position */
			pos = SSM(sci, SCI_FINDCOLUMN, line, last_col - diff);
			sci_set_current_position(sci, pos, FALSE);

			return;
		}
	}
}


static void show_autocomplete(ScintillaObject *sci, gint rootlen, const gchar *words)
{
	/* store whether a calltip is showing, so we can reshow it after autocompletion */
	calltip.set = SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
	SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words);
}


static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
{
	ScintillaObject *sci = editor->sci;

	g_return_if_fail(tags);

	if (tags->len > 0)
	{
		GString *words = g_string_sized_new(150);
		guint j;

		for (j = 0; j < tags->len; ++j)
		{
			TMTag *tag = tags->pdata[j];

			if (j > 0)
				g_string_append_c(words, '\n');

			if (j == editor_prefs.autocompletion_max_entries)
			{
				g_string_append(words, "...");
				break;
			}
			g_string_append(words, tag->name);

			/* for now, tag types don't all follow C, so just look at arglist */
			if (NZV(tag->atts.entry.arglist))
				g_string_append(words, "?2");
			else
				g_string_append(words, "?1");
		}
		show_autocomplete(sci, rootlen, words->str);
		g_string_free(words, TRUE);
	}
}


/* do not use with long strings */
static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
{
	gsize len = strlen(str);
	gchar *buf;

	g_return_val_if_fail(len < 100, FALSE);

	buf = g_alloca(len + 1);
	sci_get_text_range(sci, pos - len, pos, buf);
	return strcmp(str, buf) == 0;
}


static gboolean reshow_calltip(gpointer data)
{
	GeanyDocument *doc;

	g_return_val_if_fail(calltip.sci != NULL, FALSE);

	SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
	doc = document_get_current();

	if (doc && doc->editor->sci == calltip.sci)
	{
		/* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
		 * may be completely wrong in case the user cancelled the auto completion with the mouse */
		SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
	}
	return FALSE;
}


static void request_reshowing_calltip(SCNotification *nt)
{
	if (calltip.set)
	{
		/* delay the reshow of the calltip window to make sure it is actually displayed,
		 * without it might be not visible on SCN_AUTOCCANCEL */
		g_idle_add(reshow_calltip, NULL);
	}
}


static void autocomplete_scope(GeanyEditor *editor)
{
	ScintillaObject *sci = editor->sci;
	gint pos = sci_get_current_position(editor->sci);
	gchar typed = sci_get_char_at(sci, pos - 1);
	gchar *name;
	const GPtrArray *tags = NULL;
	const TMTag *tag;
	GeanyFiletype *ft = editor->document->file_type;

	if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
	{
		if (match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "::"))
			pos--;
		else if (typed != '.')
			return;
	}
	else if (typed != '.')
		return;

	/* allow for a space between word and operator */
	if (isspace(sci_get_char_at(sci, pos - 2)))
		pos--;
	name = editor_get_word_at_pos(editor, pos - 1, NULL);
	if (!name)
		return;

	tags = tm_workspace_find(name, tm_tag_max_t, NULL, FALSE, ft->lang);
	g_free(name);
	if (!tags || tags->len == 0)
		return;

	tag = g_ptr_array_index(tags, 0);
	name = tag->atts.entry.var_type;
	if (name)
	{
		TMWorkObject *obj = editor->document->tm_file;

		tags = tm_workspace_find_scope_members(obj ? obj->tags_array : NULL,
			name, TRUE, FALSE);
		if (tags)
			show_tags_list(editor, tags, 0);
	}
}


static void on_char_added(GeanyEditor *editor, SCNotification *nt)
{
	ScintillaObject *sci = editor->sci;
	gint pos = sci_get_current_position(sci);

	switch (nt->ch)
	{
		case '\r':
		{	/* simple indentation (only for CR format) */
			if (sci_get_eol_mode(sci) == SC_EOL_CR)
				on_new_line_added(editor);
			break;
		}
		case '\n':
		{	/* simple indentation (for CR/LF and LF format) */
			on_new_line_added(editor);
			break;
		}
		case '>':
			editor_start_auto_complete(editor, pos, FALSE);	/* C/C++ ptr-> scope completion */
			/* fall through */
		case '/':
		{	/* close xml-tags */
			handle_xml(editor, pos, nt->ch);
			break;
		}
		case '(':
		{
			auto_close_chars(sci, pos, nt->ch);
			/* show calltips */
			editor_show_calltip(editor, --pos);
			break;
		}
		case ')':
		{	/* hide calltips */
			if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
			{
				SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
			}
			g_free(calltip.text);
			calltip.text = NULL;
			calltip.pos = 0;
			calltip.sci = NULL;
			calltip.set = FALSE;
			break;
		}
		case '{':
		case '[':
		case '"':
		case '\'':
		{
			auto_close_chars(sci, pos, nt->ch);
			break;
		}
		case '}':
		{	/* closing bracket handling */
			if (editor->auto_indent)
				close_block(editor, pos - 1);
			break;
		}
		/* scope autocompletion */
		case '.':
		case ':':	/* C/C++ class:: syntax */
		/* tag autocompletion */
		default:
#if 0
			if (! editor_start_auto_complete(editor, pos, FALSE))
				request_reshowing_calltip(nt);
#else
			editor_start_auto_complete(editor, pos, FALSE);
#endif
	}
	check_line_breaking(editor, pos, nt->ch);
}


/* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
		gboolean force, gint visLevels, gint level)
{
	gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
	gint levelLine = level;
	(*line)++;
	while (*line <= lineMaxSubord)
	{
		if (G_UNLIKELY(force))
		{
			if (visLevels > 0)
				SSM(sci, SCI_SHOWLINES, *line, *line);
			else
				SSM(sci, SCI_HIDELINES, *line, *line);
		}
		else
		{
			if (doExpand)
				SSM(sci, SCI_SHOWLINES, *line, *line);
		}
		if (levelLine == -1)
			levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
		if (levelLine & SC_FOLDLEVELHEADERFLAG)
		{
			if (G_UNLIKELY(force))
			{
				if (visLevels > 1)
					SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
				else
					SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
				expand(sci, line, doExpand, force, visLevels - 1, -1);
			}
			else
			{
				if (doExpand)
				{
					if (!sci_get_fold_expanded(sci, *line))
						SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
					expand(sci, line, TRUE, force, visLevels - 1, -1);
				}
				else
				{
					expand(sci, line, FALSE, force, visLevels - 1, -1);
				}
			}
		}
		else
		{
			(*line)++;
		}
	}
}


static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
{
	if (levelNow & SC_FOLDLEVELHEADERFLAG)
	{
		if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
		{
			/* Adding a fold point */
			SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
			expand(sci, &line, TRUE, FALSE, 0, levelPrev);
		}
	}
	else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
	{
		if (! sci_get_fold_expanded(sci, line))
		{	/* Removing the fold from one that has been contracted so should expand
			 * otherwise lines are left invisible with no way to make them visible */
			SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
			expand(sci, &line, TRUE, FALSE, 0, levelPrev);
		}
	}
	if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
			((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
	{
		/* See if should still be hidden */
		gint parentLine = sci_get_fold_parent(sci, line);
		if (parentLine < 0)
		{
			SSM(sci, SCI_SHOWLINES, line, line);
		}
		else if (sci_get_fold_expanded(sci, parentLine) &&
				sci_get_line_is_visible(sci, parentLine))
		{
			SSM(sci, SCI_SHOWLINES, line, line);
		}
	}
}


static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
		gboolean enforcePolicy)
{
	gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
	gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
	gint line;

	for (line = lineStart; line <= lineEnd; line++)
	{
		SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
	}
}


static void auto_update_margin_width(GeanyEditor *editor)
{
	gint next_linecount = 1;
	gint linecount = sci_get_line_count(editor->sci);
	GeanyDocument *doc = editor->document;

	while (next_linecount <= linecount)
		next_linecount *= 10;

	if (editor->document->priv->line_count != next_linecount)
	{
		doc->priv->line_count = next_linecount;
		sci_set_line_numbers(editor->sci, TRUE, 0);
	}
}


static void partial_complete(ScintillaObject *sci, const gchar *text)
{
	gint pos = sci_get_current_position(sci);

	sci_insert_text(sci, pos, text);
	sci_set_current_position(sci, pos + strlen(text), TRUE);
}


/* Complete the next word part from @a entry */
static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
{
	gchar *stem, *ptr, *text = utils_strdupa(entry);

	read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
	stem = current_word;
	if (strstr(text, stem) != text)
		return FALSE;	/* shouldn't happen */
	if (strlen(text) <= strlen(stem))
		return FALSE;

	text += strlen(stem); /* skip stem */
	ptr = strstr(text + 1, "_");
	if (ptr)
	{
		ptr[1] = '\0';
		partial_complete(editor->sci, text);
		return TRUE;
	}
	else
	{
		/* CamelCase */
		foreach_str(ptr, text + 1)
		{
			if (!ptr[0])
				break;
			if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
			{
				ptr[0] = '\0';
				partial_complete(editor->sci, text);
				return TRUE;
			}
		}
	}
	return FALSE;
}


/* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
 * Plugins can connect to the "editor-notify" signal. */
void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
						  gpointer scnt, gpointer data)
{
	GeanyEditor *editor = data;
	gboolean retval;

	g_return_if_fail(editor != NULL);

	g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
}


static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
								 SCNotification *nt, G_GNUC_UNUSED gpointer data)
{
	ScintillaObject *sci = editor->sci;
	GeanyDocument *doc = editor->document;

	switch (nt->nmhdr.code)
	{
		case SCN_SAVEPOINTLEFT:
			document_set_text_changed(doc, TRUE);
			break;

		case SCN_SAVEPOINTREACHED:
			document_set_text_changed(doc, FALSE);
			break;

		case SCN_MODIFYATTEMPTRO:
			utils_beep();
			break;

		case SCN_MARGINCLICK:
			on_margin_click(editor, nt);
			break;

		case SCN_UPDATEUI:
			on_update_ui(editor, nt);
			break;

		case SCN_PAINTED:
			/* Visible lines are only laid out accurately just before painting,
			 * so we need to only call editor_scroll_to_line here, because the document
			 * may have line wrapping and folding enabled.
			 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
			 * This is important e.g. when loading a session and switching pages
			 * and having the cursor scroll in view. */
			 /* FIXME: Really we want to do this just before painting, not after it
			  * as it will cause repainting. */
			if (editor->scroll_percent > 0.0F)
			{
				editor_scroll_to_line(editor, -1, editor->scroll_percent);
				/* disable further scrolling */
				editor->scroll_percent = -1.0F;
			}
			break;

 		case SCN_MODIFIED:
			if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
			{
				/* automatically adjust Scintilla's line numbers margin width */
				auto_update_margin_width(editor);
			}
			if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
			{
				/* get notified about undo changes */
				document_undo_add(doc, UNDO_SCINTILLA, NULL);
			}
			if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
			{
				/* handle special fold cases, e.g. #1923350 */
				fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
			}
			break;

		case SCN_CHARADDED:
			on_char_added(editor, nt);
			break;

		case SCN_USERLISTSELECTION:
			if (nt->listType == 1)
			{
				sci_add_text(sci, nt->text);
			}
			break;

		case SCN_AUTOCSELECTION:
			if (g_str_equal(nt->text, "..."))
			{
				sci_cancel(sci);
				utils_beep();
				break;
			}
			/* fall through */
		case SCN_AUTOCCANCELLED:
			/* now that autocomplete is finishing or was cancelled, reshow calltips
			 * if they were showing */
			request_reshowing_calltip(nt);
			break;

#ifdef GEANY_DEBUG
		case SCN_STYLENEEDED:
			geany_debug("style");
			break;
#endif
		case SCN_NEEDSHOWN:
			ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
			break;

		case SCN_URIDROPPED:
			if (nt->text != NULL)
			{
				document_open_file_list(nt->text, -1);
			}
			break;

		case SCN_CALLTIPCLICK:
			if (nt->position > 0)
			{
				switch (nt->position)
				{
					case 1:	/* up arrow */
						if (calltip.tag_index > 0)
							calltip.tag_index--;
						break;

					case 2: calltip.tag_index++; break;	/* down arrow */
				}
				editor_show_calltip(editor, -1);
			}
			break;

		case SCN_ZOOM:
			/* recalculate line margin width */
			sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);
			break;
	}
	/* we always return FALSE here to let plugins handle the event too */
	return FALSE;
}


/* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
 * a scintilla pointer. */
static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
{
	if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
		return indent_prefs->hard_tab_width;

	return indent_prefs->width;	/* tab width = indent width */
}


/* Returns a string containing width chars of whitespace, filled with simple space
 * characters or with the right number of tab characters, according to the indent prefs.
 * (Result is filled with tabs *and* spaces if width isn't a multiple of
 * the tab width). */
static gchar *
get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
{
	g_return_val_if_fail(width >= 0, NULL);

	if (width == 0)
		return g_strdup("");

	if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
	{
		return g_strnfill(width, ' ');
	}
	else
	{	/* first fill text with tabs and fill the rest with spaces */
		const gint tab_width = get_tab_width(iprefs);
		gint tabs = width / tab_width;
		gint spaces = width % tab_width;
		gint len = tabs + spaces;
		gchar *str;

		str = g_malloc(len + 1);

		memset(str, '\t', tabs);
		memset(str + tabs, ' ', spaces);
		str[len] = '\0';
		return str;
 	}
}


static const GeanyIndentPrefs *
get_default_indent_prefs(void)
{
	static GeanyIndentPrefs iprefs;

	iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
	return &iprefs;
}


/** Gets the indentation prefs for the editor.
 * Prefs can be different according to project or document.
 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
 * settings may have changed, or if this function has been called for a different editor.
 * @param editor The editor, or @c NULL to get the default indent prefs.
 * @return The indent prefs. */
const GeanyIndentPrefs *
editor_get_indent_prefs(GeanyEditor *editor)
{
	static GeanyIndentPrefs iprefs;
	const GeanyIndentPrefs *dprefs = get_default_indent_prefs();

	/* Return the address of the default prefs to allow returning default and editor
	 * pref pointers without invalidating the contents of either. */
	if (editor == NULL)
		return dprefs;

	iprefs = *dprefs;
	iprefs.type = editor->indent_type;
	iprefs.width = editor->indent_width;

	/* if per-document auto-indent is enabled, but we don't have a global mode set,
	 * just use basic auto-indenting */
	if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
		iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;

	if (!editor->auto_indent)
		iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;

	return &iprefs;
}


static void on_new_line_added(GeanyEditor *editor)
{
	ScintillaObject *sci = editor->sci;
	gint line = sci_get_current_line(sci);

	/* simple indentation */
	if (editor->auto_indent)
	{
		insert_indent_after_line(editor, line - 1);
	}

	if (editor_prefs.auto_continue_multiline)
	{	/* " * " auto completion in multiline C/C++/D/Java comments */
		auto_multiline(editor, line);
	}

	if (editor_prefs.newline_strip)
	{	/* strip the trailing spaces on the previous line */
		editor_strip_line_trailing_spaces(editor, line - 1);
	}
}


static gboolean lexer_has_braces(ScintillaObject *sci)
{
	gint lexer = sci_get_lexer(sci);

	switch (lexer)
	{
		case SCLEX_CPP:
		case SCLEX_D:
		case SCLEX_HTML:	/* for PHP & JS */
		case SCLEX_PASCAL:	/* for multiline comments? */
		case SCLEX_BASH:
		case SCLEX_PERL:
		case SCLEX_TCL:
			return TRUE;
		default:
			return FALSE;
	}
}


/* Read indent chars for the line that pos is on into indent global variable.
 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
 * instead in any new code.  */
static void read_indent(GeanyEditor *editor, gint pos)
{
	ScintillaObject *sci = editor->sci;
	guint i, len, j = 0;
	gint line;
	gchar *linebuf;

	line = sci_get_line_from_position(sci, pos);

	len = sci_get_line_length(sci, line);
	linebuf = sci_get_line(sci, line);

	for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
	{
		if (linebuf[i] == ' ' || linebuf[i] == '\t')	/* simple indentation */
			indent[j++] = linebuf[i];
		else
			break;
	}
	indent[j] = '\0';
	g_free(linebuf);
}


static gint get_brace_indent(ScintillaObject *sci, gint line)
{
	guint i, len;
	gint ret = 0;
	gchar *linebuf;

	len = sci_get_line_length(sci, line);
	linebuf = sci_get_line(sci, line);

	for (i = 0; i < len; i++)
	{
		/* i == (len - 1) prevents wrong indentation after lines like
		 * "	{ return bless({}, shift); }" (Perl) */
		if (linebuf[i] == '{' && i == (len - 1))
		{
			ret++;
			break;
		}
		else
		{
			gint k = len - 1;

			while (k > 0 && isspace(linebuf[k])) k--;

			/* if last non-whitespace character is a { increase indentation by a tab
			 * e.g. for (...) { */
			if (linebuf[k] == '{')
			{
				ret++;
			}
			break;
		}
	}
	g_free(linebuf);
	return ret;
}


static gint get_python_indent(ScintillaObject *sci, gint line)
{
	gint last_char = sci_get_line_end_position(sci, line) - 1;

	/* add extra indentation for Python after colon */
	if (sci_get_char_at(sci, last_char) == ':' &&
		sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
	{
		return 1;
	}
	return 0;
}


static gint get_xml_indent(ScintillaObject *sci, gint line)
{
	gboolean need_close = FALSE;
	gint end = sci_get_line_end_position(sci, line) - 1;
	gint pos;

	/* don't indent if there's a closing tag to the right of the cursor */
	pos = sci_get_current_position(sci);
	if (sci_get_char_at(sci, pos) == '<' &&
		sci_get_char_at(sci, pos + 1) == '/')
		return 0;

	if (sci_get_char_at(sci, end) == '>' &&
		sci_get_char_at(sci, end - 1) != '/')
	{
		gint style = sci_get_style_at(sci, end);

		if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
		{
			gint start = sci_get_position_from_line(sci, line);
			gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
			gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);

			if (NZV(opened_tag_name))
			{
				need_close = TRUE;
				if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
					need_close = FALSE;
			}
			g_free(line_contents);
			g_free(opened_tag_name);
		}
	}

	return need_close ? 1 : 0;
}


static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
{
	ScintillaObject *sci = editor->sci;
	gint size;
	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);

	g_return_val_if_fail(line >= 0, 0);

	size = sci_get_line_indentation(sci, line);

	if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
	{
		gint additional_indent = 0;

		if (lexer_has_braces(sci))
			additional_indent = iprefs->width * get_brace_indent(sci, line);
		else
		if (editor->document->file_type->id == GEANY_FILETYPES_PYTHON)
			additional_indent = iprefs->width * get_python_indent(sci, line);

		/* HTML lexer "has braces" because of PHP and JavaScript.  If get_brace_indent() did not
		 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
		 * should make the XML-related check */
		if (additional_indent == 0 &&
			(sci_get_lexer(sci) == SCLEX_HTML ||
			sci_get_lexer(sci) == SCLEX_XML) &&
			editor->document->file_type->priv->xml_indent_tags)
		{
			size += iprefs->width * get_xml_indent(sci, line);
		}

		size += additional_indent;
	}
	return size;
}


static void insert_indent_after_line(GeanyEditor *editor, gint line)
{
	ScintillaObject *sci = editor->sci;
	gint line_indent = sci_get_line_indentation(sci, line);
	gint size = get_indent_size_after_line(editor, line);
	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
	gchar *text;

	if (size == 0)
		return;

	if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
	{
		/* support tab indents, space aligns style - copy last line 'indent' exactly */
		gint start = sci_get_position_from_line(sci, line);
		gint end = sci_get_line_indent_position(sci, line);

		text = sci_get_contents_range(sci, start, end);
	}
	else
	{
		text = get_whitespace(iprefs, size);
	}
	sci_add_text(sci, text);
	g_free(text);
}


static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
{
	const gchar *closing_char = NULL;
	gint end_pos = -1;

	if (utils_isbrace(c, 0))
		end_pos = sci_find_matching_brace(sci, pos - 1);

	switch (c)
	{
		case '(':
			if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
				closing_char = ")";
			break;
		case '{':
			if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
				closing_char = "}";
			break;
		case '[':
			if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
				closing_char = "]";
			break;
		case '\'':
			if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
				closing_char = "'";
			break;
		case '"':
			if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
				closing_char = "\"";
			break;
	}

	if (closing_char != NULL)
	{
		sci_add_text(sci, closing_char);
		sci_set_current_position(sci, pos, TRUE);
	}
}


/* Finds a corresponding matching brace to the given pos
 * (this is taken from Scintilla Editor.cxx,
 * fit to work with close_block) */
static gint brace_match(ScintillaObject *sci, gint pos)
{
	gchar chBrace = sci_get_char_at(sci, pos);
	gchar chSeek = utils_brace_opposite(chBrace);
	gchar chAtPos;
	gint direction = -1;
	gint styBrace;
	gint depth = 1;
	gint styAtPos;

	styBrace = sci_get_style_at(sci, pos);

	if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
		direction = 1;

	pos = pos + direction;
	while ((pos >= 0) && (pos < sci_get_length(sci)))
	{
		chAtPos = sci_get_char_at(sci, pos - 1);
		styAtPos = sci_get_style_at(sci, pos);

		if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
		{
			if (chAtPos == chBrace)
				depth++;
			if (chAtPos == chSeek)
				depth--;
			if (depth == 0)
				return pos;
		}
		pos = pos + direction;
	}
	return -1;
}


/* Called after typing '}'. */
static void close_block(GeanyEditor *editor, gint pos)
{
	GeanyDocument *doc;
	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
	gint x = 0, cnt = 0;
	gint line, line_len, eol_char_len;
	gchar *text, *line_buf;
	ScintillaObject *sci;
	gint line_indent, last_indent;

	if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
		return;
	g_return_if_fail(editor != NULL && editor->document->file_type != NULL);

	sci = editor->sci;
	doc = editor->document;

	if (! lexer_has_braces(sci))
		return;

	line = sci_get_line_from_position(sci, pos);
	line_len = sci_get_line_length(sci, line);
	/* set eol_char_len to 0 if on last line, because there is no EOL char */
	eol_char_len = (line == (sci_get_line_count(sci) - 1)) ? 0 :
								editor_get_eol_char_len(editor);

	/* check that the line is empty, to not kill text in the line */
	line_buf = sci_get_line(sci, line);
	line_buf[line_len - eol_char_len] = '\0';
	while (x < (line_len - eol_char_len))
	{
		if (isspace(line_buf[x]))
			cnt++;
		x++;
	}
	g_free(line_buf);

	if ((line_len - eol_char_len - 1) != cnt)
		return;

	if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
	{
		gint start_brace = brace_match(sci, pos);

		if (start_brace >= 0)
		{
			gint line_start;
			gint brace_line = sci_get_line_from_position(sci, start_brace);
			gint size = sci_get_line_indentation(sci, brace_line);
			gchar *ind = get_whitespace(iprefs, size);

			text = g_strconcat(ind, "}", NULL);
			line_start = sci_get_position_from_line(sci, line);
			sci_set_anchor(sci, line_start);
			sci_replace_sel(sci, text);
			g_free(text);
			g_free(ind);
			return;
		}
		/* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
	}

	/* GEANY_AUTOINDENT_CURRENTCHARS */
	line_indent = sci_get_line_indentation(sci, line);
	last_indent = sci_get_line_indentation(sci, line - 1);

	if (line_indent < last_indent)
		return;
	line_indent -= iprefs->width;
	line_indent = MAX(0, line_indent);
	sci_set_line_indentation(sci, line, line_indent);
}


/* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
 * position can be -1, then the current position is used.
 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
		const gchar *wc, gboolean stem)
{
	gint line, line_start, startword, endword;
	gchar *chunk;
	ScintillaObject *sci;

	g_return_if_fail(editor != NULL);
	sci = editor->sci;

	if (pos == -1)
		pos = sci_get_current_position(sci);

	line = sci_get_line_from_position(sci, pos);
	line_start = sci_get_position_from_line(sci, line);
	startword = pos - line_start;
	endword = pos - line_start;

	word[0] = '\0';
	chunk = sci_get_line(sci, line);

	if (wc == NULL)
		wc = GEANY_WORDCHARS;

	/* the checks for "c < 0" are to allow any Unicode character which should make the code
	 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
	 * TODO: improve this code */
	while (startword > 0 && (strchr(wc, chunk[startword - 1]) || chunk[startword - 1] < 0))
		startword--;
	if (!stem)
	{
		while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || chunk[endword] < 0))
			endword++;
	}

	if (startword != endword)
	{
		chunk[endword] = '\0';

		g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
	}
	else
		g_strlcpy(word, "", wordlen);

	g_free(chunk);
}


/* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
 * position can be -1, then the current position is used.
 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
							  const gchar *wc)
{
	read_current_word(editor, pos, word, wordlen, wc, FALSE);
}


/**
 *  Finds the word at the position specified by @a pos. If any word is found, it is returned.
 *  Otherwise NULL is returned.
 *  Additional wordchars can be specified to define what to consider as a word.
 *
 *  @param editor The editor to operate on.
 *  @param pos The position where the word should be read from.
 *             Maybe @c -1 to use the current position.
 *  @param wordchars The wordchars to separate words. wordchars mean all characters to count
 *                   as part of a word. Maybe @c NULL to use the default wordchars,
 *                   see @ref GEANY_WORDCHARS.
 *
 *  @return A newly-allocated string containing the word at the given @a pos or @c NULL.
 *          Should be freed when no longer needed.
 *
 *  @since 0.16
 */
gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
{
	static gchar cword[GEANY_MAX_WORD_LENGTH];

	g_return_val_if_fail(editor != NULL, FALSE);

	read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);

	return (*cword == '\0') ? NULL : g_strdup(cword);
}


/* Read the word up to position @a pos. */
static const gchar *
editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
{
	static gchar word[GEANY_MAX_WORD_LENGTH];

	read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);

	return (*word) ? word : NULL;
}


static gint find_previous_brace(ScintillaObject *sci, gint pos)
{
	gchar c;
	gint orig_pos = pos;

	c = sci_get_char_at(sci, pos);
	while (pos >= 0 && pos > orig_pos - 300)
	{
		c = sci_get_char_at(sci, pos);
		pos--;
		if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
			return pos;
	}
	return -1;
}


static gint find_start_bracket(ScintillaObject *sci, gint pos)
{
	gchar c;
	gint brackets = 0;
	gint orig_pos = pos;

	c = sci_get_char_at(sci, pos);
	while (pos > 0 && pos > orig_pos - 300)
	{
		c = sci_get_char_at(sci, pos);
		if (c == ')') brackets++;
		else if (c == '(') brackets--;
		pos--;
		if (brackets < 0) return pos;	/* found start bracket */
	}
	return -1;
}


static gboolean append_calltip(GString *str, const TMTag *tag, filetype_id ft_id)
{
	if (! tag->atts.entry.arglist)
		return FALSE;

	if (ft_id != GEANY_FILETYPES_PASCAL)
	{	/* usual calltips: "retval tagname (arglist)" */
		if (tag->atts.entry.var_type)
		{
			guint i;

			g_string_append(str, tag->atts.entry.var_type);
			for (i = 0; i < tag->atts.entry.pointerOrder; i++)
			{
				g_string_append_c(str, '*');
			}
			g_string_append_c(str, ' ');
		}
		if (tag->atts.entry.scope)
		{
			const gchar *cosep = symbols_get_context_separator(ft_id);

			g_string_append(str, tag->atts.entry.scope);
			g_string_append(str, cosep);
		}
		g_string_append(str, tag->name);
		g_string_append_c(str, ' ');
		g_string_append(str, tag->atts.entry.arglist);
	}
	else
	{	/* special case Pascal calltips: "tagname (arglist) : retval" */
		g_string_append(str, tag->name);
		g_string_append_c(str, ' ');
		g_string_append(str, tag->atts.entry.arglist);

		if (NZV(tag->atts.entry.var_type))
		{
			g_string_append(str, " : ");
			g_string_append(str, tag->atts.entry.var_type);
		}
	}

	return TRUE;
}


static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
{
	const GPtrArray *tags;
	const gint arg_types = tm_tag_function_t | tm_tag_prototype_t |
		tm_tag_method_t | tm_tag_macro_with_arg_t;
	TMTagAttrType *attrs = NULL;
	TMTag *tag;
	GString *str = NULL;
	guint i;

	g_return_val_if_fail(ft && word && *word, NULL);

	/* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
	tags = tm_workspace_find(word, tm_tag_max_t, attrs, FALSE, ft->lang);
	if (tags->len == 0)
		return NULL;

	tag = TM_TAG(tags->pdata[0]);

	if (tag->type == tm_tag_class_t && FILETYPE_ID(ft) == GEANY_FILETYPES_D)
	{
		/* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
		tags = tm_workspace_find_scoped("this", tag->name,
			arg_types, attrs, FALSE, ft->lang, TRUE);
		if (tags->len == 0)
			return NULL;
	}

	/* remove tags with no argument list */
	for (i = 0; i < tags->len; i++)
	{
		tag = TM_TAG(tags->pdata[i]);

		if (! tag->atts.entry.arglist)
			tags->pdata[i] = NULL;
	}
	tm_tags_prune((GPtrArray *) tags);
	if (tags->len == 0)
		return NULL;
	else
	{	/* remove duplicate calltips */
		TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
			tm_tag_attr_arglist_t, 0};

		tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE);
	}

	/* if the current word has changed since last time, start with the first tag match */
	if (! utils_str_equal(word, calltip.last_word))
		calltip.tag_index = 0;
	/* cache the current word for next time */
	g_free(calltip.last_word);
	calltip.last_word = g_strdup(word);
	calltip.tag_index = MIN(calltip.tag_index, tags->len - 1);	/* ensure tag_index is in range */

	for (i = calltip.tag_index; i < tags->len; i++)
	{
		tag = TM_TAG(tags->pdata[i]);

		if (str == NULL)
		{
			str = g_string_new(NULL);
			if (calltip.tag_index > 0)
				g_string_prepend(str, "\001 ");	/* up arrow */
			append_calltip(str, tag, FILETYPE_ID(ft));
		}
		else /* add a down arrow */
		{
			if (calltip.tag_index > 0)	/* already have an up arrow */
				g_string_insert_c(str, 1, '\002');
			else
				g_string_prepend(str, "\002 ");
			break;
		}
	}
	if (str)
	{
		gchar *result = str->str;

		g_string_free(str, FALSE);
		return result;
	}
	return NULL;
}


/* use pos = -1 to search for the previous unmatched open bracket. */
gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
{
	gint orig_pos = pos; /* the position for the calltip */
	gint lexer;
	gint style;
	gchar word[GEANY_MAX_WORD_LENGTH];
	gchar *str;
	ScintillaObject *sci;

	g_return_val_if_fail(editor != NULL, FALSE);
	g_return_val_if_fail(editor->document->file_type != NULL, FALSE);

	sci = editor->sci;

	lexer = sci_get_lexer(sci);

	if (pos == -1)
	{
		/* position of '(' is unknown, so go backwards from current position to find it */
		pos = sci_get_current_position(sci);
		pos--;
		orig_pos = pos;
		pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
			find_start_bracket(sci, pos);
		if (pos == -1)
			return FALSE;
	}

	/* the style 1 before the brace (which may be highlighted) */
	style = sci_get_style_at(sci, pos - 1);
	if (! highlighting_is_code_style(lexer, style))
		return FALSE;

	word[0] = '\0';
	editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
	if (word[0] == '\0')
		return FALSE;

	str = find_calltip(word, editor->document->file_type);
	if (str)
	{
		g_free(calltip.text);	/* free the old calltip */
		calltip.text = str;
		calltip.pos = orig_pos;
		calltip.sci = sci;
		calltip.set = TRUE;
		utils_wrap_string(calltip.text, -1);
		SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
		return TRUE;
	}
	return FALSE;
}


gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
{
	GString *str;

	g_return_val_if_fail(editor != NULL, NULL);

	str = g_string_new(NULL);
	if (append_calltip(str, tag, editor->document->file_type->id))
		return g_string_free(str, FALSE);
	else
		return g_string_free(str, TRUE);
}


/* HTML entities auto completion from html_entities.tags text file */
static gboolean
autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
{
	guint i, j = 0;
	gboolean found = FALSE;
	GString *words;
	const gchar **entities = symbols_get_html_entities();

	if (*root != '&' || G_UNLIKELY(entities == NULL))
		return FALSE;

	words = g_string_sized_new(500);
	for (i = 0; ; i++)
	{
		if (entities[i] == NULL)
			break;
		else if (entities[i][0] == '#')
			continue;

		if (! strncmp(entities[i], root, rootlen))
		{
			if (j++ > 0)
				g_string_append_c(words, '\n');
			g_string_append(words, entities[i]);
			found = TRUE;
		}
	}
	if (found)
		show_autocomplete(sci, rootlen, words->str);

	g_string_free(words, TRUE);
	return found;
}


/* Current document & global tags autocompletion */
static gboolean
autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
{
	TMTagAttrType attrs[] = { tm_tag_attr_name_t, 0 };
	const GPtrArray *tags;
	GeanyDocument *doc;

	g_return_val_if_fail(editor, FALSE);

	doc = editor->document;

	tags = tm_workspace_find(root, tm_tag_max_t, attrs, TRUE, doc->file_type->lang);
	if (tags)
	{
		show_tags_list(editor, tags, rootlen);
		return tags->len > 0;
	}
	return FALSE;
}


/* Check whether to use entity autocompletion:
 * - always in a HTML file except when inside embedded JavaScript, Python, ASP, ...
 * - in a PHP file only when we are outside of <? ?> */
static gboolean autocomplete_check_for_html(gint ft_id, gint style)
{
	/* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
	 * (everything after SCE_HJ_START is for embedded scripting languages) */
	if (ft_id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
		return TRUE;

	if (ft_id == GEANY_FILETYPES_PHP)
	{
		/* use entity completion when style is outside of PHP styles */
		if (! is_style_php(style))
			return TRUE;
	}

	return FALSE;
}


/* Algorithm based on based on Scite's StartAutoCompleteWord() */
static GString *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
{
	gchar *word;
	gint len, current, word_end;
	gint pos_find, flags;
	guint word_length;
	gsize nmatches = 0;
	GString *words;
	struct Sci_TextToFind ttf;

	len = sci_get_length(sci);
	current = sci_get_current_position(sci) - rootlen;

	ttf.lpstrText = root;
	ttf.chrg.cpMin = 0;
	ttf.chrg.cpMax = len;
	ttf.chrgText.cpMin = 0;
	ttf.chrgText.cpMax = 0;
	flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;

	words = g_string_sized_new(256);
	/* put space before first entry to make searching with strstr easy */
	g_string_append_c(words, ' ');

	/* search the whole document for the word root and collect results */
	pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
	while (pos_find >= 0 && pos_find < len)
	{
		word_end = pos_find + rootlen;
		if (pos_find != current)
		{
			while (word_end < len && strchr(GEANY_WORDCHARS, sci_get_char_at(sci, word_end)) != NULL)
				word_end++;

			word_length = word_end - pos_find;
			if (word_length > rootlen)
			{
				word = g_malloc0(word_length + 3);
				sci_get_text_range(sci, pos_find, word_end, word + 1);
				word[0] = ' ';
				word[word_length + 1] = ' ';
				/* search the words string whether we already have the word in, otherwise add it */
				if (strstr(words->str, word) == NULL)
				{
					g_string_append(words, word + 1);
					nmatches++;
				}
				g_free(word);

				if (nmatches == editor_prefs.autocompletion_max_entries)
					break;
			}
		}
		ttf.chrg.cpMin = word_end;
		pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
	}

	if (words->len > 1)
	{
		g_strdelimit(words->str, " ", '\n');
		words->str[words->len - 1] = '\0'; /* remove the trailing '\n' */
		return words;
	}
	g_string_free(words, TRUE);
	return NULL;
}


static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
{
	ScintillaObject *sci = editor->sci;
	GString *words;
	GString *str;
	gchar *ptr;
	GSList *node, *list = NULL;

	words = get_doc_words(sci, root, rootlen);
	if (!words)
	{
		scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
		return FALSE;
	}

	/* words are unsorted, make list of words */
	foreach_str(ptr, words->str)
	{
		if (*ptr == '\n')
		{
			list = g_slist_prepend(list, ptr + 1);
			/* terminate previous string in list */
			ptr[0] = 0x0;
			ptr++;
		}
	}
	list = g_slist_sort(list, (GCompareFunc)utils_str_casecmp);

	str = g_string_sized_new(words->len);
	foreach_slist(node, list)
	{
		g_string_append(str, node->data);
		if (node->next)
			g_string_append_c(str, '\n');
	}
	if (g_slist_length(list) >= editor_prefs.autocompletion_max_entries)
		g_string_append(str, "\n...");

	g_slist_free(list);
	g_string_free(words, TRUE);

	show_autocomplete(sci, rootlen, str->str);
	g_string_free(str, TRUE);
	return TRUE;
}


gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
{
	gint line, line_start, line_len, line_pos, current, rootlen, startword, lexer, style;
	gchar *linebuf, *root;
	ScintillaObject *sci;
	gboolean ret = FALSE;
	const gchar *wordchars;
	GeanyFiletype *ft;

	if (! editor_prefs.auto_complete_symbols && ! force)
		return FALSE;

	g_return_val_if_fail(editor != NULL, FALSE);

	/* If we are at the beginning of the document, we skip autocompletion as we can't determine the
	 * necessary styling information */
	if (G_UNLIKELY(pos < 2))
		return FALSE;

	sci = editor->sci;
	ft = editor->document->file_type;

	line = sci_get_line_from_position(sci, pos);
	line_start = sci_get_position_from_line(sci, line);
	line_len = sci_get_line_length(sci, line);
	line_pos = pos - line_start - 1;
	current = pos - line_start;
	startword = current;
	lexer = sci_get_lexer(sci);
	style = sci_get_style_at(sci, pos - 2);

	/* don't autocomplete in comments and strings */
	if (!force && !highlighting_is_code_style(lexer, style))
		return FALSE;

	autocomplete_scope(editor);

	linebuf = sci_get_line(sci, line);

	if (ft->id == GEANY_FILETYPES_LATEX)
		wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
	else if (ft->id == GEANY_FILETYPES_HTML || ft->id == GEANY_FILETYPES_PHP)
		wordchars = GEANY_WORDCHARS"&"; /* add & to word chars if we are in a PHP or HTML file */
	else
		wordchars = GEANY_WORDCHARS;

	/* find the start of the current word */
	while ((startword > 0) && (strchr(wordchars, linebuf[startword - 1])))
		startword--;
	linebuf[current] = '\0';
	root = linebuf + startword;
	rootlen = current - startword;

	if (rootlen > 0)
	{
		if (autocomplete_check_for_html(ft->id, style))
		{
			/* Allow something like "&quot;some text&quot;". The above startword calculation
			 * only works on words but for HTML entity completion we also want to have completion
			 * based on '&' within words. */
			gchar *tmp = strchr(root, '&');
			if (tmp != NULL)
			{
				root = tmp;
				rootlen = strlen(tmp);
			}
			ret = autocomplete_html(sci, root, rootlen);
		}
		else
		{
			/* force is set when called by keyboard shortcut, otherwise start at the
			 * editor_prefs.symbolcompletion_min_chars'th char */
			if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
			{
				/* complete tags, except if forcing when completion is already visible */
				if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
					ret = autocomplete_tags(editor, root, rootlen);

				/* If forcing and there's nothing else to show, complete from words in document */
				if (!ret && (force || editor_prefs.autocomplete_doc_words))
					ret = autocomplete_doc_word(editor, root, rootlen);
			}
		}
	}
	if (!ret && force)
		utils_beep();

	g_free(linebuf);
	return ret;
}


static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
{
	gchar *result = NULL;
	GHashTable *tmp;

	g_return_val_if_fail(type != NULL && name != NULL, NULL);

	tmp = g_hash_table_lookup(snippet_hash, type);
	if (tmp != NULL)
	{
		result = g_hash_table_lookup(tmp, name);
	}
	/* whether nothing is set for the current filetype(tmp is NULL) or
	 * the particular completion for this filetype is not set (result is NULL) */
	if (tmp == NULL || result == NULL)
	{
		tmp = g_hash_table_lookup(snippet_hash, "Default");
		if (tmp != NULL)
		{
			result = g_hash_table_lookup(tmp, name);
		}
	}
	/* if result is still NULL here, no completion could be found */

	/* result is owned by the hash table and will be freed when the table will destroyed */
	return result;
}


/* This is very ugly but passing the pattern to ac_replace_specials() doesn't work because it is
 * modified when replacing a completion but the foreach function still passes the old pointer
 * to ac_replace_specials, so we use a global pointer outside of ac_replace_specials and
 * ac_complete_constructs. Any hints to improve this are welcome. */
static GString *snippets_global_pattern = NULL;

static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
{
	gchar *needle;

	g_return_if_fail(key != NULL);
	g_return_if_fail(value != NULL);

	needle = g_strconcat("%", (gchar*) key, "%", NULL);

	utils_string_replace_all(snippets_global_pattern, needle, (gchar*) value);
	g_free(needle);
}


/* this only works with spaces only indentation on the lines */
static void fix_line_indents(GeanyEditor *editor, gint line_start, gint line_end)
{
	ScintillaObject *sci = editor->sci;
	gint line, cur_line, cur_col, pos;

	/* get the line, col position as fixing indentation will move cursor to start of line */
	pos = sci_get_current_position(sci);
	cur_col = sci_get_col_from_position(sci, pos);
	cur_line = sci_get_current_line(sci);

	for (line = line_start; line <= line_end; line++)
	{
		gint size = sci_get_line_indentation(sci, line);

		/* set to 0 first to trigger proper indent creation */
		sci_set_line_indentation(sci, line, 0);
		sci_set_line_indentation(sci, line, size);
	}
	pos = scintilla_send_message(sci, SCI_FINDCOLUMN, cur_line, cur_col);
	sci_set_current_position(sci, pos, FALSE);
}


static void replace_leading_tabs(GString *str, const gchar *whitespace)
{
	regex_t regex;
	gssize pos;
	regmatch_t matches[2];
	gchar *ptr;

	if (regcomp(&regex, "^ *(\t)", 0) != 0)
	{
		g_return_if_fail(FALSE);
	}
	ptr = str->str;
	while (ptr)
	{
		if (regexec(&regex, ptr,
			G_N_ELEMENTS(matches), matches, 0) != 0)
			break;

		pos = matches[1].rm_so;
		g_return_if_fail(pos >= 0);
		pos += ptr - str->str;
		g_string_erase(str, pos, 1);
		g_string_insert(str, pos, whitespace);
		ptr = str->str + pos + strlen(whitespace);
	}
	regfree(&regex);
}


/** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
 * accordingly for the document.
 * - Leading tabs are replaced with the correct indentation.
 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
 * - Newline chars are replaced with the correct line ending string.
 * This is very useful for inserting code without having to handle the indent
 * type yourself (Tabs & Spaces mode can be tricky).
 * @param editor Editor.
 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
 * @param insert_pos Document position to insert text at.
 * @param cursor_index If >= 0, the index into @a text to place the cursor.
 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
 * -1 to read the indent size from the line with @a insert_pos on it.
 * @param replace_newlines Whether to replace newlines. If
 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
 * not hard tabs, as those won't be preserved.
 * @note This doesn't scroll the cursor in view afterwards. **/
void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
		gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
{
	ScintillaObject *sci = editor->sci;
	gint line_start = sci_get_line_from_position(sci, insert_pos);
	gint line_end;
	gchar *whitespace;
	GString *buf;
	const gchar cur_marker[] = "__GEANY_CURSOR_MARKER__";
	const gchar *eol = editor_get_eol_char(editor);
	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);

	g_return_if_fail(text);
	g_return_if_fail(editor != NULL);
	g_return_if_fail(insert_pos >= 0);

	buf = g_string_new(text);

	if (cursor_index >= 0)
		g_string_insert(buf, cursor_index, cur_marker);	/* remember cursor pos */

	if (newline_indent_size == -1)
	{
		/* count indent size up to insert_pos instead of asking sci
		 * because there may be spaces after it */
		gchar *tmp = sci_get_line(sci, line_start);
		gint idx = insert_pos - sci_get_position_from_line(sci, line_start);
		tmp[idx] = '\0';
		newline_indent_size = count_indent_size(editor, tmp);
		g_free(tmp);
	}

	/* Add line indents (in spaces) */
	if (newline_indent_size > 0)
	{
		whitespace = g_strnfill(newline_indent_size, ' ');
		setptr(whitespace, g_strconcat(eol, whitespace, NULL));
		utils_string_replace_all(buf, eol, whitespace);
		g_free(whitespace);
	}

	/* transform line endings */
	if (replace_newlines)
		utils_string_replace_all(buf, "\n", eol);

	/* transform leading tabs into indent widths (in spaces) */
	whitespace = g_strnfill(iprefs->width, ' ');
	replace_leading_tabs(buf, whitespace);
	/* remaining tabs are for alignment */
	if (iprefs->type != GEANY_INDENT_TYPE_TABS)
		utils_string_replace_all(buf, "\t", whitespace);
	g_free(whitespace);

	sci_start_undo_action(sci);

	if (cursor_index >= 0)
	{
		gint idx = utils_strpos(buf->str, cur_marker);

		g_string_erase(buf, idx, strlen(cur_marker));

		sci_insert_text(sci, insert_pos, buf->str);
		sci_set_current_position(sci, insert_pos + idx, FALSE);
	}
	else
		sci_insert_text(sci, insert_pos, buf->str);

	/* fixup indentation (very useful for Tabs & Spaces indent type) */
	line_end = sci_get_line_from_position(sci, insert_pos + buf->len);
	fix_line_indents(editor, line_start, line_end);
	snippet_cursor_insert_pos = sci_get_current_position(sci);

	sci_end_undo_action(sci);
	g_string_free(buf, TRUE);
}


/* Move the cursor to the next specified cursor position in an inserted snippet.
 * Can, and should, be optimized to give better results */
void editor_goto_next_snippet_cursor(GeanyEditor *editor)
{
	ScintillaObject *sci = editor->sci;
	gint current_pos = sci_get_current_position(sci);

	if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
	{
		gint offset;

		offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
		if (current_pos > snippet_cursor_insert_pos)
			snippet_cursor_insert_pos = offset + current_pos;
		else
			snippet_cursor_insert_pos += offset;

		sci_set_current_position(sci, snippet_cursor_insert_pos, TRUE);
	}
	else
	{
		utils_beep();
	}
}


static gssize snippets_make_replacements(GeanyEditor *editor, GString *pattern,
		gsize indent_size)
{
	gssize cur_index = -1;
	gchar *whitespace;
	gint i, tmp_pos, whitespace_len, nl_count = 0;
	GHashTable *specials;
	GList *temp_list = NULL;
	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
	gint cursor_steps, old_cursor = 0;

	/* replace 'special' completions */
	specials = g_hash_table_lookup(snippet_hash, "Special");
	if (G_LIKELY(specials != NULL))
	{
		/* ugly hack using global_pattern */
		snippets_global_pattern = pattern;
		g_hash_table_foreach(specials, snippets_replace_specials, NULL);
	}

	/* replace any template {foo} wildcards */
	templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);

	/* transform other wildcards */
	/* convert to %newlines%, else we get endless loops */
	utils_string_replace_all(pattern, "\n", "%newline%");

	/* if spaces are used, replaces all tabs with %ws%, which is later replaced
	 * by real whitespace characters
	 * otherwise replace all %ws% by \t, which will be replaced later by tab
	 * characters,
	 * this makes seperating between tab and spaces intentation pretty easy */
	if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
		utils_string_replace_all(pattern, "\t", "%ws%");
	else
		utils_string_replace_all(pattern, "%ws%", "\t");

	whitespace = g_strnfill(iprefs->width, ' '); /* use spaces for indentation, will be fixed up */
	whitespace_len = strlen(whitespace);
	i = 0;
	while ((cursor_steps = utils_strpos(pattern->str, "%cursor%")) >= 0)
	{
		/* replace every %newline% (up to next %cursor%) with EOL,
		 * and update cursor_steps after */
		while ((tmp_pos = utils_strpos(pattern->str, "%newline%")) < cursor_steps && tmp_pos != -1)
		{
			nl_count++;
			utils_string_replace_first(pattern, "%newline%", editor_get_eol_char(editor));
			cursor_steps = utils_strpos(pattern->str, "%cursor%");
		}
		/* replace every %ws% (up to next %cursor%) with whitespaces,
		 * and update cursor_steps after */
		while ((tmp_pos = utils_strpos(pattern->str, "%ws%")) < cursor_steps && tmp_pos != -1)
		{
			utils_string_replace_first(pattern, "%ws%", whitespace);
			cursor_steps = utils_strpos(pattern->str, "%cursor%");
		}
		/* finally replace the next %cursor% */
		utils_string_replace_first(pattern, "%cursor%", "");

		/* modify cursor_steps to take indentation count and type into account */

		/* We're saving the relative offset to each cursor position in a simple
		 * linked list, including indentations between them. */
		if (i++ > 0)
		{
			cursor_steps += (nl_count * indent_size);
			temp_list = g_list_append(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
		}
		else
		{
			nl_count = 0;
			cur_index = cursor_steps;
		}
		old_cursor = cursor_steps;
	}
	/* replace remaining %ws% and %newline% which may occur after the last %cursor% */
	utils_string_replace_all(pattern, "%newline%", editor_get_eol_char(editor));
	utils_string_replace_all(pattern, "%ws%", whitespace);
	g_free(whitespace);

	/* escape % last */
	/* Bug: {ob}pc{cb} will be replaced by % too */
	templates_replace_valist(pattern, "{pc}", "%", NULL);

	/* We put the cursor positions for the most recent
	 * parsed snippet first, followed by any remaining positions */
	i = 0;
	if (temp_list)
	{
		GList *node;

		foreach_list(node, temp_list)
			g_queue_push_nth(snippet_offsets, node->data, i++);

		/* limit length of queue */
		while (g_queue_get_length(snippet_offsets) > 20)
			g_queue_pop_tail(snippet_offsets);

		g_list_free(temp_list);
	}
	if (cur_index < 0)
		cur_index = pattern->len;

	return cur_index;
}


static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
{
	ScintillaObject *sci = editor->sci;
	gchar *str;
	const gchar *completion;
	gint str_len;
	gint ft_id = editor->document->file_type->id;

	str = g_strdup(word);
	g_strstrip(str);

	completion = snippets_find_completion_by_name(filetypes[ft_id]->name, str);
	if (completion == NULL)
	{
		g_free(str);
		return FALSE;
	}

	/* remove the typed word, it will be added again by the used auto completion
	 * (not really necessary but this makes the auto completion more flexible,
	 *  e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
	str_len = strlen(str);
	sci_set_selection_start(sci, pos - str_len);
	sci_set_selection_end(sci, pos);
	sci_replace_sel(sci, "");
	pos -= str_len; /* pos has changed while deleting */

	editor_insert_snippet(editor, pos, completion);
	sci_scroll_caret(sci);

	g_free(str);
 	return TRUE;
}


static gboolean at_eol(ScintillaObject *sci, gint pos)
{
	gint line = sci_get_line_from_position(sci, pos);
	gchar c;

	/* skip any trailing spaces */
	while (TRUE)
	{
		c = sci_get_char_at(sci, pos);
		if (c == ' ' || c == '\t')
			pos++;
		else
			break;
	}

	return (pos == sci_get_line_end_position(sci, line));
}


gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
{
	gboolean result = FALSE;
	const gchar *wc;
	const gchar *word;
	ScintillaObject *sci;

	g_return_val_if_fail(editor != NULL, FALSE);

	sci = editor->sci;
	if (sci_has_selection(sci))
		return FALSE;
	/* return if we are editing an existing line (chars on right of cursor) */
	if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
			GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
		! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
		return FALSE;

	wc = snippets_find_completion_by_name("Special", "wordchars");
	word = editor_read_word_stem(editor, pos, wc);

	/* prevent completion of "for " */
	if (NZV(word) &&
		! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
	{
		sci_start_undo_action(sci);	/* needed because we insert a space separately from construct */
		result = snippets_complete_constructs(editor, pos, word);
		sci_end_undo_action(sci);
		if (result)
			sci_cancel(sci);	/* cancel any autocompletion list, etc */
	}
	return result;
}


void editor_show_macro_list(GeanyEditor *editor)
{
	GString *words;

	if (editor == NULL || editor->document->file_type == NULL)
		return;

	words = symbols_get_macro_list(editor->document->file_type->lang);
	if (words == NULL)
		return;

	SSM(editor->sci, SCI_USERLISTSHOW, 1, (sptr_t) words->str);
	g_string_free(words, TRUE);
}


static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
{
	ScintillaObject *sci = editor->sci;
	gchar *to_insert = NULL;

	if (ch == '/')
	{
		const gchar *gt = ">";
		/* if there is already a '>' behind the cursor, don't add it */
		if (sci_get_char_at(sci, pos) == '>')
			gt = "";

		to_insert = g_strconcat(tag_name, gt, NULL);
	}
	else
		to_insert = g_strconcat("</", tag_name, ">", NULL);

	sci_start_undo_action(sci);
	sci_replace_sel(sci, to_insert);
	if (ch == '>')
		sci_set_selection(sci, pos, pos);
	sci_end_undo_action(sci);
	g_free(to_insert);
}


/*
 * (stolen from anjuta and heavily modified)
 * This routine will auto complete XML or HTML tags that are still open by closing them
 * @param ch The character we are dealing with, currently only works with the '>' character
 * @return True if handled, false otherwise
 */
static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
{
	ScintillaObject *sci = editor->sci;
	gint lexer = sci_get_lexer(sci);
	gint min, size, style;
	gchar *str_found, sel[512];
	gboolean result = FALSE;

	/* If the user has turned us off, quit now.
	 * This may make sense only in certain languages */
	if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
		return FALSE;

	/* return if we are inside any embedded script */
	style = sci_get_style_at(sci, pos);
	if (style > SCE_H_XCCOMMENT && ! highlighting_is_string_style(lexer, style))
		return FALSE;

	/* if ch is /, check for </, else quit */
	if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
		return FALSE;

	/* Grab the last 512 characters or so */
	min = pos - (sizeof(sel) - 1);
	if (min < 0) min = 0;

	if (pos - min < 3)
		return FALSE; /* Smallest tag is 3 characters e.g. <p> */

	sci_get_text_range(sci, min, pos, sel);
	sel[sizeof(sel) - 1] = '\0';

	if (ch == '>' && sel[pos - min - 2] == '/')
		/* User typed something like "<br/>" */
		return FALSE;

	size = pos - min;
	if (ch == '/')
		size -= 2; /* skip </ */
	str_found = utils_find_open_xml_tag(sel, size);

	if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
	{
		/* ignore tag */
	}
	else if (NZV(str_found))
	{
		insert_closing_tag(editor, pos, ch, str_found);
		result = TRUE;
	}
	g_free(str_found);
	return result;
}


/* like sci_get_line_indentation(), but for a string. */
static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
{
	const gchar *ptr;
	gsize tab_size = sci_get_tab_width(editor->sci);
	gsize count = 0;

	g_return_val_if_fail(base_indent, 0);

	for (ptr = base_indent; *ptr != 0; ptr++)
	{
		switch (*ptr)
		{
			case ' ':
				count++;
				break;
			case '\t':
				count += tab_size;
				break;
			default:
				return count;
		}
	}
	return count;
}


static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
{
	const gchar *eol;
	gchar *str_begin, *str_end, *co, *cc;
	gint line_len;

	g_return_if_fail(editor != NULL && editor->document->file_type != NULL);

	eol = editor_get_eol_char(editor);
	co = editor->document->file_type->comment_open;
	cc = editor->document->file_type->comment_close;
	str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
	str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);

	/* insert the comment strings */
	sci_insert_text(editor->sci, line_start, str_begin);
	line_len = sci_get_position_from_line(editor->sci, last_line + 2);
	sci_insert_text(editor->sci, line_len, str_end);

	g_free(str_begin);
	g_free(str_end);
}


static void real_uncomment_multiline(GeanyEditor *editor)
{
	/* find the beginning of the multi line comment */
	gint pos, line, len, x;
	gchar *linebuf;
	GeanyDocument *doc;

	g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
	doc = editor->document;

	/* remove comment open chars */
	pos = document_find_text(doc, doc->file_type->comment_open, 0, TRUE, FALSE, NULL);
	SSM(editor->sci, SCI_DELETEBACK, 0, 0);

	/* check whether the line is empty and can be deleted */
	line = sci_get_line_from_position(editor->sci, pos);
	len = sci_get_line_length(editor->sci, line);
	linebuf = sci_get_line(editor->sci, line);
	x = 0;
	while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
	if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
	g_free(linebuf);

	/* remove comment close chars */
	pos = document_find_text(doc, doc->file_type->comment_close, 0, FALSE, FALSE, NULL);
	SSM(editor->sci, SCI_DELETEBACK, 0, 0);

	/* check whether the line is empty and can be deleted */
	line = sci_get_line_from_position(editor->sci, pos);
	len = sci_get_line_length(editor->sci, line);
	linebuf = sci_get_line(editor->sci, line);
	x = 0;
	while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
	if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
	g_free(linebuf);
}


static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
{
	gint lexer = sci_get_lexer(editor->sci);
	gint style_comment;

	/* List only those lexers which support multi line comments */
	switch (lexer)
	{
		case SCLEX_XML:
		case SCLEX_HTML:
		{
			if (is_style_php(sci_get_style_at(editor->sci, line_start)))
				style_comment = SCE_HPHP_COMMENT;
			else
				style_comment = SCE_H_COMMENT;
			break;
		}
		case SCLEX_HASKELL: style_comment = SCE_HA_COMMENTBLOCK; break;
		case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
		case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
		case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
		case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
		case SCLEX_D: style_comment = SCE_D_COMMENT; break;
		case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
		default: style_comment = SCE_C_COMMENT;
	}

	return style_comment;
}


/* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
 * returns the amount of uncommented single comment lines, in case of multi line uncomment
 * it returns just 1 */
gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
{
	gint first_line, last_line, eol_char_len;
	gint x, i, line_start, line_len;
	gint sel_start, sel_end;
	gint count = 0;
	gsize co_len;
	gchar sel[256], *co, *cc;
	gboolean break_loop = FALSE, single_line = FALSE;
	GeanyFiletype *ft;

	g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);

	if (line < 0)
	{	/* use selection or current line */
		sel_start = sci_get_selection_start(editor->sci);
		sel_end = sci_get_selection_end(editor->sci);

		first_line = sci_get_line_from_position(editor->sci, sel_start);
		/* Find the last line with chars selected (not EOL char) */
		last_line = sci_get_line_from_position(editor->sci,
			sel_end - editor_get_eol_char_len(editor));
		last_line = MAX(first_line, last_line);
	}
	else
	{
		first_line = last_line = line;
		sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
	}

	ft = editor->document->file_type;
	eol_char_len = editor_get_eol_char_len(editor);

	/* detection of HTML vs PHP code, if non-PHP set filetype to XML */
	line_start = sci_get_position_from_line(editor->sci, first_line);
	if (ft->id == GEANY_FILETYPES_PHP)
	{
		if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
			ft = filetypes[GEANY_FILETYPES_XML];
	}

	co = ft->comment_open;
	cc = ft->comment_close;
	if (co == NULL)
		return 0;

	co_len = strlen(co);
	if (co_len == 0)
		return 0;

	sci_start_undo_action(editor->sci);

	for (i = first_line; (i <= last_line) && (! break_loop); i++)
	{
		gint buf_len;

		line_start = sci_get_position_from_line(editor->sci, i);
		line_len = sci_get_line_length(editor->sci, i);
		x = 0;

		buf_len = MIN((gint)sizeof(sel) - 1, line_len - eol_char_len);
		if (buf_len <= 0)
			continue;
		sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
		sel[buf_len] = '\0';

		while (isspace(sel[x])) x++;

		/* to skip blank lines */
		if (x < line_len && sel[x] != '\0')
		{
			/* use single line comment */
			if (cc == NULL || strlen(cc) == 0)
			{
				single_line = TRUE;

				if (toggle)
				{
					gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
					if (strncmp(sel + x, co, co_len) != 0 ||
						strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
						continue;

					co_len += tm_len;
				}
				else
				{
					if (strncmp(sel + x, co, co_len) != 0)
						continue;
				}

				sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
				sci_replace_sel(editor->sci, "");
				count++;
			}
			/* use multi line comment */
			else
			{
				gint style_comment;

				/* skip lines which are already comments */
				style_comment = get_multiline_comment_style(editor, line_start);
				if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
				{
					real_uncomment_multiline(editor);
					count = 1;
				}

				/* break because we are already on the last line */
				break_loop = TRUE;
				break;
			}
		}
	}
	sci_end_undo_action(editor->sci);

	/* restore selection if there is one
	 * but don't touch the selection if caller is editor_do_comment_toggle */
	if (! toggle && sel_start < sel_end)
	{
		if (single_line)
		{
			sci_set_selection_start(editor->sci, sel_start - co_len);
			sci_set_selection_end(editor->sci, sel_end - (count * co_len));
		}
		else
		{
			gint eol_len = editor_get_eol_char_len(editor);
			sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
			sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
		}
	}

	return count;
}


void editor_do_comment_toggle(GeanyEditor *editor)
{
	gint first_line, last_line, eol_char_len;
	gint x, i, line_start, line_len, first_line_start;
	gint sel_start, sel_end;
	gint count_commented = 0, count_uncommented = 0;
	gchar sel[256], *co, *cc;
	gboolean break_loop = FALSE, single_line = FALSE;
	gboolean first_line_was_comment = FALSE;
	gsize co_len;
	gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
	GeanyFiletype *ft;

	g_return_if_fail(editor != NULL && editor->document->file_type != NULL);

	sel_start = sci_get_selection_start(editor->sci);
	sel_end = sci_get_selection_end(editor->sci);

	ft = editor->document->file_type;
	eol_char_len = editor_get_eol_char_len(editor);

	first_line = sci_get_line_from_position(editor->sci,
		sci_get_selection_start(editor->sci));
	/* Find the last line with chars selected (not EOL char) */
	last_line = sci_get_line_from_position(editor->sci,
		sci_get_selection_end(editor->sci) - editor_get_eol_char_len(editor));
	last_line = MAX(first_line, last_line);

	/* detection of HTML vs PHP code, if non-PHP set filetype to XML */
	first_line_start = sci_get_position_from_line(editor->sci, first_line);
	if (ft->id == GEANY_FILETYPES_PHP)
	{
		if (! is_style_php(sci_get_style_at(editor->sci, first_line_start)))
			ft = filetypes[GEANY_FILETYPES_XML];
	}

	co = ft->comment_open;
	cc = ft->comment_close;
	if (co == NULL)
		return;

	co_len = strlen(co);
	if (co_len == 0)
		return;

	sci_start_undo_action(editor->sci);

	for (i = first_line; (i <= last_line) && (! break_loop); i++)
	{
		gint buf_len;

		line_start = sci_get_position_from_line(editor->sci, i);
		line_len = sci_get_line_length(editor->sci, i);
		x = 0;

		buf_len = MIN((gint)sizeof(sel) - 1, line_len - eol_char_len);
		if (buf_len < 0)
			continue;
		sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
		sel[buf_len] = '\0';

		while (isspace(sel[x])) x++;

		/* use single line comment */
		if (cc == NULL || strlen(cc) == 0)
		{
			gboolean do_continue = FALSE;
			single_line = TRUE;

			if (strncmp(sel + x, co, co_len) == 0 &&
				strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
			{
				do_continue = TRUE;
			}

			if (do_continue && i == first_line)
				first_line_was_comment = TRUE;

			if (do_continue)
			{
				count_uncommented += editor_do_uncomment(editor, i, TRUE);
				continue;
			}

			/* we are still here, so the above lines were not already comments, so comment it */
			editor_do_comment(editor, i, TRUE, TRUE);
			count_commented++;
		}
		/* use multi line comment */
		else
		{
			gint style_comment;

			/* skip lines which are already comments */
			style_comment = get_multiline_comment_style(editor, line_start);
			if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
			{
				real_uncomment_multiline(editor);
				count_uncommented++;
			}
			else
			{
				real_comment_multiline(editor, line_start, last_line);
				count_commented++;
			}

			/* break because we are already on the last line */
			break_loop = TRUE;
			break;
		}
	}

	sci_end_undo_action(editor->sci);

	co_len += tm_len;

	/* restore selection if there is one */
	if (sel_start < sel_end)
	{
		if (single_line)
		{
			gint a = (first_line_was_comment) ? - co_len : co_len;

			/* don't modify sel_start when the selection starts within indentation */
			read_indent(editor, sel_start);
			if ((sel_start - first_line_start) <= (gint) strlen(indent))
				a = 0;

			sci_set_selection_start(editor->sci, sel_start + a);
			sci_set_selection_end(editor->sci, sel_end +
								(count_commented * co_len) - (count_uncommented * co_len));
		}
		else
		{
			gint eol_len = editor_get_eol_char_len(editor);
			if (count_uncommented > 0)
			{
				sci_set_selection_start(editor->sci, sel_start - co_len + eol_len);
				sci_set_selection_end(editor->sci, sel_end - co_len + eol_len);
			}
			else if (count_commented > 0)
			{
				sci_set_selection_start(editor->sci, sel_start + co_len - eol_len);
				sci_set_selection_end(editor->sci, sel_end + co_len - eol_len);
			}
		}
	}
	else if (count_uncommented > 0)
	{
		gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
		sci_set_current_position(editor->sci, sel_start - co_len + eol_len, TRUE);
	}
	else if (count_commented > 0)
	{
		gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
		sci_set_current_position(editor->sci, sel_start + co_len - eol_len, TRUE);
	}
}


/* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
void editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle)
{
	gint first_line, last_line, eol_char_len;
	gint x, i, line_start, line_len;
	gint sel_start, sel_end, co_len;
	gchar sel[256], *co, *cc;
	gboolean break_loop = FALSE, single_line = FALSE;
	GeanyFiletype *ft;

	g_return_if_fail(editor != NULL && editor->document->file_type != NULL);

	if (line < 0)
	{	/* use selection or current line */
		sel_start = sci_get_selection_start(editor->sci);
		sel_end = sci_get_selection_end(editor->sci);

		first_line = sci_get_line_from_position(editor->sci, sel_start);
		/* Find the last line with chars selected (not EOL char) */
		last_line = sci_get_line_from_position(editor->sci,
			sel_end - editor_get_eol_char_len(editor));
		last_line = MAX(first_line, last_line);
	}
	else
	{
		first_line = last_line = line;
		sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
	}

	ft = editor->document->file_type;
	eol_char_len = editor_get_eol_char_len(editor);

	/* detection of HTML vs PHP code, if non-PHP set filetype to XML */
	line_start = sci_get_position_from_line(editor->sci, first_line);
	if (ft->id == GEANY_FILETYPES_PHP)
	{
		if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
			ft = filetypes[GEANY_FILETYPES_XML];
	}

	co = ft->comment_open;
	cc = ft->comment_close;
	if (co == NULL)
		return;

	co_len = strlen(co);
	if (co_len == 0)
		return;

	sci_start_undo_action(editor->sci);

	for (i = first_line; (i <= last_line) && (! break_loop); i++)
	{
		gint buf_len;

		line_start = sci_get_position_from_line(editor->sci, i);
		line_len = sci_get_line_length(editor->sci, i);
		x = 0;

		buf_len = MIN((gint)sizeof(sel) - 1, line_len - eol_char_len);
		if (buf_len < 0)
			continue;
		sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
		sel[buf_len] = '\0';

		while (isspace(sel[x])) x++;

		/* to skip blank lines */
		if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
		{
			/* use single line comment */
			if (cc == NULL || strlen(cc) == 0)
			{
				gint start = line_start;
				single_line = TRUE;

				if (ft->comment_use_indent)
					start = line_start + x;

				if (toggle)
				{
					gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
					sci_insert_text(editor->sci, start, text);
					g_free(text);
				}
				else
					sci_insert_text(editor->sci, start, co);
			}
			/* use multi line comment */
			else
			{
				gint style_comment;

				/* skip lines which are already comments */
				style_comment = get_multiline_comment_style(editor, line_start);
				if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
					continue;

				real_comment_multiline(editor, line_start, last_line);

				/* break because we are already on the last line */
				break_loop = TRUE;
				break;
			}
		}
	}
	sci_end_undo_action(editor->sci);

	/* restore selection if there is one
	 * but don't touch the selection if caller is editor_do_comment_toggle */
	if (! toggle && sel_start < sel_end)
	{
		if (single_line)
		{
			sci_set_selection_start(editor->sci, sel_start + co_len);
			sci_set_selection_end(editor->sci, sel_end + ((i - first_line) * co_len));
		}
		else
		{
			gint eol_len = editor_get_eol_char_len(editor);
			sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
			sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
		}
	}
}


static gboolean brace_timeout_active = FALSE;

static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
{
	GeanyDocument *doc = document_get_current();
	GeanyEditor *editor;
	gint brace_pos = GPOINTER_TO_INT(user_data);
	gint end_pos, cur_pos;

	brace_timeout_active = FALSE;
	if (!doc)
		return FALSE;

	editor = doc->editor;
	cur_pos = sci_get_current_position(editor->sci) - 1;

	if (cur_pos != brace_pos)
	{
		cur_pos++;
		if (cur_pos != brace_pos)
		{
			/* we have moved past the original brace_pos, but after the timeout
			 * we may now be on a new brace, so check again */
			editor_highlight_braces(editor, cur_pos);
			return FALSE;
		}
	}
	if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
	{
		editor_highlight_braces(editor, cur_pos);
		return FALSE;
	}
	end_pos = sci_find_matching_brace(editor->sci, brace_pos);

	if (end_pos >= 0)
	{
		gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
			sci_get_col_from_position(editor->sci, end_pos));
		SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
		SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
	}
	else
	{
		SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
		SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
	}
	return FALSE;
}


static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
{
	gint brace_pos = cur_pos - 1;

	SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
	SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);

	if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
	{
		brace_pos++;
		if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
		{
			return;
		}
	}
	if (!brace_timeout_active)
	{
		brace_timeout_active = TRUE;
		/* delaying matching makes scrolling faster e.g. holding down arrow keys */
		g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
	}
}


static gboolean in_block_comment(gint lexer, gint style)
{
	switch (lexer)
	{
		case SCLEX_CPP:
			return (style == SCE_C_COMMENT ||
				style == SCE_C_COMMENTDOC);

		case SCLEX_PASCAL:
			return (style == SCE_PAS_COMMENT ||
				style == SCE_PAS_COMMENT2);

		case SCLEX_D:
			return (style == SCE_D_COMMENT ||
				style == SCE_D_COMMENTDOC ||
				style == SCE_D_COMMENTNESTED);

		case SCLEX_HTML:
			return (style == SCE_HPHP_COMMENT);

		case SCLEX_CSS:
			return (style == SCE_CSS_COMMENT);

		default:
			return FALSE;
	}
}


static gboolean is_comment_char(gchar c, gint lexer)
{
	if ((c == '*' || c == '+') && lexer == SCLEX_D)
		return TRUE;
	else
	if (c == '*')
		return TRUE;

	return FALSE;
}


static void auto_multiline(GeanyEditor *editor, gint cur_line)
{
	ScintillaObject *sci = editor->sci;
	gint indent_pos, style;
	gint lexer = sci_get_lexer(sci);

	/* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
	indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
	style = sci_get_style_at(sci, indent_pos);
	if (!in_block_comment(lexer, style))
		return;

	/* Check whether the comment block continues on this line */
	indent_pos = sci_get_line_indent_position(sci, cur_line);
	if (sci_get_style_at(sci, indent_pos) == style)
	{
		gchar *previous_line = sci_get_line(sci, cur_line - 1);
		/* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
		gchar *continuation = "*";
		gchar *whitespace = ""; /* to hold whitespace if needed */
		gchar *result;
		gint len = strlen(previous_line);
		gint i;

		/* find and stop at end of multi line comment */
		i = len - 1;
		while (i >= 0 && isspace(previous_line[i])) i--;
		if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
		{
			gint indent_len, indent_width;

			indent_pos = sci_get_line_indent_position(sci, cur_line);
			indent_len = sci_get_col_from_position(sci, indent_pos);
			indent_width = editor_get_indent_prefs(editor)->width;

			/* if there is one too many spaces, delete the last space,
			 * to return to the indent used before the multiline comment was started. */
			if (indent_len % indent_width == 1)
				SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0);	/* remove whitespace indent */
			g_free(previous_line);
			return;
		}
		/* check whether we are on the second line of multi line comment */
		i = 0;
		while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */

		if (i + 1 < len &&
			previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
		{ /* we are on the second line of a multi line comment, so we have to insert white space */
			whitespace = " ";
		}

		if (G_UNLIKELY(style == SCE_D_COMMENTNESTED))
			continuation = "+"; /* for nested comments in D */

		result = g_strconcat(whitespace, continuation, " ", NULL);
		sci_add_text(sci, result);
		g_free(result);

		g_free(previous_line);
	}
}


#if 0
static gboolean editor_lexer_is_c_like(gint lexer)
{
	switch (lexer)
	{
		case SCLEX_CPP:
		case SCLEX_D:
		return TRUE;

		default:
		return FALSE;
	}
}
#endif


/* Returns: -1 if lexer doesn't support type keywords */
gint editor_lexer_get_type_keyword_idx(gint lexer)
{
	switch (lexer)
	{
		case SCLEX_CPP:
		case SCLEX_D:
		return 3;

		default:
		return -1;
	}
}


/* inserts a three-line comment at one line above current cursor position */
void editor_insert_multiline_comment(GeanyEditor *editor)
{
	gchar *text;
	gint text_len;
	gint line;
	gint pos;
	gboolean have_multiline_comment = FALSE;
	GeanyDocument *doc;

	g_return_if_fail(editor != NULL &&
		editor->document->file_type != NULL && editor->document->file_type->comment_open != NULL);

	sci_start_undo_action(editor->sci);

	doc = editor->document;

	if (doc->file_type->comment_close != NULL && strlen(doc->file_type->comment_close) > 0)
		have_multiline_comment = TRUE;

	/* insert three lines one line above of the current position */
	line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
	pos = sci_get_position_from_line(editor->sci, line);

	/* use the indent on the current line but only when comment indentation is used
	 * and we don't have multi line comment characters */
	if (editor->auto_indent &&
		! have_multiline_comment &&	doc->file_type->comment_use_indent)
	{
		read_indent(editor, editor_info.click_pos);
		text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
		text_len = strlen(text);
	}
	else
	{
		text = g_strdup("\n\n\n");
		text_len = 3;
	}
	sci_insert_text(editor->sci, pos, text);
	g_free(text);

	/* select the inserted lines for commenting */
	sci_set_selection_start(editor->sci, pos);
	sci_set_selection_end(editor->sci, pos + text_len);

	editor_do_comment(editor, -1, TRUE, FALSE);

	/* set the current position to the start of the first inserted line */
	pos += strlen(doc->file_type->comment_open);

	/* on multi line comment jump to the next line, otherwise add the length of added indentation */
	if (have_multiline_comment)
		pos += 1;
	else
		pos += strlen(indent);

	sci_set_current_position(editor->sci, pos, TRUE);
	/* reset the selection */
	sci_set_anchor(editor->sci, pos);

	sci_end_undo_action(editor->sci);
}


/* Note: If the editor is pending a redraw, set document::scroll_percent instead.
 * Scroll the view to make line appear at percent_of_view.
 * line can be -1 to use the current position. */
void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
{
	gint los;
	GtkWidget *wid;

	g_return_if_fail(editor != NULL);

	wid = GTK_WIDGET(editor->sci);

	if (! wid->window || ! gdk_window_is_viewable(wid->window))
		return;	/* prevent gdk_window_scroll warning */

	if (line == -1)
		line = sci_get_current_line(editor->sci);

	/* sci 'visible line' != doc line number because of folding and line wrapping */
	/* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
	 * SCI_DOCLINEFROMVISIBLE for vis1. */
	line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
	los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
	line = line - los * percent_of_view;
	SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
	sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
}


/* creates and inserts one tab or whitespace of the amount of the tab width */
void editor_insert_alternative_whitespace(GeanyEditor *editor)
{
	gchar *text;
	GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);

	g_return_if_fail(editor != NULL);

	switch (iprefs.type)
	{
		case GEANY_INDENT_TYPE_TABS:
			iprefs.type = GEANY_INDENT_TYPE_SPACES;
			break;
		case GEANY_INDENT_TYPE_SPACES:
		case GEANY_INDENT_TYPE_BOTH:	/* most likely we want a tab */
			iprefs.type = GEANY_INDENT_TYPE_TABS;
			break;
	}
	text = get_whitespace(&iprefs, iprefs.width);
	sci_add_text(editor->sci, text);
	g_free(text);
}


void editor_select_word(GeanyEditor *editor)
{
	gint pos;
	gint start;
	gint end;

	g_return_if_fail(editor != NULL);

	pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
	start = SSM(editor->sci, SCI_WORDSTARTPOSITION, pos, TRUE);
	end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, TRUE);

	if (start == end) /* caret in whitespaces sequence */
	{
		/* look forward but reverse the selection direction,
		 * so the caret end up stay as near as the original position. */
		end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, FALSE);
		start = SSM(editor->sci, SCI_WORDENDPOSITION, end, TRUE);
		if (start == end)
			return;
	}

	sci_set_selection(editor->sci, start, end);
}


/* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
 * when those lines have no selection (cursor at start of line). */
void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
{
	gint start, end, line;

	g_return_if_fail(editor != NULL);

	start = sci_get_selection_start(editor->sci);
	end = sci_get_selection_end(editor->sci);

	/* check if whole lines are already selected */
	if (! extra_line && start != end &&
		sci_get_col_from_position(editor->sci, start) == 0 &&
		sci_get_col_from_position(editor->sci, end) == 0)
			return;

	line = sci_get_line_from_position(editor->sci, start);
	start = sci_get_position_from_line(editor->sci, line);

	line = sci_get_line_from_position(editor->sci, end);
	end = sci_get_position_from_line(editor->sci, line + 1);

	sci_set_selection(editor->sci, start, end);
}


static gboolean sci_is_blank_line(ScintillaObject *sci, gint line)
{
	return sci_get_line_indent_position(sci, line) ==
		sci_get_line_end_position(sci, line);
}


/* Returns first line of paragraph for GTK_DIR_UP, line after paragraph
 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
{
	gint step;
	ScintillaObject *sci = editor->sci;

	/* first check current line and return -1 if it is empty to skip creating of a selection */
	if (sci_is_blank_line(sci, line))
		return -1;

	if (direction == GTK_DIR_UP)
		step = -1;
	else
		step = 1;

	while (TRUE)
	{
		line += step;
		if (line == -1)
		{
			/* start of document */
			line = 0;
			break;
		}
		if (line == sci_get_line_count(sci))
			break;

		if (sci_is_blank_line(sci, line))
		{
			/* return line paragraph starts on */
			if (direction == GTK_DIR_UP)
				line++;
			break;
		}
	}
	return line;
}


void editor_select_paragraph(GeanyEditor *editor)
{
	gint pos_start, pos_end, line_start, line_found;

	g_return_if_fail(editor != NULL);

	line_start = sci_get_current_line(editor->sci);

	line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
	if (line_found == -1)
		return;

	pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);

	line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
	pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);

	sci_set_selection(editor->sci, pos_start, pos_end);
}


/* Returns first line of block for GTK_DIR_UP, line after block
 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
static gint find_block_stop(GeanyEditor *editor, gint line, gint direction)
{
	gint step, ind;
	ScintillaObject *sci = editor->sci;

	/* first check current line and return -1 if it is empty to skip creating of a selection */
	if (sci_is_blank_line(sci, line))
		return -1;

	if (direction == GTK_DIR_UP)
		step = -1;
	else
		step = 1;

	ind = sci_get_line_indentation(sci, line);
	while (TRUE)
	{
		line += step;
		if (line == -1)
		{
			/* start of document */
			line = 0;
			break;
		}
		if (line == sci_get_line_count(sci))
			break;

		if (sci_get_line_indentation(sci, line) != ind ||
			sci_is_blank_line(sci, line))
		{
			/* return line block starts on */
			if (direction == GTK_DIR_UP)
				line++;
			break;
		}
	}
	return line;
}


void editor_select_indent_block(GeanyEditor *editor)
{
	gint pos_start, pos_end, line_start, line_found;

	g_return_if_fail(editor != NULL);

	line_start = sci_get_current_line(editor->sci);

	line_found = find_block_stop(editor, line_start, GTK_DIR_UP);
	if (line_found == -1)
		return;

	pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);

	line_found = find_block_stop(editor, line_start, GTK_DIR_DOWN);
	pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);

	sci_set_selection(editor->sci, pos_start, pos_end);
}


/* simple indentation to indent the current line with the same indent as the previous one */
static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
{
	gint i, sel_start = 0, sel_end = 0;

	/* get previous line and use it for read_indent to use that line
	 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
	read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));

	for (i = first_line; i <= last_line; i++)
	{
		/* skip the first line or if the indentation of the previous and current line are equal */
		if (i == 0 ||
			SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
			SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
			continue;

		sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
		sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
		if (sel_start < sel_end)
		{
			sci_set_selection(editor->sci, sel_start, sel_end);
			sci_replace_sel(editor->sci, "");
		}
		sci_insert_text(editor->sci, sel_start, indent);
	}
}


/* simple indentation to indent the current line with the same indent as the previous one */
void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
{
	gint first_line, last_line;
	gint first_sel_start, first_sel_end;
	ScintillaObject *sci;

	g_return_if_fail(editor != NULL);

	sci = editor->sci;

	first_sel_start = sci_get_selection_start(sci);
	first_sel_end = sci_get_selection_end(sci);

	first_line = sci_get_line_from_position(sci, first_sel_start);
	/* Find the last line with chars selected (not EOL char) */
	last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
	last_line = MAX(first_line, last_line);

	if (pos == -1)
		pos = first_sel_start;

	sci_start_undo_action(sci);

	smart_line_indentation(editor, first_line, last_line);

	/* set cursor position if there was no selection */
	if (first_sel_start == first_sel_end)
	{
		gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);

		/* use indent position as user may wish to change indentation afterwards */
		sci_set_current_position(sci, indent_pos, FALSE);
	}
	else
	{
		/* fully select all the lines affected */
		sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
		sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
	}

	sci_end_undo_action(sci);
}


/* increase / decrease current line or selection by one space */
void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
{
	gint i, first_line, last_line, line_start, indentation_end, count = 0;
	gint sel_start, sel_end, first_line_offset = 0;

	g_return_if_fail(editor != NULL);

	sel_start = sci_get_selection_start(editor->sci);
	sel_end = sci_get_selection_end(editor->sci);

	first_line = sci_get_line_from_position(editor->sci, sel_start);
	/* Find the last line with chars selected (not EOL char) */
	last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
	last_line = MAX(first_line, last_line);

	if (pos == -1)
		pos = sel_start;

	sci_start_undo_action(editor->sci);

	for (i = first_line; i <= last_line; i++)
	{
		indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
		if (decrease)
		{
			line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
			/* searching backwards for a space to remove */
			while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
				indentation_end--;

			if (sci_get_char_at(editor->sci, indentation_end) == ' ')
			{
				sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
				sci_replace_sel(editor->sci, "");
				count--;
				if (i == first_line)
					first_line_offset = -1;
			}
		}
		else
		{
			sci_insert_text(editor->sci, indentation_end, " ");
			count++;
			if (i == first_line)
				first_line_offset = 1;
		}
	}

	/* set cursor position */
	if (sel_start < sel_end)
	{
		gint start = sel_start + first_line_offset;
		if (first_line_offset < 0)
			start = MAX(sel_start + first_line_offset,
						SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));

		sci_set_selection_start(editor->sci, start);
		sci_set_selection_end(editor->sci, sel_end + count);
	}
	else
		sci_set_current_position(editor->sci, pos + count, FALSE);

	sci_end_undo_action(editor->sci);
}


void editor_finalize()
{
	scintilla_release_resources();
}


/* wordchars: NULL or a string containing characters to match a word.
 * Returns: the current selection or the current word. */
gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
									const gchar *wordchars)
{
	gchar *s = NULL;

	g_return_val_if_fail(editor != NULL, NULL);

	if (sci_get_lines_selected(editor->sci) == 1)
	{
		gint len = sci_get_selected_text_length(editor->sci);

		s = g_malloc(len + 1);
		sci_get_selected_text(editor->sci, s);
	}
	else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
	{	/* use the word at current cursor position */
		gchar word[GEANY_MAX_WORD_LENGTH];

		editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
		if (word[0] != '\0')
			s = g_strdup(word);
	}
	return s;
}


/* Note: Usually the line should be made visible (not folded) before calling this.
 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
 * outside the *vertical* view.
 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
 * sci_scroll_caret() when this returns TRUE. */
gboolean editor_line_in_view(GeanyEditor *editor, gint line)
{
	gint vis1, los;

	g_return_val_if_fail(editor != NULL, FALSE);

	/* If line is wrapped the result may occur on another virtual line than the first and may be
	 * still hidden, so increase the line number to check for the next document line */
	if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
		line++;

	line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);	/* convert to visible line number */
	vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
	los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);

	return (line >= vis1 && line < vis1 + los);
}


/* If the current line is outside the current view window, scroll the line
 * so it appears at percent_of_view. */
void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
{
	gint line;

	g_return_if_fail(editor != NULL);

	line = sci_get_current_line(editor->sci);

	/* unfold maybe folded results */
	sci_ensure_line_is_visible(editor->sci, line);

	/* scroll the line if it's off screen */
	if (! editor_line_in_view(editor, line))
		editor->scroll_percent = percent_of_view;
	else
		sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
}


 /*
 *  Deletes all currently set indicators in the @a editor window.
 *  Error indicators (red squiggly underlines) and usual line markers are removed.
 *
 *  @param editor The editor to operate on.
 */
void editor_indicator_clear_errors(GeanyEditor *editor)
{
	editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
	sci_marker_delete_all(editor->sci, 0);	/* remove the yellow error line marker */
}


/**
 *  Deletes all currently set indicators matching @a indic in the @a editor window.
 *
 *  @param editor The editor to operate on.
 *  @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
 *
 *  @since 0.16
 */
void editor_indicator_clear(GeanyEditor *editor, gint indic)
{
	glong last_pos;

	g_return_if_fail(editor != NULL);

	last_pos = sci_get_length(editor->sci);
	if (last_pos > 0)
	{
		sci_indicator_set(editor->sci, indic);
		sci_indicator_clear(editor->sci, 0, last_pos);
	}
}


/**
 *  Sets an indicator @a indic on @a line.
 *  Whitespace at the start and the end of the line is not marked.
 *
 *  @param editor The editor to operate on.
 *  @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
 *  @param line The line number which should be marked.
 *
 *  @since 0.16
 */
void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
{
	gint start, end;
	guint i = 0, len;
	gchar *linebuf;

	g_return_if_fail(editor != NULL);
	g_return_if_fail(line >= 0);

	start = sci_get_position_from_line(editor->sci, line);
	end = sci_get_position_from_line(editor->sci, line + 1);

	/* skip blank lines */
	if ((start + 1) == end ||
		start > end ||
		sci_get_line_length(editor->sci, line) == editor_get_eol_char_len(editor))
	{
		return;
	}

	len = end - start;
	linebuf = sci_get_line(editor->sci, line);

	/* don't set the indicator on whitespace */
	while (isspace(linebuf[i]))
		i++;
	while (len > 1 && len > i && isspace(linebuf[len - 1]))
	{
		len--;
		end--;
	}
	g_free(linebuf);

	editor_indicator_set_on_range(editor, indic, start + i, end);
}


/**
 *  Sets an indicator on the range specified by @a start and @a end.
 *  No error checking or whitespace removal is performed, this should be done by the calling
 *  function if necessary.
 *
 *  @param editor The editor to operate on.
 *  @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
 *  @param start The starting position for the marker.
 *  @param end The ending position for the marker.
 *
 *  @since 0.16
 */
void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
{
	g_return_if_fail(editor != NULL);
	if (start >= end)
		return;

	sci_indicator_set(editor->sci, indic);
	sci_indicator_fill(editor->sci, start, end - start);
}


/* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
 * the replacement will also start with 0x... */
void editor_insert_color(GeanyEditor *editor, const gchar *colour)
{
	g_return_if_fail(editor != NULL);

	if (sci_has_selection(editor->sci))
	{
		gint start = sci_get_selection_start(editor->sci);
		const gchar *replacement = colour;

		if (sci_get_char_at(editor->sci, start) == '0' &&
			sci_get_char_at(editor->sci, start + 1) == 'x')
		{
			sci_set_selection_start(editor->sci, start + 2);
			sci_set_selection_end(editor->sci, start + 8);
			replacement++; /* skip the leading "0x" */
		}
		else if (sci_get_char_at(editor->sci, start - 1) == '#')
		{	/* double clicking something like #00ffff may only select 00ffff because of wordchars */
			replacement++; /* so skip the '#' to only replace the colour value */
		}
		sci_replace_sel(editor->sci, replacement);
	}
	else
		sci_add_text(editor->sci, colour);
}


/**
 *  Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
 *  If @a editor is @c NULL, the default end of line characters are used.
 *
 *  @param editor The editor to operate on, or @c NULL to query the default value.
 *  @return The used end of line characters mode.
 *
 *  @since 0.20
 */
gint editor_get_eol_char_mode(GeanyEditor *editor)
{
	gint mode = file_prefs.default_eol_character;

	if (editor != NULL)
		mode = sci_get_eol_mode(editor->sci);

	return mode;
}


/**
 *  Retrieves the localized name (for displaying) of the used end of line characters
 *  (LF, CR/LF, CR) in the given editor.
 *  If @a editor is @c NULL, the default end of line characters are used.
 *
 *  @param editor The editor to operate on, or @c NULL to query the default value.
 *  @return The name of the end of line characters.
 *
 *  @since 0.19
 */
const gchar *editor_get_eol_char_name(GeanyEditor *editor)
{
	gint mode = file_prefs.default_eol_character;

	if (editor != NULL)
		mode = sci_get_eol_mode(editor->sci);

	return utils_get_eol_name(mode);
}


/**
 *  Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
 *  If @a editor is @c NULL, the default end of line characters are used.
 *  The returned value is 1 for CR and LF and 2 for CR/LF.
 *
 *  @param editor The editor to operate on, or @c NULL to query the default value.
 *  @return The length of the end of line characters.
 *
 *  @since 0.19
 */
gint editor_get_eol_char_len(GeanyEditor *editor)
{
	gint mode = file_prefs.default_eol_character;

	if (editor != NULL)
		mode = sci_get_eol_mode(editor->sci);

	switch (mode)
	{
		case SC_EOL_CRLF: return 2; break;
		default: return 1; break;
	}
}


/**
 *  Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
 *  If @a editor is @c NULL, the default end of line characters are used.
 *  The returned value is either "\n", "\r\n" or "\r".
 *
 *  @param editor The editor to operate on, or @c NULL to query the default value.
 *  @return The end of line characters.
 *
 *  @since 0.19
 */
const gchar *editor_get_eol_char(GeanyEditor *editor)
{
	gint mode = file_prefs.default_eol_character;

	if (editor != NULL)
		mode = sci_get_eol_mode(editor->sci);

	return utils_get_eol_char(mode);
}


static void fold_all(GeanyEditor *editor, gboolean want_fold)
{
	gint lines, first, i;

	if (editor == NULL || ! editor_prefs.folding)
		return;

	lines = sci_get_line_count(editor->sci);
	first = sci_get_first_visible_line(editor->sci);

	for (i = 0; i < lines; i++)
	{
		gint level = sci_get_fold_level(editor->sci, i);

		if (level & SC_FOLDLEVELHEADERFLAG)
		{
			if (sci_get_fold_expanded(editor->sci, i) == want_fold)
					sci_toggle_fold(editor->sci, i);
		}
	}
	editor_scroll_to_line(editor, first, 0.0F);
}


void editor_unfold_all(GeanyEditor *editor)
{
	fold_all(editor, FALSE);
}


void editor_fold_all(GeanyEditor *editor)
{
	fold_all(editor, TRUE);
}


void editor_replace_tabs(GeanyEditor *editor)
{
	gint search_pos, pos_in_line, current_tab_true_length;
	gint tab_len;
	gchar *tab_str;
	struct Sci_TextToFind ttf;

	g_return_if_fail(editor != NULL);

	sci_start_undo_action(editor->sci);
	tab_len = sci_get_tab_width(editor->sci);
	ttf.chrg.cpMin = 0;
	ttf.chrg.cpMax = sci_get_length(editor->sci);
	ttf.lpstrText = (gchar*) "\t";

	while (TRUE)
	{
		search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
		if (search_pos == -1)
			break;

		pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
		current_tab_true_length = tab_len - (pos_in_line % tab_len);
		tab_str = g_strnfill(current_tab_true_length, ' ');
		sci_set_target_start(editor->sci, search_pos);
		sci_set_target_end(editor->sci, search_pos + 1);
		sci_replace_target(editor->sci, tab_str, FALSE);
		/* next search starts after replacement */
		ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
		/* update end of range now text has changed */
		ttf.chrg.cpMax += current_tab_true_length - 1;
		g_free(tab_str);
	}
	sci_end_undo_action(editor->sci);
}


/* Replaces all occurrences all spaces of the length of a given tab_width. */
void editor_replace_spaces(GeanyEditor *editor)
{
	gint search_pos;
	static gdouble tab_len_f = -1.0; /* keep the last used value */
	gint tab_len;
	struct Sci_TextToFind ttf;

	g_return_if_fail(editor != NULL);

	if (tab_len_f < 0.0)
		tab_len_f = sci_get_tab_width(editor->sci);

	if (! dialogs_show_input_numeric(
		_("Enter Tab Width"),
		_("Enter the amount of spaces which should be replaced by a tab character."),
		&tab_len_f, 1, 100, 1))
	{
		return;
	}
	tab_len = (gint) tab_len_f;

	sci_start_undo_action(editor->sci);
	ttf.chrg.cpMin = 0;
	ttf.chrg.cpMax = sci_get_length(editor->sci);
	ttf.lpstrText = g_strnfill(tab_len, ' ');

	while (TRUE)
	{
		search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
		if (search_pos == -1)
			break;

		sci_set_target_start(editor->sci, search_pos);
		sci_set_target_end(editor->sci, search_pos + tab_len);
		sci_replace_target(editor->sci, "\t", FALSE);
		ttf.chrg.cpMin = search_pos;
		/* update end of range now text has changed */
		ttf.chrg.cpMax -= tab_len - 1;
	}
	sci_end_undo_action(editor->sci);
	g_free(ttf.lpstrText);
}


void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
{
	gint line_start = sci_get_position_from_line(editor->sci, line);
	gint line_end = sci_get_line_end_position(editor->sci, line);
	gint i = line_end - 1;
	gchar ch = sci_get_char_at(editor->sci, i);

	while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
	{
		i--;
		ch = sci_get_char_at(editor->sci, i);
	}
	if (i < (line_end - 1))
	{
		sci_set_target_start(editor->sci, i + 1);
		sci_set_target_end(editor->sci, line_end);
		sci_replace_target(editor->sci, "", FALSE);
	}
}


void editor_strip_trailing_spaces(GeanyEditor *editor)
{
	gint max_lines = sci_get_line_count(editor->sci);
	gint line;

	sci_start_undo_action(editor->sci);

	for (line = 0; line < max_lines; line++)
	{
		editor_strip_line_trailing_spaces(editor, line);
	}
	sci_end_undo_action(editor->sci);
}


void editor_ensure_final_newline(GeanyEditor *editor)
{
	gint max_lines = sci_get_line_count(editor->sci);
	gboolean append_newline = (max_lines == 1);
	gint end_document = sci_get_position_from_line(editor->sci, max_lines);

	if (max_lines > 1)
	{
		append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
	}
	if (append_newline)
	{
		const gchar *eol = editor_get_eol_char(editor);

		sci_insert_text(editor->sci, end_document, eol);
	}
}


void editor_set_font(GeanyEditor *editor, const gchar *font)
{
	gint style, size;
	gchar *font_name;
	PangoFontDescription *pfd;

	g_return_if_fail(editor);

	pfd = pango_font_description_from_string(font);
	size = pango_font_description_get_size(pfd) / PANGO_SCALE;
	font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
	pango_font_description_free(pfd);

	for (style = 0; style <= 127; style++)
		sci_set_font(editor->sci, style, font_name, size);

	/* line number and braces */
	sci_set_font(editor->sci, STYLE_LINENUMBER, font_name, size);
	sci_set_font(editor->sci, STYLE_BRACELIGHT, font_name, size);
	sci_set_font(editor->sci, STYLE_BRACEBAD, font_name, size);
	g_free(font_name);

	/* zoom to 100% to prevent confusion */
	sci_zoom_off(editor->sci);
}


void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
{
	g_return_if_fail(editor != NULL);

	editor->line_wrapping = wrap;
	sci_set_lines_wrapped(editor->sci, wrap);
}


/** Sets the indent type for @a editor.
 * @param editor Editor.
 * @param type Indent type.
 *
 *  @since 0.16
 */
void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
{
	editor_set_indent(editor, type, editor->indent_width);
}


void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
{
	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
	ScintillaObject *sci = editor->sci;
	gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;

	editor->indent_type = type;
	editor->indent_width = width;
	sci_set_use_tabs(sci, use_tabs);

	if (type == GEANY_INDENT_TYPE_BOTH)
	{
		sci_set_tab_width(sci, iprefs->hard_tab_width);
		if (iprefs->hard_tab_width != 8)
		{
			static gboolean warn = TRUE;
			if (warn)
				ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
					iprefs->hard_tab_width);
			warn = FALSE;
		}
	}
	else
		sci_set_tab_width(sci, width);

	SSM(sci, SCI_SETINDENT, width, 0);

	/* remove indent spaces on backspace, if using any spaces to indent */
	SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
}


/* Convenience function for editor_goto_pos() to pass in a line number. */
gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
{
	gint pos;

	g_return_val_if_fail(editor, FALSE);
	if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
		return FALSE;

	if (offset != 0)
	{
		gint current_line = sci_get_current_line(editor->sci);
		line_no *= offset;
		line_no = current_line + line_no;
	}

	pos = sci_get_position_from_line(editor->sci, line_no);
	return editor_goto_pos(editor, pos, TRUE);
}


/** Moves to position @a pos, switching to the document if necessary,
 *  setting a marker if @a mark is set.
 *
 * @param editor Editor.
 * @param pos The position.
 * @param mark Whether to set a mark on the position.
 * @return @c TRUE if action has been performed, otherwise @c FALSE.
 *
 *  @since 0.20
 **/
gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
{
	gint page_num;

	g_return_val_if_fail(editor, FALSE);
	if (G_UNLIKELY(pos < 0))
		return FALSE;

	if (mark)
	{
		gint line = sci_get_line_from_position(editor->sci, pos);

		/* mark the tag with the yellow arrow */
		sci_marker_delete_all(editor->sci, 0);
		sci_set_marker_at_line(editor->sci, line, 0);
	}

	sci_goto_pos(editor->sci, pos, TRUE);
	editor->scroll_percent = 0.25F;

	/* finally switch to the page */
	page_num = gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), GTK_WIDGET(editor->sci));
	gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);

	return TRUE;
}


static gboolean
on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
{
	GeanyEditor *editor = user_data;

	/* Handle scroll events if Alt is pressed and scroll whole pages instead of a
	 * few lines only, maybe this could/should be done in Scintilla directly */
	if (event->state & GDK_MOD1_MASK)
	{
		sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
		return TRUE;
	}
	else if (event->state & GDK_SHIFT_MASK)
	{
		gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;

		sci_scroll_columns(editor->sci, amount);
		return TRUE;
	}

	return FALSE; /* let Scintilla handle all other cases */
}


static gboolean editor_check_colourise(GeanyEditor *editor)
{
	GeanyDocument *doc = editor->document;

	if (!doc->priv->colourise_needed)
		return FALSE;

	doc->priv->colourise_needed = FALSE;
	sci_colourise(editor->sci, 0, -1);

	/* now that the current document is colourised, fold points are now accurate,
	 * so force an update of the current function/tag. */
	symbols_get_current_function(NULL, NULL);
	ui_update_statusbar(NULL, -1);

	return TRUE;
}


/* We only want to colourise just before drawing, to save startup time and
 * prevent unnecessary recolouring other documents after one is saved.
 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
 * and "show" doesn't work). */
static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
{
	GeanyEditor *editor = user_data;

	editor_check_colourise(editor);
	return FALSE;
}


static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
		gpointer user_data)
{
	GeanyEditor *editor = user_data;

	/* This is just to catch any uncolourised documents being drawn that didn't receive focus
	 * for some reason, maybe it's not necessary but just in case. */
	editor_check_colourise(editor);
	return FALSE;
}


static void setup_sci_keys(ScintillaObject *sci)
{
	/* disable some Scintilla keybindings to be able to redefine them cleanly */
	sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
	sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
	sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
	sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
	sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
	sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
	sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
	sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
	sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
	sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
	sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
	sci_clear_cmdkey(sci, SCK_HOME); /* line start */
	sci_clear_cmdkey(sci, SCK_END);	/* line end */
	sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16));	/* visual line end */

	if (editor_prefs.use_gtk_word_boundaries)
	{
		/* use GtkEntry-like word boundaries */
		sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
		sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
		sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
	}
	sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
	sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
	sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
	sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
	sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
	sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);

	sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
}


#include "icons/16x16/classviewer-var.xpm"
#include "icons/16x16/classviewer-method.xpm"

/* Create new editor widget (scintilla).
 * @note The @c "sci-notify" signal is connected separately. */
static ScintillaObject *create_new_sci(GeanyEditor *editor)
{
	ScintillaObject	*sci;

	sci = SCINTILLA(scintilla_new());

	gtk_widget_show(GTK_WIDGET(sci));

	sci_set_codepage(sci, SC_CP_UTF8);
	/*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
	/* disable scintilla provided popup menu */
	sci_use_popup(sci, FALSE);

	setup_sci_keys(sci);

	sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
	sci_set_lines_wrapped(sci, editor_prefs.line_wrapping);
	sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
	sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
	/*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
	SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
	SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);

	/* tag autocompletion images */
	SSM(sci, SCI_REGISTERIMAGE, 1, (sptr_t)classviewer_var);
	SSM(sci, SCI_REGISTERIMAGE, 2, (sptr_t)classviewer_method);

	/* necessary for column mode editing, implemented in Scintilla since 2.0 */
	SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);

	/* virtual space */
	SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);

	/* only connect signals if this is for the document notebook, not split window */
	if (editor->sci == NULL)
	{
		g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
		g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
		g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
		g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
		g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
	}
	return sci;
}


/** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
 * @param editor Editor settings.
 * @return The new widget.
 *
 * @since 0.15
 **/
ScintillaObject *editor_create_widget(GeanyEditor *editor)
{
	const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
	ScintillaObject *old, *sci;

	/* temporarily change editor to use the new sci widget */
	old = editor->sci;
	sci = create_new_sci(editor);
	editor->sci = sci;

	editor_set_indent(editor, iprefs->type, iprefs->width);
	editor_set_font(editor, interface_prefs.editor_font);
	editor_apply_update_prefs(editor);

	/* if editor already had a widget, restore it */
	if (old)
		editor->sci = old;
	return sci;
}


GeanyEditor *editor_create(GeanyDocument *doc)
{
	const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
	GeanyEditor *editor = g_new0(GeanyEditor, 1);

	editor->document = doc;
	doc->editor = editor;	/* needed in case some editor functions/callbacks expect it */

	editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
	editor->line_wrapping = editor_prefs.line_wrapping;
	editor->scroll_percent = -1.0F;
	editor->line_breaking = FALSE;

	editor->sci = editor_create_widget(editor);
	return editor;
}


/* in case we need to free some fields in future */
void editor_destroy(GeanyEditor *editor)
{
	g_free(editor);
}


static void on_document_save(GObject *obj, GeanyDocument *doc)
{
	g_return_if_fail(NZV(doc->real_path));

	if (utils_str_equal(doc->real_path,
		utils_build_path(app->configdir, "snippets.conf", NULL)))
	{
		/* reload snippets */
		editor_snippets_free();
		editor_snippets_init();
	}
}


gboolean editor_complete_word_part(GeanyEditor *editor)
{
	gchar *entry;

	g_return_val_if_fail(editor, FALSE);

	if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
		return FALSE;

	entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);

	/* if no word part, complete normally */
	if (!check_partial_completion(editor, entry))
		SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);

	g_free(entry);
	return TRUE;
}


void editor_init(void)
{
	static GeanyIndentPrefs indent_prefs;

	memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
	memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
	editor_prefs.indentation = &indent_prefs;

	/* use g_signal_connect_after() to allow plugins connecting to the signal before the default
	 * handler (on_editor_notify) is called */
	g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);

	ui_add_config_file_menu_item(utils_build_path(app->configdir, "snippets.conf", NULL),
		NULL, NULL);
	g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
}


/* TODO: Should these be user-defined instead of hard-coded? */
void editor_set_indentation_guides(GeanyEditor *editor)
{
	gint mode;
	gint lexer;

	g_return_if_fail(editor != NULL);

	if (! editor_prefs.show_indent_guide)
	{
		sci_set_indentation_guides(editor->sci, SC_IV_NONE);
		return;
	}

	lexer = sci_get_lexer(editor->sci);
	switch (lexer)
	{
		/* Lines added/removed are prefixed with +/- characters, so
		 * those lines will not be shown with any indentation guides.
		 * It can be distracting that only a few of lines in a diff/patch
		 * file will show the guides. */
		case SCLEX_DIFF:
			mode = SC_IV_NONE;
			break;

		/* These languages use indentation for control blocks; the "look forward" method works
		 * best here */
		case SCLEX_PYTHON:
		case SCLEX_HASKELL:
		case SCLEX_MAKEFILE:
		case SCLEX_ASM:
		case SCLEX_SQL:
		case SCLEX_PROPERTIES:
		case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
		case SCLEX_CAML:
			mode = SC_IV_LOOKFORWARD;
			break;

		/* C-like (structured) languages benefit from the "look both" method */
		case SCLEX_CPP:
		case SCLEX_HTML:
		case SCLEX_XML:
		case SCLEX_PERL:
		case SCLEX_LATEX:
		case SCLEX_LUA:
		case SCLEX_PASCAL:
		case SCLEX_RUBY:
		case SCLEX_TCL:
		case SCLEX_F77:
		case SCLEX_CSS:
		case SCLEX_BASH:
		case SCLEX_VHDL:
		case SCLEX_FREEBASIC:
		case SCLEX_D:
		case SCLEX_OCTAVE:
			mode = SC_IV_LOOKBOTH;
			break;

		default:
			mode = SC_IV_REAL;
			break;
	}

	sci_set_indentation_guides(editor->sci, mode);
}


/* Apply just the prefs that can change in the Preferences dialog */
void editor_apply_update_prefs(GeanyEditor *editor)
{
	ScintillaObject *sci;

	g_return_if_fail(editor != NULL);

	if (main_status.quitting)
		return;

	sci = editor->sci;

	sci_set_mark_long_lines(sci, editor_get_long_line_type(),
		editor_get_long_line_column(), editor_prefs.long_line_color);

	/* update indent width, tab width */
	editor_set_indent(editor, editor->indent_type, editor->indent_width);
	sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);

	sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
		editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
	sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
		editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);

	sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
	SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);

	editor_set_indentation_guides(editor);

	sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
	sci_set_visible_eols(sci, editor_prefs.show_line_endings);
	sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
	sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);

	sci_set_folding_margin_visible(sci, editor_prefs.folding);

	/* virtual space */
	SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);

	/* (dis)allow scrolling past end of document */
	sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
}


/* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
{
	ScintillaObject *sci = editor->sci;
	gint pos = sci_get_position_from_line(sci, line);

	if (increase)
	{
		sci_insert_text(sci, pos, "\t");
	}
	else
	{
		if (sci_get_char_at(sci, pos) == '\t')
		{
			sci_set_selection(sci, pos, pos + 1);
			sci_replace_sel(sci, "");
		}
		else /* remove spaces only if no tabs */
		{
			gint width = sci_get_line_indentation(sci, line);

			width -= editor_get_indent_prefs(editor)->width;
			sci_set_line_indentation(sci, line, width);
		}
	}
}


static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
{
	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
	ScintillaObject *sci = editor->sci;

	if (iprefs->type == GEANY_INDENT_TYPE_TABS)
		change_tab_indentation(editor, line, increase);
	else
	{
		gint width = sci_get_line_indentation(sci, line);

		width += increase ? iprefs->width : -iprefs->width;
		sci_set_line_indentation(sci, line, width);
	}
}


void editor_indent(GeanyEditor *editor, gboolean increase)
{
	ScintillaObject *sci = editor->sci;
	gint start, end;
	gint line, lstart, lend;

	if (sci_get_lines_selected(sci) <= 1)
	{
		line = sci_get_current_line(sci);
		editor_change_line_indent(editor, line, increase);
		return;
	}
	editor_select_lines(editor, FALSE);
	start = sci_get_selection_start(sci);
	end = sci_get_selection_end(sci);
	lstart = sci_get_line_from_position(sci, start);
	lend = sci_get_line_from_position(sci, end);
	if (end == sci_get_length(sci))
		lend++;	/* for last line with text on it */

	sci_start_undo_action(sci);
	for (line = lstart; line < lend; line++)
	{
		editor_change_line_indent(editor, line, increase);
	}
	sci_end_undo_action(sci);

	/* set cursor/selection */
	if (lend > lstart)
	{
		sci_set_selection_start(sci, start);
		end = sci_get_position_from_line(sci, lend);
		sci_set_selection_end(sci, end);
		editor_select_lines(editor, FALSE);
	}
	else
	{
		sci_set_current_line(sci, lstart);
	}
}


/** Gets snippet by name.
 *
 * If @a editor is passed, returns a snippet specific to the document filetype.
 * If @a editor is @c NULL, returns a snippet from the default set.
 *
 * @param editor Editor or @c NULL.
 * @param snippet_name Snippet name.
 * @return snippet or @c NULL if it was not found. Must not be freed.
 */
const gchar *editor_find_snippet(GeanyEditor *editor, const gchar *snippet_name)
{
	const gchar *subhash_name = editor ? editor->document->file_type->name : "Default";
	GHashTable *subhash = g_hash_table_lookup(snippet_hash, subhash_name);

	return subhash ? g_hash_table_lookup(subhash, snippet_name) : NULL;
}


/** Replaces all special sequences in @a snippet and inserts it at @a pos.
 * If you insert at the current position, consider calling @c sci_scroll_caret()
 * after this function.
 * @param editor .
 * @param pos .
 * @param snippet .
 */
void editor_insert_snippet(GeanyEditor *editor, gint pos, const gchar *snippet)
{
	gint cursor_pos;
	GString *pattern;

	pattern = g_string_new(snippet);
	read_indent(editor, pos);
	cursor_pos = snippets_make_replacements(editor, pattern, strlen(indent));
	editor_insert_text_block(editor, pattern->str, pos, cursor_pos, -1, FALSE);
	g_string_free(pattern, TRUE);
}