File: qsciscintilla.cpp

package info (click to toggle)
monkeystudio 1.9.0.4%2Bgit20161218-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 41,500 kB
  • ctags: 22,118
  • sloc: cpp: 144,671; ansic: 33,969; python: 2,922; makefile: 127; sh: 122; php: 73; cs: 69
file content (4382 lines) | stat: -rw-r--r-- 109,465 bytes parent folder | download
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
// This module implements the "official" high-level API of the Qt port of
// Scintilla.  It is modelled on QTextEdit - a method of the same name should
// behave in the same way.
//
// Copyright (c) 2015 Riverbank Computing Limited <info@riverbankcomputing.com>
// 
// This file is part of QScintilla.
// 
// This file may be used under the terms of the GNU General Public License
// version 3.0 as published by the Free Software Foundation and appearing in
// the file LICENSE included in the packaging of this file.  Please review the
// following information to ensure the GNU General Public License version 3.0
// requirements will be met: http://www.gnu.org/copyleft/gpl.html.
// 
// If you do not wish to use this file under the terms of the GPL version 3.0
// then you may purchase a commercial license.  For more information contact
// info@riverbankcomputing.com.
// 
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.


#include "Qsci/qsciscintilla.h"

#include <string.h>

#include <QAction>
#include <QApplication>
#include <QColor>
#include <QEvent>
#include <QImage>
#include <QIODevice>
#include <QKeyEvent>
#include <QKeySequence>
#include <QMenu>
#include <QPoint>

#include "Qsci/qsciabstractapis.h"
#include "Qsci/qscicommandset.h"
#include "Qsci/qscilexer.h"
#include "Qsci/qscistyle.h"
#include "Qsci/qscistyledtext.h"


// Make sure these match the values in Scintilla.h.  We don't #include that
// file because it just causes more clashes.
#define KEYWORDSET_MAX  8
#define MARKER_MAX      31

// The list separators for auto-completion and user lists.
const char acSeparator = '\x03';
const char userSeparator = '\x04';

// The default fold margin width.
static const int defaultFoldMarginWidth = 14;

// The default set of characters that make up a word.
static const char *defaultWordChars = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";


// The ctor.
QsciScintilla::QsciScintilla(QWidget *parent)
    : QsciScintillaBase(parent),
      allocatedMarkers(0), allocatedIndicators(7), oldPos(-1), selText(false),
      fold(NoFoldStyle), foldmargin(2), autoInd(false),
      braceMode(NoBraceMatch), acSource(AcsNone), acThresh(-1),
      wchars(defaultWordChars), call_tips_position(CallTipsBelowText),
      call_tips_style(CallTipsNoContext), maxCallTips(-1),
      use_single(AcusNever), explicit_fillups(""), fillups_enabled(false)
{
    connect(this,SIGNAL(SCN_MODIFYATTEMPTRO()),
             SIGNAL(modificationAttempted()));

    connect(this,SIGNAL(SCN_MODIFIED(int,int,const char *,int,int,int,int,int,int,int)),
             SLOT(handleModified(int,int,const char *,int,int,int,int,int,int,int)));
    connect(this,SIGNAL(SCN_CALLTIPCLICK(int)),
             SLOT(handleCallTipClick(int)));
    connect(this,SIGNAL(SCN_CHARADDED(int)),
             SLOT(handleCharAdded(int)));
    connect(this,SIGNAL(SCN_INDICATORCLICK(int,int)),
             SLOT(handleIndicatorClick(int,int)));
    connect(this,SIGNAL(SCN_INDICATORRELEASE(int,int)),
             SLOT(handleIndicatorRelease(int,int)));
    connect(this,SIGNAL(SCN_MARGINCLICK(int,int,int)),
             SLOT(handleMarginClick(int,int,int)));
    connect(this,SIGNAL(SCN_SAVEPOINTREACHED()),
             SLOT(handleSavePointReached()));
    connect(this,SIGNAL(SCN_SAVEPOINTLEFT()),
             SLOT(handleSavePointLeft()));
    connect(this,SIGNAL(SCN_UPDATEUI(int)),
             SLOT(handleUpdateUI(int)));
    connect(this,SIGNAL(QSCN_SELCHANGED(bool)),
             SLOT(handleSelectionChanged(bool)));
    connect(this,SIGNAL(SCN_AUTOCSELECTION(const char *,int)),
             SLOT(handleAutoCompletionSelection()));
    connect(this,SIGNAL(SCN_USERLISTSELECTION(const char *,int)),
             SLOT(handleUserListSelection(const char *,int)));

    // Set the default font.
    setFont(QApplication::font());

    // Set the default fore and background colours.
    QPalette pal = QApplication::palette();
    setColor(pal.text().color());
    setPaper(pal.base().color());
    setSelectionForegroundColor(pal.highlightedText().color());
    setSelectionBackgroundColor(pal.highlight().color());

#if defined(Q_OS_WIN)
    setEolMode(EolWindows);
#else
    // Note that EolMac is pre-OS/X.
    setEolMode(EolUnix);
#endif

    // Capturing the mouse seems to cause problems on multi-head systems. Qt
    // should do the right thing anyway.
    SendScintilla(SCI_SETMOUSEDOWNCAPTURES, 0UL);

    setMatchedBraceForegroundColor(Qt::blue);
    setUnmatchedBraceForegroundColor(Qt::red);

    setAnnotationDisplay(AnnotationStandard);
    setLexer();

    // Set the visible policy.  These are the same as SciTE's defaults
    // which, presumably, are sensible.
    SendScintilla(SCI_SETVISIBLEPOLICY, VISIBLE_STRICT | VISIBLE_SLOP, 4);

    // The default behaviour is unexpected.
    SendScintilla(SCI_AUTOCSETCASEINSENSITIVEBEHAVIOUR,
            SC_CASEINSENSITIVEBEHAVIOUR_IGNORECASE);

    // Create the standard command set.
    stdCmds = new QsciCommandSet(this);

    doc.display(this,0);
}


// The dtor.
QsciScintilla::~QsciScintilla()
{
    // Detach any current lexer.
    detachLexer();

    doc.undisplay(this);
    delete stdCmds;
}


// Return the current text colour.
QColor QsciScintilla::color() const
{
    return nl_text_colour;
}


// Set the text colour.
void QsciScintilla::setColor(const QColor &c)
{
    if (lex.isNull())
    {
        // Assume style 0 applies to everything so that we don't need to use
        // SCI_STYLECLEARALL which clears everything.
        SendScintilla(SCI_STYLESETFORE, 0, c);
        nl_text_colour = c;
    }
}


// Return the overwrite mode.
bool QsciScintilla::overwriteMode() const
{
    return SendScintilla(SCI_GETOVERTYPE);
}


// Set the overwrite mode.
void QsciScintilla::setOverwriteMode(bool overwrite)
{
    SendScintilla(SCI_SETOVERTYPE, overwrite);
}


// Return the current paper colour.
QColor QsciScintilla::paper() const
{
    return nl_paper_colour;
}


// Set the paper colour.
void QsciScintilla::setPaper(const QColor &c)
{
    if (lex.isNull())
    {
        // Assume style 0 applies to everything so that we don't need to use
        // SCI_STYLECLEARALL which clears everything.  We still have to set the
        // default style as well for the background without any text.
        SendScintilla(SCI_STYLESETBACK, 0, c);
        SendScintilla(SCI_STYLESETBACK, STYLE_DEFAULT, c);
        nl_paper_colour = c;
    }
}


// Set the default font.
void QsciScintilla::setFont(const QFont &f)
{
    if (lex.isNull())
    {
        // Assume style 0 applies to everything so that we don't need to use
        // SCI_STYLECLEARALL which clears everything.
        setStylesFont(f, 0);
        QWidget::setFont(f);
    }
}


// Enable/disable auto-indent.
void QsciScintilla::setAutoIndent(bool autoindent)
{
    autoInd = autoindent;
}


// Set the brace matching mode.
void QsciScintilla::setBraceMatching(BraceMatch bm)
{
    braceMode = bm;
}


// Handle the addition of a character.
void QsciScintilla::handleCharAdded(int ch)
{
    // Ignore if there is a selection.
    long pos = SendScintilla(SCI_GETSELECTIONSTART);

    if (pos != SendScintilla(SCI_GETSELECTIONEND) || pos == 0)
        return;

    // If auto-completion is already active then see if this character is a
    // start character.  If it is then create a new list which will be a subset
    // of the current one.  The case where it isn't a start character seems to
    // be handled correctly elsewhere.
    if (isListActive() && isStartChar(ch))
    {
        cancelList();
        startAutoCompletion(acSource, false, use_single == AcusAlways);

        return;
    }

    // Handle call tips.
    if (call_tips_style != CallTipsNone && !lex.isNull() && strchr("(),", ch) != NULL)
        callTip();

    // Handle auto-indentation.
    if (autoInd)
        if (lex.isNull() || (lex->autoIndentStyle() & AiMaintain))
            maintainIndentation(ch, pos);
        else
            autoIndentation(ch, pos);

    // See if we might want to start auto-completion.
    if (!isCallTipActive() && acSource != AcsNone)
        if (isStartChar(ch))
            startAutoCompletion(acSource, false, use_single == AcusAlways);
        else if (acThresh >= 1 && isWordCharacter(ch))
            startAutoCompletion(acSource, true, use_single == AcusAlways);
}


// See if a call tip is active.
bool QsciScintilla::isCallTipActive() const
{
    return SendScintilla(SCI_CALLTIPACTIVE);
}


// Handle a possible change to any current call tip.
void QsciScintilla::callTip()
{
    QsciAbstractAPIs *apis = lex->apis();

    if (!apis)
        return;

    int pos, commas = 0;
    bool found = false;
    char ch;

    pos = SendScintilla(SCI_GETCURRENTPOS);

    // Move backwards through the line looking for the start of the current
    // call tip and working out which argument it is.
    while ((ch = getCharacter(pos)) != '\0')
    {
        if (ch == ',')
            ++commas;
        else if (ch == ')')
        {
            int depth = 1;

            // Ignore everything back to the start of the corresponding
            // parenthesis.
            while ((ch = getCharacter(pos)) != '\0')
            {
                if (ch == ')')
                    ++depth;
                else if (ch == '(' && --depth == 0)
                    break;
            }
        }
        else if (ch == '(')
        {
            found = true;
            break;
        }
    }

    // Cancel any existing call tip.
    SendScintilla(SCI_CALLTIPCANCEL);

    // Done if there is no new call tip to set.
    if (!found)
        return;

    QStringList context = apiContext(pos, pos, ctPos);

    if (context.isEmpty())
        return;

    // The last word is complete, not partial.
    context << QString();

    ct_cursor = 0;
    ct_shifts.clear();
    ct_entries = apis->callTips(context, commas, call_tips_style, ct_shifts);

    int nr_entries = ct_entries.count();

    if (nr_entries == 0)
        return;

    if (maxCallTips > 0 && maxCallTips < nr_entries)
    {
        ct_entries = ct_entries.mid(0, maxCallTips);
        nr_entries = maxCallTips;
    }

    int shift;
    QString ct;

    int nr_shifts = ct_shifts.count();

    if (maxCallTips < 0 && nr_entries > 1)
    {
        shift = (nr_shifts > 0 ? ct_shifts.first() : 0);
        ct = ct_entries[0];
        ct.prepend('\002');
    }
    else
    {
        if (nr_shifts > nr_entries)
            nr_shifts = nr_entries;

        // Find the biggest shift.
        shift = 0;

        for (int i = 0; i < nr_shifts; ++i)
        {
            int sh = ct_shifts[i];

            if (shift < sh)
                shift = sh;
        }

        ct = ct_entries.join("\n");
    }

    QByteArray ct_ba = ct.toLatin1();
    const char *cts = ct_ba.data();

    SendScintilla(SCI_CALLTIPSHOW, adjustedCallTipPosition(shift), cts);

    // Done if there is more than one call tip.
    if (nr_entries > 1)
        return;

    // Highlight the current argument.
    const char *astart;

    if (commas == 0)
        astart = strchr(cts, '(');
    else
        for (astart = strchr(cts, ','); astart && --commas > 0; astart = strchr(astart + 1, ','))
            ;

    if (!astart || !*++astart)
        return;

    // The end is at the next comma or unmatched closing parenthesis.
    const char *aend;
    int depth = 0;

    for (aend = astart; *aend; ++aend)
    {
        char ch = *aend;

        if (ch == ',' && depth == 0)
            break;
        else if (ch == '(')
            ++depth;
        else if (ch == ')')
        {
            if (depth == 0)
                break;

            --depth;
        }
    }

    if (astart != aend)
        SendScintilla(SCI_CALLTIPSETHLT, astart - cts, aend - cts);
}


// Handle a call tip click.
void QsciScintilla::handleCallTipClick(int dir)
{
    int nr_entries = ct_entries.count();

    // Move the cursor while bounds checking.
    if (dir == 1)
    {
        if (ct_cursor - 1 < 0)
            return;

        --ct_cursor;
    }
    else if (dir == 2)
    {
        if (ct_cursor + 1 >= nr_entries)
            return;

        ++ct_cursor;
    }
    else
        return;

    int shift = (ct_shifts.count() > ct_cursor ? ct_shifts[ct_cursor] : 0);
    QString ct = ct_entries[ct_cursor];

    // Add the arrows.
    if (ct_cursor < nr_entries - 1)
        ct.prepend('\002');

    if (ct_cursor > 0)
        ct.prepend('\001');

    SendScintilla(SCI_CALLTIPSHOW, adjustedCallTipPosition(shift), ct.toLatin1().data());
}


// Shift the position of the call tip (to take any context into account) but
// don't go before the start of the line.
int QsciScintilla::adjustedCallTipPosition(int ctshift) const
{
    int ct = ctPos;

    if (ctshift)
    {
        int ctmin = SendScintilla(SCI_POSITIONFROMLINE, SendScintilla(SCI_LINEFROMPOSITION, ct));

        if (ct - ctshift < ctmin)
            ct = ctmin;
    }

    return ct;
}


// Return the list of words that make up the context preceding the given
// position.  The list will only have more than one element if there is a lexer
// set and it defines start strings.  If so, then the last element might be
// empty if a start string has just been typed.  On return pos is at the start
// of the context.
QStringList QsciScintilla::apiContext(int pos, int &context_start,
        int &last_word_start)
{
    enum {
        Either,
        Separator,
        Word
    };

    QStringList words;
    int good_pos = pos, expecting = Either;

    last_word_start = -1;

    while (pos > 0)
    {
        if (getSeparator(pos))
        {
            if (expecting == Either)
                words.prepend(QString());
            else if (expecting == Word)
                break;

            good_pos = pos;
            expecting = Word;
        }
        else
        {
            QString word = getWord(pos);

            if (word.isEmpty() || expecting == Separator)
                break;

            words.prepend(word);
            good_pos = pos;
            expecting = Separator;

            // Return the position of the start of the last word if required.
            if (last_word_start < 0)
                last_word_start = pos;
        }

        // Strip any preceding spaces (mainly around operators).
        char ch;

        while ((ch = getCharacter(pos)) != '\0')
        {
            // This is the same definition of space that Scintilla uses.
            if (ch != ' ' && (ch < 0x09 || ch > 0x0d))
            {
                ++pos;
                break;
            }
        }
    }

    // A valid sequence always starts with a word and so should be expecting a
    // separator.
    if (expecting != Separator)
        words.clear();

    context_start = good_pos;

    return words;
}


// Try and get a lexer's word separator from the text before the current
// position.  Return true if one was found and adjust the position accordingly.
bool QsciScintilla::getSeparator(int &pos) const
{
    int opos = pos;

    // Go through each separator.
    for (int i = 0; i < wseps.count(); ++i)
    {
        const QString &ws = wseps[i];

        // Work backwards.
        uint l;

        for (l = ws.length(); l; --l)
        {
            char ch = getCharacter(pos);

            if (ch == '\0' || ws.at(l - 1) != ch)
                break;
        }

        if (!l)
            return true;

        // Reset for the next separator.
        pos = opos;
    }

    return false;
}


// Try and get a word from the text before the current position.  Return the
// word if one was found and adjust the position accordingly.
QString QsciScintilla::getWord(int &pos) const
{
    QString word;
    bool numeric = true;
    char ch;

    while ((ch = getCharacter(pos)) != '\0')
    {
        if (!isWordCharacter(ch))
        {
            ++pos;
            break;
        }

        if (ch < '0' || ch > '9')
            numeric = false;

        word.prepend(ch);
    }

    // We don't auto-complete numbers.
    if (numeric)
        word.truncate(0);

    return word;
}


// Get the "next" character (ie. the one before the current position) in the
// current line.  The character will be '\0' if there are no more.
char QsciScintilla::getCharacter(int &pos) const
{
    if (pos <= 0)
        return '\0';

    char ch = SendScintilla(SCI_GETCHARAT, --pos);

    // Don't go past the end of the previous line.
    if (ch == '\n' || ch == '\r')
    {
        ++pos;
        return '\0';
    }

    return ch;
}


// See if a character is an auto-completion start character, ie. the last
// character of a word separator.
bool QsciScintilla::isStartChar(char ch) const
{
    QString s = QChar(ch);

    for (int i = 0; i < wseps.count(); ++i)
        if (wseps[i].endsWith(s))
            return true;

    return false;
}


// Possibly start auto-completion.
void QsciScintilla::startAutoCompletion(AutoCompletionSource acs,
        bool checkThresh, bool choose_single)
{
    int start, ignore;
    QStringList context = apiContext(SendScintilla(SCI_GETCURRENTPOS), start,
            ignore);

    if (context.isEmpty())
        return;

    // Get the last word's raw data and length.
    ScintillaBytes s = textAsBytes(context.last());
    const char *last_data = ScintillaBytesConstData(s);
    int last_len = s.length();

    if (checkThresh && last_len < acThresh)
        return;

    // Generate the string representing the valid words to select from.
    QStringList wlist;

    if ((acs == AcsAll || acs == AcsAPIs) && !lex.isNull())
    {
        QsciAbstractAPIs *apis = lex->apis();

        if (apis)
            apis->updateAutoCompletionList(context, wlist);
    }

    if (acs == AcsAll || acs == AcsDocument)
    {
        int sflags = SCFIND_WORDSTART;

        if (!SendScintilla(SCI_AUTOCGETIGNORECASE))
            sflags |= SCFIND_MATCHCASE;

        SendScintilla(SCI_SETSEARCHFLAGS, sflags);

        int pos = 0;
        int dlen = SendScintilla(SCI_GETLENGTH);
        int caret = SendScintilla(SCI_GETCURRENTPOS);
        int clen = caret - start;
        char *orig_context = new char[clen + 1];

        SendScintilla(SCI_GETTEXTRANGE, start, caret, orig_context);

        for (;;)
        {
            int fstart;

            SendScintilla(SCI_SETTARGETSTART, pos);
            SendScintilla(SCI_SETTARGETEND, dlen);

            if ((fstart = SendScintilla(SCI_SEARCHINTARGET, clen, orig_context)) < 0)
                break;

            // Move past the root part.
            pos = fstart + clen;

            // Skip if this is the context we are auto-completing.
            if (pos == caret)
                continue;

            // Get the rest of this word.
            QString w = last_data;

            while (pos < dlen)
            {
                char ch = SendScintilla(SCI_GETCHARAT, pos);

                if (!isWordCharacter(ch))
                    break;

                w += ch;
                ++pos;
            }

            // Add the word if it isn't already there.
            if (!w.isEmpty())
            {
                bool keep;

                // If there are APIs then check if the word is already present
                // as an API word (i.e. with a trailing space).
                if (acs == AcsAll)
                {
                    QString api_w = w;
                    api_w.append(' ');

                    keep = !wlist.contains(api_w);
                }
                else
                {
                    keep = true;
                }

                if (keep && !wlist.contains(w))
                    wlist.append(w);
            }
        }

        delete []orig_context;
    }

    if (wlist.isEmpty())
        return;

    wlist.sort();

    SendScintilla(SCI_AUTOCSETCHOOSESINGLE, choose_single);
    SendScintilla(SCI_AUTOCSETSEPARATOR, acSeparator);

    ScintillaBytes wlist_s = textAsBytes(wlist.join(QChar(acSeparator)));
    SendScintilla(SCI_AUTOCSHOW, last_len, ScintillaBytesConstData(wlist_s));
}


// Maintain the indentation of the previous line.
void QsciScintilla::maintainIndentation(char ch, long pos)
{
    if (ch != '\r' && ch != '\n')
        return;

    int curr_line = SendScintilla(SCI_LINEFROMPOSITION, pos);

    // Get the indentation of the preceding non-zero length line.
    int ind = 0;

    for (int line = curr_line - 1; line >= 0; --line)
    {
        if (SendScintilla(SCI_GETLINEENDPOSITION, line) >
            SendScintilla(SCI_POSITIONFROMLINE, line))
        {
            ind = indentation(line);
            break;
        }
    }

    if (ind > 0)
        autoIndentLine(pos, curr_line, ind);
}


// Implement auto-indentation.
void QsciScintilla::autoIndentation(char ch, long pos)
{
    int curr_line = SendScintilla(SCI_LINEFROMPOSITION, pos);
    int ind_width = indentWidth();
    long curr_line_start = SendScintilla(SCI_POSITIONFROMLINE, curr_line);

    const char *block_start = lex->blockStart();
    bool start_single = (block_start && qstrlen(block_start) == 1);

    const char *block_end = lex->blockEnd();
    bool end_single = (block_end && qstrlen(block_end) == 1);

    if (end_single && block_end[0] == ch)
    {
        if (!(lex->autoIndentStyle() & AiClosing) && rangeIsWhitespace(curr_line_start, pos - 1))
            autoIndentLine(pos, curr_line, blockIndent(curr_line - 1) - ind_width);
    }
    else if (start_single && block_start[0] == ch)
    {
        // De-indent if we have already indented because the previous line was
        // a start of block keyword.
        if (!(lex->autoIndentStyle() & AiOpening) && curr_line > 0 && getIndentState(curr_line - 1) == isKeywordStart && rangeIsWhitespace(curr_line_start, pos - 1))
            autoIndentLine(pos, curr_line, blockIndent(curr_line - 1) - ind_width);
    }
    else if (ch == '\r' || ch == '\n')
    {
        // Don't auto-indent the line (ie. preserve its existing indentation)
        // if we have inserted a new line above by pressing return at the start
        // of this line - in other words, if the previous line is empty.
        long prev_line_length = SendScintilla(SCI_GETLINEENDPOSITION, curr_line - 1) - SendScintilla(SCI_POSITIONFROMLINE, curr_line - 1);

        if (prev_line_length != 0)
            autoIndentLine(pos, curr_line, blockIndent(curr_line - 1));
    }
}


// Set the indentation for a line.
void QsciScintilla::autoIndentLine(long pos, int line, int indent)
{
    if (indent < 0)
        return;

    long pos_before = SendScintilla(SCI_GETLINEINDENTPOSITION, line);
    SendScintilla(SCI_SETLINEINDENTATION, line, indent);
    long pos_after = SendScintilla(SCI_GETLINEINDENTPOSITION, line);
    long new_pos = -1;

    if (pos_after > pos_before)
        new_pos = pos + (pos_after - pos_before);
    else if (pos_after < pos_before && pos >= pos_after)
        if (pos >= pos_before)
            new_pos = pos + (pos_after - pos_before);
        else
            new_pos = pos_after;

    if (new_pos >= 0)
        SendScintilla(SCI_SETSEL, new_pos, new_pos);
}


// Return the indentation of the block defined by the given line (or something
// significant before).
int QsciScintilla::blockIndent(int line)
{
    if (line < 0)
        return 0;

    // Handle the trvial case.
    if (!lex->blockStartKeyword() && !lex->blockStart() && !lex->blockEnd())
        return indentation(line);

    int line_limit = line - lex->blockLookback();

    if (line_limit < 0)
        line_limit = 0;

    for (int l = line; l >= line_limit; --l)
    {
        IndentState istate = getIndentState(l);

        if (istate != isNone)
        {
            int ind_width = indentWidth();
            int ind = indentation(l);

            if (istate == isBlockStart)
            {
                if (!(lex -> autoIndentStyle() & AiOpening))
                    ind += ind_width;
            }
            else if (istate == isBlockEnd)
            {
                if (lex -> autoIndentStyle() & AiClosing)
                    ind -= ind_width;

                if (ind < 0)
                    ind = 0;
            }
            else if (line == l)
                ind += ind_width;

            return ind;
        }
    }

    return indentation(line);
}


// Return true if all characters starting at spos up to, but not including
// epos, are spaces or tabs.
bool QsciScintilla::rangeIsWhitespace(long spos, long epos)
{
    while (spos < epos)
    {
        char ch = SendScintilla(SCI_GETCHARAT, spos);

        if (ch != ' ' && ch != '\t')
            return false;

        ++spos;
    }

    return true;
}


// Returns the indentation state of a line.
QsciScintilla::IndentState QsciScintilla::getIndentState(int line)
{
    IndentState istate;

    // Get the styled text.
    long spos = SendScintilla(SCI_POSITIONFROMLINE, line);
    long epos = SendScintilla(SCI_POSITIONFROMLINE, line + 1);

    char *text = new char[(epos - spos + 1) * 2];

    SendScintilla(SCI_GETSTYLEDTEXT, spos, epos, text);

    int style, bstart_off, bend_off;

    // Block start/end takes precedence over keywords.
    const char *bstart_words = lex->blockStart(&style);
    bstart_off = findStyledWord(text, style, bstart_words);

    const char *bend_words = lex->blockEnd(&style);
    bend_off = findStyledWord(text, style, bend_words);

    // If there is a block start but no block end characters then ignore it
    // unless the block start is the last significant thing on the line, ie.
    // assume Python-like blocking.
    if (bstart_off >= 0 && !bend_words)
        for (int i = bstart_off * 2; text[i] != '\0'; i += 2)
            if (!QChar(text[i]).isSpace())
                return isNone;

    if (bstart_off > bend_off)
        istate = isBlockStart;
    else if (bend_off > bstart_off)
        istate = isBlockEnd;
    else
    {
        const char *words = lex->blockStartKeyword(&style);

        istate = (findStyledWord(text,style,words) >= 0) ? isKeywordStart : isNone;
    }

    delete[] text;

    return istate;
}


// text is a pointer to some styled text (ie. a character byte followed by a
// style byte).  style is a style number.  words is a space separated list of
// words.  Returns the position in the text immediately after the last one of
// the words with the style.  The reason we are after the last, and not the
// first, occurance is that we are looking for words that start and end a block
// where the latest one is the most significant.
int QsciScintilla::findStyledWord(const char *text, int style,
        const char *words)
{
    if (!words)
        return -1;

    // Find the range of text with the style we are looking for.
    const char *stext;

    for (stext = text; stext[1] != style; stext += 2)
        if (stext[0] == '\0')
            return -1;

    // Move to the last character.
    const char *etext = stext;

    while (etext[2] != '\0')
        etext += 2;

    // Backtrack until we find the style.  There will be one.
    while (etext[1] != style)
        etext -= 2;

    // Look for each word in turn.
    while (words[0] != '\0')
    {
        // Find the end of the word.
        const char *eword = words;

        while (eword[1] != ' ' && eword[1] != '\0')
            ++eword;

        // Now search the text backwards.
        const char *wp = eword;

        for (const char *tp = etext; tp >= stext; tp -= 2)
        {
            if (tp[0] != wp[0] || tp[1] != style)
            {
                // Reset the search.
                wp = eword;
                continue;
            }

            // See if all the word has matched.
            if (wp-- == words)
                return ((tp - text) / 2) + (eword - words) + 1;
        }

        // Move to the start of the next word if there is one.
        words = eword + 1;

        if (words[0] == ' ')
            ++words;
    }

    return -1;
}


// Return true if the code page is UTF8.
bool QsciScintilla::isUtf8() const
{
    return (SendScintilla(SCI_GETCODEPAGE) == SC_CP_UTF8);
}


// Set the code page.
void QsciScintilla::setUtf8(bool cp)
{
    SendScintilla(SCI_SETCODEPAGE, (cp ? SC_CP_UTF8 : 0));
}


// Return the end-of-line mode.
QsciScintilla::EolMode QsciScintilla::eolMode() const
{
    return (EolMode)SendScintilla(SCI_GETEOLMODE);
}


// Set the end-of-line mode.
void QsciScintilla::setEolMode(EolMode mode)
{
    SendScintilla(SCI_SETEOLMODE, mode);
}


// Convert the end-of-lines to a particular mode.
void QsciScintilla::convertEols(EolMode mode)
{
    SendScintilla(SCI_CONVERTEOLS, mode);
}


// Return the edge colour.
QColor QsciScintilla::edgeColor() const
{
    long res = SendScintilla(SCI_GETEDGECOLOUR);

    return QColor((int)res, ((int)(res >> 8)) & 0x00ff, ((int)(res >> 16)) & 0x00ff);
}


// Set the edge colour.
void QsciScintilla::setEdgeColor(const QColor &col)
{
    SendScintilla(SCI_SETEDGECOLOUR, col);
}


// Return the edge column.
int QsciScintilla::edgeColumn() const
{
    return SendScintilla(SCI_GETEDGECOLUMN);
}


// Set the edge column.
void QsciScintilla::setEdgeColumn(int colnr)
{
    SendScintilla(SCI_SETEDGECOLUMN, colnr);
}


// Return the edge mode.
QsciScintilla::EdgeMode QsciScintilla::edgeMode() const
{
    return (EdgeMode)SendScintilla(SCI_GETEDGEMODE);
}


// Set the edge mode.
void QsciScintilla::setEdgeMode(EdgeMode mode)
{
    SendScintilla(SCI_SETEDGEMODE, mode);
}


// Return the end-of-line visibility.
bool QsciScintilla::eolVisibility() const
{
    return SendScintilla(SCI_GETVIEWEOL);
}


// Set the end-of-line visibility.
void QsciScintilla::setEolVisibility(bool visible)
{
    SendScintilla(SCI_SETVIEWEOL, visible);
}


// Return the extra ascent.
int QsciScintilla::extraAscent() const
{
    return SendScintilla(SCI_GETEXTRAASCENT);
}


// Set the extra ascent.
void QsciScintilla::setExtraAscent(int extra)
{
    SendScintilla(SCI_SETEXTRAASCENT, extra);
}


// Return the extra descent.
int QsciScintilla::extraDescent() const
{
    return SendScintilla(SCI_GETEXTRADESCENT);
}


// Set the extra descent.
void QsciScintilla::setExtraDescent(int extra)
{
    SendScintilla(SCI_SETEXTRADESCENT, extra);
}


// Return the whitespace size.
int QsciScintilla::whitespaceSize() const
{
    return SendScintilla(SCI_GETWHITESPACESIZE);
}


// Set the whitespace size.
void QsciScintilla::setWhitespaceSize(int size)
{
    SendScintilla(SCI_SETWHITESPACESIZE, size);
}


// Set the whitespace background colour.
void QsciScintilla::setWhitespaceBackgroundColor(const QColor &col)
{
    SendScintilla(SCI_SETWHITESPACEBACK, col.isValid(), col);
}


// Set the whitespace foreground colour.
void QsciScintilla::setWhitespaceForegroundColor(const QColor &col)
{
    SendScintilla(SCI_SETWHITESPACEFORE, col.isValid(), col);
}


// Return the whitespace visibility.
QsciScintilla::WhitespaceVisibility QsciScintilla::whitespaceVisibility() const
{
    return (WhitespaceVisibility)SendScintilla(SCI_GETVIEWWS);
}


// Set the whitespace visibility.
void QsciScintilla::setWhitespaceVisibility(WhitespaceVisibility mode)
{
    SendScintilla(SCI_SETVIEWWS, mode);
}


// Return the line wrap mode.
QsciScintilla::WrapMode QsciScintilla::wrapMode() const
{
    return (WrapMode)SendScintilla(SCI_GETWRAPMODE);
}


// Set the line wrap mode.
void QsciScintilla::setWrapMode(WrapMode mode)
{
    SendScintilla(SCI_SETLAYOUTCACHE,
            (mode == WrapNone ? SC_CACHE_CARET : SC_CACHE_DOCUMENT));
    SendScintilla(SCI_SETWRAPMODE, mode);
}


// Return the line wrap indent mode.
QsciScintilla::WrapIndentMode QsciScintilla::wrapIndentMode() const
{
    return (WrapIndentMode)SendScintilla(SCI_GETWRAPINDENTMODE);
}


// Set the line wrap indent mode.
void QsciScintilla::setWrapIndentMode(WrapIndentMode mode)
{
    SendScintilla(SCI_SETWRAPINDENTMODE, mode);
}


// Set the line wrap visual flags.
void QsciScintilla::setWrapVisualFlags(WrapVisualFlag endFlag,
        WrapVisualFlag startFlag, int indent)
{
    int flags = SC_WRAPVISUALFLAG_NONE;
    int loc = SC_WRAPVISUALFLAGLOC_DEFAULT;

    switch (endFlag)
    {
    case WrapFlagByText:
        flags |= SC_WRAPVISUALFLAG_END;
        loc |= SC_WRAPVISUALFLAGLOC_END_BY_TEXT;
        break;

    case WrapFlagByBorder:
        flags |= SC_WRAPVISUALFLAG_END;
        break;

    case WrapFlagInMargin:
        flags |= SC_WRAPVISUALFLAG_MARGIN;
        break;
    }

    switch (startFlag)
    {
    case WrapFlagByText:
        flags |= SC_WRAPVISUALFLAG_START;
        loc |= SC_WRAPVISUALFLAGLOC_START_BY_TEXT;
        break;

    case WrapFlagByBorder:
        flags |= SC_WRAPVISUALFLAG_START;
        break;

    case WrapFlagInMargin:
        flags |= SC_WRAPVISUALFLAG_MARGIN;
        break;
    }

    SendScintilla(SCI_SETWRAPVISUALFLAGS, flags);
    SendScintilla(SCI_SETWRAPVISUALFLAGSLOCATION, loc);
    SendScintilla(SCI_SETWRAPSTARTINDENT, indent);
}


// Set the folding style.
void QsciScintilla::setFolding(FoldStyle folding, int margin)
{
    fold = folding;
    foldmargin = margin;

    if (folding == NoFoldStyle)
    {
        SendScintilla(SCI_SETMARGINWIDTHN, margin, 0L);
        return;
    }

    int mask = SendScintilla(SCI_GETMODEVENTMASK);
    SendScintilla(SCI_SETMODEVENTMASK, mask | SC_MOD_CHANGEFOLD);

    SendScintilla(SCI_SETFOLDFLAGS, SC_FOLDFLAG_LINEAFTER_CONTRACTED);

    SendScintilla(SCI_SETMARGINTYPEN, margin, (long)SC_MARGIN_SYMBOL);
    SendScintilla(SCI_SETMARGINMASKN, margin, SC_MASK_FOLDERS);
    SendScintilla(SCI_SETMARGINSENSITIVEN, margin, 1);

    // Set the marker symbols to use.
    switch (folding)
    {
    case PlainFoldStyle:
        setFoldMarker(SC_MARKNUM_FOLDEROPEN, SC_MARK_MINUS);
        setFoldMarker(SC_MARKNUM_FOLDER, SC_MARK_PLUS);
        setFoldMarker(SC_MARKNUM_FOLDERSUB);
        setFoldMarker(SC_MARKNUM_FOLDERTAIL);
        setFoldMarker(SC_MARKNUM_FOLDEREND);
        setFoldMarker(SC_MARKNUM_FOLDEROPENMID);
        setFoldMarker(SC_MARKNUM_FOLDERMIDTAIL);
        break;

    case CircledFoldStyle:
        setFoldMarker(SC_MARKNUM_FOLDEROPEN, SC_MARK_CIRCLEMINUS);
        setFoldMarker(SC_MARKNUM_FOLDER, SC_MARK_CIRCLEPLUS);
        setFoldMarker(SC_MARKNUM_FOLDERSUB);
        setFoldMarker(SC_MARKNUM_FOLDERTAIL);
        setFoldMarker(SC_MARKNUM_FOLDEREND);
        setFoldMarker(SC_MARKNUM_FOLDEROPENMID);
        setFoldMarker(SC_MARKNUM_FOLDERMIDTAIL);
        break;

    case BoxedFoldStyle:
        setFoldMarker(SC_MARKNUM_FOLDEROPEN, SC_MARK_BOXMINUS);
        setFoldMarker(SC_MARKNUM_FOLDER, SC_MARK_BOXPLUS);
        setFoldMarker(SC_MARKNUM_FOLDERSUB);
        setFoldMarker(SC_MARKNUM_FOLDERTAIL);
        setFoldMarker(SC_MARKNUM_FOLDEREND);
        setFoldMarker(SC_MARKNUM_FOLDEROPENMID);
        setFoldMarker(SC_MARKNUM_FOLDERMIDTAIL);
        break;

    case CircledTreeFoldStyle:
        setFoldMarker(SC_MARKNUM_FOLDEROPEN, SC_MARK_CIRCLEMINUS);
        setFoldMarker(SC_MARKNUM_FOLDER, SC_MARK_CIRCLEPLUS);
        setFoldMarker(SC_MARKNUM_FOLDERSUB, SC_MARK_VLINE);
        setFoldMarker(SC_MARKNUM_FOLDERTAIL, SC_MARK_LCORNERCURVE);
        setFoldMarker(SC_MARKNUM_FOLDEREND, SC_MARK_CIRCLEPLUSCONNECTED);
        setFoldMarker(SC_MARKNUM_FOLDEROPENMID, SC_MARK_CIRCLEMINUSCONNECTED);
        setFoldMarker(SC_MARKNUM_FOLDERMIDTAIL, SC_MARK_TCORNERCURVE);
        break;

    case BoxedTreeFoldStyle:
        setFoldMarker(SC_MARKNUM_FOLDEROPEN, SC_MARK_BOXMINUS);
        setFoldMarker(SC_MARKNUM_FOLDER, SC_MARK_BOXPLUS);
        setFoldMarker(SC_MARKNUM_FOLDERSUB, SC_MARK_VLINE);
        setFoldMarker(SC_MARKNUM_FOLDERTAIL, SC_MARK_LCORNER);
        setFoldMarker(SC_MARKNUM_FOLDEREND, SC_MARK_BOXPLUSCONNECTED);
        setFoldMarker(SC_MARKNUM_FOLDEROPENMID, SC_MARK_BOXMINUSCONNECTED);
        setFoldMarker(SC_MARKNUM_FOLDERMIDTAIL, SC_MARK_TCORNER);
        break;
    }

    SendScintilla(SCI_SETMARGINWIDTHN, margin, defaultFoldMarginWidth);
}


// Clear all current folds.
void QsciScintilla::clearFolds()
{
    recolor();

    int maxLine = SendScintilla(SCI_GETLINECOUNT);

    for (int line = 0; line < maxLine; line++)
    {
        int level = SendScintilla(SCI_GETFOLDLEVEL, line);

        if (level & SC_FOLDLEVELHEADERFLAG)
        {
            SendScintilla(SCI_SETFOLDEXPANDED, line, 1);
            foldExpand(line, true, false, 0, level);
            line--;
        }
    }
}


// Set up a folder marker.
void QsciScintilla::setFoldMarker(int marknr, int mark)
{
    SendScintilla(SCI_MARKERDEFINE, marknr, mark);

    if (mark != SC_MARK_EMPTY)
    {
        SendScintilla(SCI_MARKERSETFORE, marknr, QColor(Qt::white));
        SendScintilla(SCI_MARKERSETBACK, marknr, QColor(Qt::black));
    }
}


// Handle a click in the fold margin.  This is mostly taken from SciTE.
void QsciScintilla::foldClick(int lineClick, int bstate)
{
    bool shift = bstate & Qt::ShiftModifier;
    bool ctrl = bstate & Qt::ControlModifier;

    if (shift && ctrl)
    {
        foldAll();
        return;
    }

    int levelClick = SendScintilla(SCI_GETFOLDLEVEL, lineClick);

    if (levelClick & SC_FOLDLEVELHEADERFLAG)
    {
        if (shift)
        {
            // Ensure all children are visible.
            SendScintilla(SCI_SETFOLDEXPANDED, lineClick, 1);
            foldExpand(lineClick, true, true, 100, levelClick);
        }
        else if (ctrl)
        {
            if (SendScintilla(SCI_GETFOLDEXPANDED, lineClick))
            {
                // Contract this line and all its children.
                SendScintilla(SCI_SETFOLDEXPANDED, lineClick, 0L);
                foldExpand(lineClick, false, true, 0, levelClick);
            }
            else
            {
                // Expand this line and all its children.
                SendScintilla(SCI_SETFOLDEXPANDED, lineClick, 1);
                foldExpand(lineClick, true, true, 100, levelClick);
            }
        }
        else
        {
            // Toggle this line.
            SendScintilla(SCI_TOGGLEFOLD, lineClick);
        }
    }
}


// Do the hard work of hiding and showing lines.  This is mostly taken from
// SciTE.
void QsciScintilla::foldExpand(int &line, bool doExpand, bool force,
        int visLevels, int level)
{
    int lineMaxSubord = SendScintilla(SCI_GETLASTCHILD, line,
            level & SC_FOLDLEVELNUMBERMASK);

    line++;

    while (line <= lineMaxSubord)
    {
        if (force)
        {
            if (visLevels > 0)
                SendScintilla(SCI_SHOWLINES, line, line);
            else
                SendScintilla(SCI_HIDELINES, line, line);
        }
        else if (doExpand)
            SendScintilla(SCI_SHOWLINES, line, line);

        int levelLine = level;

        if (levelLine == -1)
            levelLine = SendScintilla(SCI_GETFOLDLEVEL, line);

        if (levelLine & SC_FOLDLEVELHEADERFLAG)
        {
            if (force)
            {
                if (visLevels > 1)
                    SendScintilla(SCI_SETFOLDEXPANDED, line, 1);
                else
                    SendScintilla(SCI_SETFOLDEXPANDED, line, 0L);

                foldExpand(line, doExpand, force, visLevels - 1);
            }
            else if (doExpand)
            {
                if (!SendScintilla(SCI_GETFOLDEXPANDED, line))
                    SendScintilla(SCI_SETFOLDEXPANDED, line, 1);

                foldExpand(line, true, force, visLevels - 1);
            }
            else
                foldExpand(line, false, force, visLevels - 1);
        }
        else
            line++;
    }
}


// Fully expand (if there is any line currently folded) all text.  Otherwise,
// fold all text.  This is mostly taken from SciTE.
void QsciScintilla::foldAll(bool children)
{
    recolor();

    int maxLine = SendScintilla(SCI_GETLINECOUNT);
    bool expanding = true;

    for (int lineSeek = 0; lineSeek < maxLine; lineSeek++)
    {
        if (SendScintilla(SCI_GETFOLDLEVEL,lineSeek) & SC_FOLDLEVELHEADERFLAG)
        {
            expanding = !SendScintilla(SCI_GETFOLDEXPANDED, lineSeek);
            break;
        }
    }

    for (int line = 0; line < maxLine; line++)
    {
        int level = SendScintilla(SCI_GETFOLDLEVEL, line);

        if (!(level & SC_FOLDLEVELHEADERFLAG))
            continue;

        if (children ||
            (SC_FOLDLEVELBASE == (level & SC_FOLDLEVELNUMBERMASK)))
        {
            if (expanding)
            {
                SendScintilla(SCI_SETFOLDEXPANDED, line, 1);
                foldExpand(line, true, false, 0, level);
                line--;
            }
            else
            {
                int lineMaxSubord = SendScintilla(SCI_GETLASTCHILD, line, -1);

                SendScintilla(SCI_SETFOLDEXPANDED, line, 0L);

                if (lineMaxSubord > line)
                    SendScintilla(SCI_HIDELINES, line + 1, lineMaxSubord);
            }
        }
    }
}


// Handle a fold change.  This is mostly taken from SciTE.
void QsciScintilla::foldChanged(int line,int levelNow,int levelPrev)
{
    if (levelNow & SC_FOLDLEVELHEADERFLAG)
    {
        if (!(levelPrev & SC_FOLDLEVELHEADERFLAG))
            SendScintilla(SCI_SETFOLDEXPANDED, line, 1);
    }
    else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
    {
        if (!SendScintilla(SCI_GETFOLDEXPANDED, 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.
            foldExpand(line, true, false, 0, levelPrev);
        }
    }
}


// Toggle the fold for a line if it contains a fold marker.
void QsciScintilla::foldLine(int line)
{
    SendScintilla(SCI_TOGGLEFOLD, line);
}


// Return the list of folded lines.
QList<int> QsciScintilla::contractedFolds() const
{
    QList<int> folds;
    int linenr = 0, fold_line;

    while ((fold_line = SendScintilla(SCI_CONTRACTEDFOLDNEXT, linenr)) >= 0)
    {
        folds.append(fold_line);
        linenr = fold_line + 1;
    }

    return folds;
}


// Set the fold state from a list.
void QsciScintilla::setContractedFolds(const QList<int> &folds)
{
    for (int i = 0; i < folds.count(); ++i)
    {
        int line = folds[i];
        int last_line = SendScintilla(SCI_GETLASTCHILD, line, -1);

        SendScintilla(SCI_SETFOLDEXPANDED, line, 0L);
        SendScintilla(SCI_HIDELINES, line + 1, last_line);
    }
}


// Handle the SCN_MODIFIED notification.
void QsciScintilla::handleModified(int pos, int mtype, const char *text,
        int len, int added, int line, int foldNow, int foldPrev, int token,
        int annotationLinesAdded)
{
    if (mtype & SC_MOD_CHANGEFOLD)
    {
        if (fold)
            foldChanged(line, foldNow, foldPrev);
    }

    if (mtype & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
    {
        emit textChanged();

        if (added != 0)
            emit linesChanged();
    }
}


// Zoom in a number of points.
void QsciScintilla::zoomIn(int range)
{
    zoomTo(SendScintilla(SCI_GETZOOM) + range);
}


// Zoom in a single point.
void QsciScintilla::zoomIn()
{
    SendScintilla(SCI_ZOOMIN);
}


// Zoom out a number of points.
void QsciScintilla::zoomOut(int range)
{
    zoomTo(SendScintilla(SCI_GETZOOM) - range);
}


// Zoom out a single point.
void QsciScintilla::zoomOut()
{
    SendScintilla(SCI_ZOOMOUT);
}


// Set the zoom to a number of points.
void QsciScintilla::zoomTo(int size)
{
    if (size < -10)
        size = -10;
    else if (size > 20)
        size = 20;

    SendScintilla(SCI_SETZOOM, size);
}


// Find the first occurrence of a string.
bool QsciScintilla::findFirst(const QString &expr, bool re, bool cs, bool wo,
        bool wrap, bool forward, int line, int index, bool show, bool posix)
{
    if (expr.isEmpty())
    {
        findState.status = FindState::Idle;
        return false;
    }

    findState.status = FindState::Finding;
    findState.expr = expr;
    findState.wrap = wrap;
    findState.forward = forward;

    findState.flags =
        (cs ? SCFIND_MATCHCASE : 0) |
        (wo ? SCFIND_WHOLEWORD : 0) |
        (re ? SCFIND_REGEXP : 0) |
        (posix ? SCFIND_POSIX : 0);

    if (line < 0 || index < 0)
        findState.startpos = SendScintilla(SCI_GETCURRENTPOS);
    else
        findState.startpos = positionFromLineIndex(line, index);

    if (forward)
        findState.endpos = SendScintilla(SCI_GETLENGTH);
    else
        findState.endpos = 0;

    findState.show = show;

    return doFind();
}


// Find the first occurrence of a string in the current selection.
bool QsciScintilla::findFirstInSelection(const QString &expr, bool re, bool cs,
        bool wo, bool forward, bool show, bool posix)
{
    if (expr.isEmpty())
    {
        findState.status = FindState::Idle;
        return false;
    }

    findState.status = FindState::FindingInSelection;
    findState.expr = expr;
    findState.wrap = false;
    findState.forward = forward;

    findState.flags =
        (cs ? SCFIND_MATCHCASE : 0) |
        (wo ? SCFIND_WHOLEWORD : 0) |
        (re ? SCFIND_REGEXP : 0) |
        (posix ? SCFIND_POSIX : 0);

    findState.startpos_orig = SendScintilla(SCI_GETSELECTIONSTART);
    findState.endpos_orig = SendScintilla(SCI_GETSELECTIONEND);

    if (forward)
    {
        findState.startpos = findState.startpos_orig;
        findState.endpos = findState.endpos_orig;
    }
    else
    {
        findState.startpos = findState.endpos_orig;
        findState.endpos = findState.startpos_orig;
    }

    findState.show = show;

    return doFind();
}


// Find the next occurrence of a string.
bool QsciScintilla::findNext()
{
    if (findState.status == FindState::Idle)
        return false;

    return doFind();
}


// Do the hard work of the find methods.
bool QsciScintilla::doFind()
{
    SendScintilla(SCI_SETSEARCHFLAGS, findState.flags);

    int pos = simpleFind();

    // See if it was found.  If not and wraparound is wanted, try again.
    if (pos == -1 && findState.wrap)
    {
        if (findState.forward)
        {
            findState.startpos = 0;
            findState.endpos = SendScintilla(SCI_GETLENGTH);
        }
        else
        {
            findState.startpos = SendScintilla(SCI_GETLENGTH);
            findState.endpos = 0;
        }

        pos = simpleFind();
    }

    if (pos == -1)
    {
        // Restore the original selection.
        if (findState.status == FindState::FindingInSelection)
            SendScintilla(SCI_SETSEL, findState.startpos_orig,
                    findState.endpos_orig);

        findState.status = FindState::Idle;
        return false;
    }

    // It was found.
    long targstart = SendScintilla(SCI_GETTARGETSTART);
    long targend = SendScintilla(SCI_GETTARGETEND);

    // Ensure the text found is visible if required.
    if (findState.show)
    {
        int startLine = SendScintilla(SCI_LINEFROMPOSITION, targstart);
        int endLine = SendScintilla(SCI_LINEFROMPOSITION, targend);

        for (int i = startLine; i <= endLine; ++i)
            SendScintilla(SCI_ENSUREVISIBLEENFORCEPOLICY, i);
    }

    // Now set the selection.
    SendScintilla(SCI_SETSEL, targstart, targend);

    // Finally adjust the start position so that we don't find the same one
    // again.
    if (findState.forward)
        findState.startpos = targend;
    else if ((findState.startpos = targstart - 1) < 0)
        findState.startpos = 0;

    return true;
}


// Do a simple find between the start and end positions.
int QsciScintilla::simpleFind()
{
    if (findState.startpos == findState.endpos)
        return -1;

    SendScintilla(SCI_SETTARGETSTART, findState.startpos);
    SendScintilla(SCI_SETTARGETEND, findState.endpos);

    ScintillaBytes s = textAsBytes(findState.expr);

    return SendScintilla(SCI_SEARCHINTARGET, s.length(),
            ScintillaBytesConstData(s));
}


// Replace the text found with the previous find method.
void QsciScintilla::replace(const QString &replaceStr)
{
    if (findState.status == FindState::Idle)
        return;

    long start = SendScintilla(SCI_GETSELECTIONSTART);
    long orig_len = SendScintilla(SCI_GETSELECTIONEND) - start;

    SendScintilla(SCI_TARGETFROMSELECTION);

    int cmd = (findState.flags & SCFIND_REGEXP) ? SCI_REPLACETARGETRE : SCI_REPLACETARGET;

    ScintillaBytes s = textAsBytes(replaceStr);
    long len = SendScintilla(cmd, -1, ScintillaBytesConstData(s));

    // Reset the selection.
    SendScintilla(SCI_SETSELECTIONSTART, start);
    SendScintilla(SCI_SETSELECTIONEND, start + len);

    // Fix the original selection.
    findState.endpos_orig += (len - orig_len);

    if (findState.forward)
        findState.startpos = start + len;
}


// Query the modified state.
bool QsciScintilla::isModified() const
{
    return doc.isModified();
}


// Set the modified state.
void QsciScintilla::setModified(bool m)
{
    if (!m)
        SendScintilla(SCI_SETSAVEPOINT);
}


// Handle the SCN_INDICATORCLICK notification.
void QsciScintilla::handleIndicatorClick(int pos, int modifiers)
{
    int state = mapModifiers(modifiers);
    int line, index;

    lineIndexFromPosition(pos, &line, &index);

    emit indicatorClicked(line, index, Qt::KeyboardModifiers(state));
}


// Handle the SCN_INDICATORRELEASE notification.
void QsciScintilla::handleIndicatorRelease(int pos, int modifiers)
{
    int state = mapModifiers(modifiers);
    int line, index;

    lineIndexFromPosition(pos, &line, &index);

    emit indicatorReleased(line, index, Qt::KeyboardModifiers(state));
}


// Handle the SCN_MARGINCLICK notification.
void QsciScintilla::handleMarginClick(int pos, int modifiers, int margin)
{
    int state = mapModifiers(modifiers);
    int line = SendScintilla(SCI_LINEFROMPOSITION, pos);

    if (fold && margin == foldmargin)
        foldClick(line, state);
    else
        emit marginClicked(margin, line, Qt::KeyboardModifiers(state));
}


// Handle the SCN_SAVEPOINTREACHED notification.
void QsciScintilla::handleSavePointReached()
{
    doc.setModified(false);
    emit modificationChanged(false);
}


// Handle the SCN_SAVEPOINTLEFT notification.
void QsciScintilla::handleSavePointLeft()
{
    doc.setModified(true);
    emit modificationChanged(true);
}


// Handle the QSCN_SELCHANGED signal.
void QsciScintilla::handleSelectionChanged(bool yes)
{
    selText = yes;

    emit copyAvailable(yes);
    emit selectionChanged();
}


// Get the current selection.
void QsciScintilla::getSelection(int *lineFrom, int *indexFrom, int *lineTo,
        int *indexTo) const
{
    if (selText)
    {
        lineIndexFromPosition(SendScintilla(SCI_GETSELECTIONSTART), lineFrom,
                indexFrom);
        lineIndexFromPosition(SendScintilla(SCI_GETSELECTIONEND), lineTo,
                indexTo);
    }
    else
        *lineFrom = *indexFrom = *lineTo = *indexTo = -1;
}


// Sets the current selection.
void QsciScintilla::setSelection(int lineFrom, int indexFrom, int lineTo,
        int indexTo)
{
    SendScintilla(SCI_SETSEL, positionFromLineIndex(lineFrom, indexFrom),
            positionFromLineIndex(lineTo, indexTo));
}


// Set the background colour of selected text.
void QsciScintilla::setSelectionBackgroundColor(const QColor &col)
{
    int alpha = col.alpha();

    if (alpha == 255)
        alpha = SC_ALPHA_NOALPHA;

    SendScintilla(SCI_SETSELBACK, 1, col);
    SendScintilla(SCI_SETSELALPHA, alpha);
}


// Set the foreground colour of selected text.
void QsciScintilla::setSelectionForegroundColor(const QColor &col)
{
    SendScintilla(SCI_SETSELFORE, 1, col);
}


// Reset the background colour of selected text to the default.
void QsciScintilla::resetSelectionBackgroundColor()
{
    SendScintilla(SCI_SETSELALPHA, SC_ALPHA_NOALPHA);
    SendScintilla(SCI_SETSELBACK, 0UL);
}


// Reset the foreground colour of selected text to the default.
void QsciScintilla::resetSelectionForegroundColor()
{
    SendScintilla(SCI_SETSELFORE, 0UL);
}


// Set the fill to the end-of-line for the selection.
void QsciScintilla::setSelectionToEol(bool filled)
{
    SendScintilla(SCI_SETSELEOLFILLED, filled);
}


// Return the fill to the end-of-line for the selection.
bool QsciScintilla::selectionToEol() const
{
    return SendScintilla(SCI_GETSELEOLFILLED);
}


// Set the width of the caret.
void QsciScintilla::setCaretWidth(int width)
{
    SendScintilla(SCI_SETCARETWIDTH, width);
}


// Set the foreground colour of the caret.
void QsciScintilla::setCaretForegroundColor(const QColor &col)
{
    SendScintilla(SCI_SETCARETFORE, col);
}


// Set the background colour of the line containing the caret.
void QsciScintilla::setCaretLineBackgroundColor(const QColor &col)
{
    int alpha = col.alpha();

    if (alpha == 255)
        alpha = SC_ALPHA_NOALPHA;

    SendScintilla(SCI_SETCARETLINEBACK, col);
    SendScintilla(SCI_SETCARETLINEBACKALPHA, alpha);
}


// Set the state of the background colour of the line containing the caret.
void QsciScintilla::setCaretLineVisible(bool enable)
{
    SendScintilla(SCI_SETCARETLINEVISIBLE, enable);
}


// Set the background colour of a hotspot area.
void QsciScintilla::setHotspotBackgroundColor(const QColor &col)
{
    SendScintilla(SCI_SETSELBACK, 1, col);
}


// Set the foreground colour of a hotspot area.
void QsciScintilla::setHotspotForegroundColor(const QColor &col)
{
    SendScintilla(SCI_SETHOTSPOTACTIVEFORE, 1, col);
}


// Reset the background colour of a hotspot area to the default.
void QsciScintilla::resetHotspotBackgroundColor()
{
    SendScintilla(SCI_SETSELBACK, 0UL);
}


// Reset the foreground colour of a hotspot area to the default.
void QsciScintilla::resetHotspotForegroundColor()
{
    SendScintilla(SCI_SETHOTSPOTACTIVEFORE, 0UL);
}


// Set the underline of a hotspot area.
void QsciScintilla::setHotspotUnderline(bool enable)
{
    SendScintilla(SCI_SETHOTSPOTACTIVEUNDERLINE, enable);
}


// Set the wrapping of a hotspot area.
void QsciScintilla::setHotspotWrap(bool enable)
{
    SendScintilla(SCI_SETHOTSPOTSINGLELINE, !enable);
}


// Query the read-only state.
bool QsciScintilla::isReadOnly() const
{
    return SendScintilla(SCI_GETREADONLY);
}


// Set the read-only state.
void QsciScintilla::setReadOnly(bool ro)
{
    setAttribute(Qt::WA_InputMethodEnabled, !ro);
    SendScintilla(SCI_SETREADONLY, ro);
}


// Append the given text.
void QsciScintilla::append(const QString &text)
{
    bool ro = ensureRW();

    ScintillaBytes s = textAsBytes(text);
    SendScintilla(SCI_APPENDTEXT, s.length(), ScintillaBytesConstData(s));

    SendScintilla(SCI_EMPTYUNDOBUFFER);

    setReadOnly(ro);
}


// Insert the given text at the current position.
void QsciScintilla::insert(const QString &text)
{
    insertAtPos(text, -1);
}


// Insert the given text at the given line and offset.
void QsciScintilla::insertAt(const QString &text, int line, int index)
{
    insertAtPos(text, positionFromLineIndex(line, index));
}


// Insert the given text at the given position.
void QsciScintilla::insertAtPos(const QString &text, int pos)
{
    bool ro = ensureRW();

    SendScintilla(SCI_BEGINUNDOACTION);
    SendScintilla(SCI_INSERTTEXT, pos,
            ScintillaBytesConstData(textAsBytes(text)));
    SendScintilla(SCI_ENDUNDOACTION);

    setReadOnly(ro);
}


// Begin a sequence of undoable actions.
void QsciScintilla::beginUndoAction()
{
    SendScintilla(SCI_BEGINUNDOACTION);
}


// End a sequence of undoable actions.
void QsciScintilla::endUndoAction()
{
    SendScintilla(SCI_ENDUNDOACTION);
}


// Redo a sequence of actions.
void QsciScintilla::redo()
{
    SendScintilla(SCI_REDO);
}


// Undo a sequence of actions.
void QsciScintilla::undo()
{
    SendScintilla(SCI_UNDO);
}


// See if there is something to redo.
bool QsciScintilla::isRedoAvailable() const
{
    return SendScintilla(SCI_CANREDO);
}


// See if there is something to undo.
bool QsciScintilla::isUndoAvailable() const
{
    return SendScintilla(SCI_CANUNDO);
}


// Return the number of lines.
int QsciScintilla::lines() const
{
    return SendScintilla(SCI_GETLINECOUNT);
}


// Return the line at a position.
int QsciScintilla::lineAt(const QPoint &pos) const
{
    long chpos = SendScintilla(SCI_POSITIONFROMPOINTCLOSE, pos.x(), pos.y());

    if (chpos < 0)
        return -1;

    return SendScintilla(SCI_LINEFROMPOSITION, chpos);
}


// Return the length of a line.
int QsciScintilla::lineLength(int line) const
{
    if (line < 0 || line >= SendScintilla(SCI_GETLINECOUNT))
        return -1;

    return SendScintilla(SCI_LINELENGTH, line);
}


// Return the length of the current text.
int QsciScintilla::length() const
{
    return SendScintilla(SCI_GETTEXTLENGTH);
}


// Remove any selected text.
void QsciScintilla::removeSelectedText()
{
    SendScintilla(SCI_REPLACESEL, "");
}


// Replace any selected text.
void QsciScintilla::replaceSelectedText(const QString &text)
{
    SendScintilla(SCI_REPLACESEL, ScintillaBytesConstData(textAsBytes(text)));
}


// Return the current selected text.
QString QsciScintilla::selectedText() const
{
    if (!selText)
        return QString();

    char *buf = new char[SendScintilla(SCI_GETSELECTIONEND) - SendScintilla(SCI_GETSELECTIONSTART) + 1];

    SendScintilla(SCI_GETSELTEXT, buf);

    QString qs = bytesAsText(buf);
    delete[] buf;

    return qs;
}


// Return the current text.
QString QsciScintilla::text() const
{
    int buflen = length() + 1;
    char *buf = new char[buflen];

    SendScintilla(SCI_GETTEXT, buflen, buf);

    QString qs = bytesAsText(buf);
    delete[] buf;

    return qs;
}


// Return the text of a line.
QString QsciScintilla::text(int line) const
{
    int line_len = lineLength(line);

    if (line_len < 1)
        return QString();

    char *buf = new char[line_len + 1];

    SendScintilla(SCI_GETLINE, line, buf);
    buf[line_len] = '\0';

    QString qs = bytesAsText(buf);
    delete[] buf;

    return qs;
}


// Set the given text.
void QsciScintilla::setText(const QString &text)
{
    bool ro = ensureRW();

    SendScintilla(SCI_SETTEXT, ScintillaBytesConstData(textAsBytes(text)));
    SendScintilla(SCI_EMPTYUNDOBUFFER);

    setReadOnly(ro);
}


// Get the cursor position
void QsciScintilla::getCursorPosition(int *line, int *index) const
{
    lineIndexFromPosition(SendScintilla(SCI_GETCURRENTPOS), line, index);
}


// Set the cursor position
void QsciScintilla::setCursorPosition(int line, int index)
{
    SendScintilla(SCI_GOTOPOS, positionFromLineIndex(line, index));
}


// Ensure the cursor is visible.
void QsciScintilla::ensureCursorVisible()
{
    SendScintilla(SCI_SCROLLCARET);
}


// Ensure a line is visible.
void QsciScintilla::ensureLineVisible(int line)
{
    SendScintilla(SCI_ENSUREVISIBLEENFORCEPOLICY, line);
}


// Copy text to the clipboard.
void QsciScintilla::copy()
{
    SendScintilla(SCI_COPY);
}


// Cut text to the clipboard.
void QsciScintilla::cut()
{
    SendScintilla(SCI_CUT);
}


// Paste text from the clipboard.
void QsciScintilla::paste()
{
    SendScintilla(SCI_PASTE);
}


// Select all text, or deselect any selected text.
void QsciScintilla::selectAll(bool select)
{
    if (select)
        SendScintilla(SCI_SELECTALL);
    else
        SendScintilla(SCI_SETANCHOR, SendScintilla(SCI_GETCURRENTPOS));
}


// Delete all text.
void QsciScintilla::clear()
{
    bool ro = ensureRW();

    SendScintilla(SCI_BEGINUNDOACTION);
    SendScintilla(SCI_CLEARALL);
    SendScintilla(SCI_ENDUNDOACTION);

    setReadOnly(ro);
}


// Return the indentation of a line.
int QsciScintilla::indentation(int line) const
{
    return SendScintilla(SCI_GETLINEINDENTATION, line);
}


// Set the indentation of a line.
void QsciScintilla::setIndentation(int line, int indentation)
{
    SendScintilla(SCI_BEGINUNDOACTION);
    SendScintilla(SCI_SETLINEINDENTATION, line, indentation);
    SendScintilla(SCI_ENDUNDOACTION);
}


// Indent a line.
void QsciScintilla::indent(int line)
{
    setIndentation(line, indentation(line) + indentWidth());
}


// Unindent a line.
void QsciScintilla::unindent(int line)
{
    int newIndent = indentation(line) - indentWidth();

    if (newIndent < 0)
        newIndent = 0;

    setIndentation(line, newIndent);
}


// Return the indentation of the current line.
int QsciScintilla::currentIndent() const
{
    return indentation(SendScintilla(SCI_LINEFROMPOSITION,
                SendScintilla(SCI_GETCURRENTPOS)));
}


// Return the current indentation width.
int QsciScintilla::indentWidth() const
{
    int w = indentationWidth();

    if (w == 0)
        w = tabWidth();

    return w;
}


// Return the state of indentation guides.
bool QsciScintilla::indentationGuides() const
{
    return (SendScintilla(SCI_GETINDENTATIONGUIDES) != SC_IV_NONE);
}


// Enable and disable indentation guides.
void QsciScintilla::setIndentationGuides(bool enable)
{
    int iv;

    if (!enable)
        iv = SC_IV_NONE;
    else if (lex.isNull())
        iv = SC_IV_REAL;
    else
        iv = lex->indentationGuideView();

    SendScintilla(SCI_SETINDENTATIONGUIDES, iv);
}


// Set the background colour of indentation guides.
void QsciScintilla::setIndentationGuidesBackgroundColor(const QColor &col)
{
    SendScintilla(SCI_STYLESETBACK, STYLE_INDENTGUIDE, col);
}


// Set the foreground colour of indentation guides.
void QsciScintilla::setIndentationGuidesForegroundColor(const QColor &col)
{
    SendScintilla(SCI_STYLESETFORE, STYLE_INDENTGUIDE, col);
}


// Return the indentation width.
int QsciScintilla::indentationWidth() const
{
    return SendScintilla(SCI_GETINDENT);
}


// Set the indentation width.
void QsciScintilla::setIndentationWidth(int width)
{
    SendScintilla(SCI_SETINDENT, width);
}


// Return the tab width.
int QsciScintilla::tabWidth() const
{
    return SendScintilla(SCI_GETTABWIDTH);
}


// Set the tab width.
void QsciScintilla::setTabWidth(int width)
{
    SendScintilla(SCI_SETTABWIDTH, width);
}


// Return the effect of the backspace key.
bool QsciScintilla::backspaceUnindents() const
{
    return SendScintilla(SCI_GETBACKSPACEUNINDENTS);
}


// Set the effect of the backspace key.
void QsciScintilla::setBackspaceUnindents(bool unindents)
{
    SendScintilla(SCI_SETBACKSPACEUNINDENTS, unindents);
}


// Return the effect of the tab key.
bool QsciScintilla::tabIndents() const
{
    return SendScintilla(SCI_GETTABINDENTS);
}


// Set the effect of the tab key.
void QsciScintilla::setTabIndents(bool indents)
{
    SendScintilla(SCI_SETTABINDENTS, indents);
}


// Return the indentation use of tabs.
bool QsciScintilla::indentationsUseTabs() const
{
    return SendScintilla(SCI_GETUSETABS);
}


// Set the indentation use of tabs.
void QsciScintilla::setIndentationsUseTabs(bool tabs)
{
    SendScintilla(SCI_SETUSETABS, tabs);
}


// Return the margin options.
int QsciScintilla::marginOptions() const
{
    return SendScintilla(SCI_GETMARGINOPTIONS);
}


// Set the margin options.
void QsciScintilla::setMarginOptions(int options)
{
    SendScintilla(SCI_SETMARGINOPTIONS, options);
}


// Return the margin type.
QsciScintilla::MarginType QsciScintilla::marginType(int margin) const
{
    return (MarginType)SendScintilla(SCI_GETMARGINTYPEN, margin);
}


// Set the margin type.
void QsciScintilla::setMarginType(int margin, QsciScintilla::MarginType type)
{
    SendScintilla(SCI_SETMARGINTYPEN, margin, type);
}


// Clear margin text.
void QsciScintilla::clearMarginText(int line)
{
    if (line < 0)
        SendScintilla(SCI_MARGINTEXTCLEARALL);
    else
        SendScintilla(SCI_MARGINSETTEXT, line, (const char *)0);
}


// Annotate a line.
void QsciScintilla::setMarginText(int line, const QString &text, int style)
{
    int style_offset = SendScintilla(SCI_MARGINGETSTYLEOFFSET);

    SendScintilla(SCI_MARGINSETTEXT, line,
            ScintillaBytesConstData(textAsBytes(text)));

    SendScintilla(SCI_MARGINSETSTYLE, line, style - style_offset);
}


// Annotate a line.
void QsciScintilla::setMarginText(int line, const QString &text, const QsciStyle &style)
{
    style.apply(this);

    setMarginText(line, text, style.style());
}


// Annotate a line.
void QsciScintilla::setMarginText(int line, const QsciStyledText &text)
{
    text.apply(this);

    setMarginText(line, text.text(), text.style());
}


// Annotate a line.
void QsciScintilla::setMarginText(int line, const QList<QsciStyledText> &text)
{
    char *styles;
    ScintillaBytes styled_text = styleText(text, &styles,
            SendScintilla(SCI_MARGINGETSTYLEOFFSET));

    SendScintilla(SCI_MARGINSETTEXT, line,
            ScintillaBytesConstData(styled_text));
    SendScintilla(SCI_MARGINSETSTYLES, line, styles);

    delete[] styles;
}


// Return the state of line numbers in a margin.
bool QsciScintilla::marginLineNumbers(int margin) const
{
    return SendScintilla(SCI_GETMARGINTYPEN, margin);
}


// Enable and disable line numbers in a margin.
void QsciScintilla::setMarginLineNumbers(int margin, bool lnrs)
{
    SendScintilla(SCI_SETMARGINTYPEN, margin,
            lnrs ? SC_MARGIN_NUMBER : SC_MARGIN_SYMBOL);
}


// Return the marker mask of a margin.
int QsciScintilla::marginMarkerMask(int margin) const
{
    return SendScintilla(SCI_GETMARGINMASKN, margin);
}


// Set the marker mask of a margin.
void QsciScintilla::setMarginMarkerMask(int margin,int mask)
{
    SendScintilla(SCI_SETMARGINMASKN, margin, mask);
}


// Return the state of a margin's sensitivity.
bool QsciScintilla::marginSensitivity(int margin) const
{
    return SendScintilla(SCI_GETMARGINSENSITIVEN, margin);
}


// Enable and disable a margin's sensitivity.
void QsciScintilla::setMarginSensitivity(int margin,bool sens)
{
    SendScintilla(SCI_SETMARGINSENSITIVEN, margin, sens);
}


// Return the width of a margin.
int QsciScintilla::marginWidth(int margin) const
{
    return SendScintilla(SCI_GETMARGINWIDTHN, margin);
}


// Set the width of a margin.
void QsciScintilla::setMarginWidth(int margin, int width)
{
    SendScintilla(SCI_SETMARGINWIDTHN, margin, width);
}


// Set the width of a margin to the width of some text.
void QsciScintilla::setMarginWidth(int margin, const QString &s)
{
    int width = SendScintilla(SCI_TEXTWIDTH, STYLE_LINENUMBER,
            ScintillaBytesConstData(textAsBytes(s)));

    setMarginWidth(margin, width);
}


// Set the background colour of all margins.
void QsciScintilla::setMarginsBackgroundColor(const QColor &col)
{
    handleStylePaperChange(col, STYLE_LINENUMBER);
}


// Set the foreground colour of all margins.
void QsciScintilla::setMarginsForegroundColor(const QColor &col)
{
    handleStyleColorChange(col, STYLE_LINENUMBER);
}


// Set the font of all margins.
void QsciScintilla::setMarginsFont(const QFont &f)
{
    setStylesFont(f, STYLE_LINENUMBER);
}


// Define an indicator.
int QsciScintilla::indicatorDefine(IndicatorStyle style, int indicatorNumber)
{
    checkIndicator(indicatorNumber);

    if (indicatorNumber >= 0)
        SendScintilla(SCI_INDICSETSTYLE, indicatorNumber,
                static_cast<long>(style));

    return indicatorNumber;
}


// Return the state of an indicator being drawn under the text.
bool QsciScintilla::indicatorDrawUnder(int indicatorNumber) const
{
    if (indicatorNumber < 0 || indicatorNumber >= INDIC_IME)
        return false;

    return SendScintilla(SCI_INDICGETUNDER, indicatorNumber);
}


// Set the state of indicators being drawn under the text.
void QsciScintilla::setIndicatorDrawUnder(bool under, int indicatorNumber)
{
    if (indicatorNumber < INDIC_IME)
    {
        // We ignore allocatedIndicators to allow any indicators defined
        // elsewhere (e.g. in lexers) to be set.
        if (indicatorNumber < 0)
        {
            for (int i = 0; i < INDIC_IME; ++i)
                SendScintilla(SCI_INDICSETUNDER, i, under);
        }
        else
        {
            SendScintilla(SCI_INDICSETUNDER, indicatorNumber, under);
        }
    }
}


// Set the indicator foreground colour.
void QsciScintilla::setIndicatorForegroundColor(const QColor &col,
        int indicatorNumber)
{
    if (indicatorNumber < INDIC_IME)
    {
        int alpha = col.alpha();

        // We ignore allocatedIndicators to allow any indicators defined
        // elsewhere (e.g. in lexers) to be set.
        if (indicatorNumber < 0)
        {
            for (int i = 0; i < INDIC_IME; ++i)
            {
                SendScintilla(SCI_INDICSETFORE, i, col);
                SendScintilla(SCI_INDICSETALPHA, i, alpha);
            }
        }
        else
        {
            SendScintilla(SCI_INDICSETFORE, indicatorNumber, col);
            SendScintilla(SCI_INDICSETALPHA, indicatorNumber, alpha);
        }
    }
}


// Set the indicator hover foreground colour.
void QsciScintilla::setIndicatorHoverForegroundColor(const QColor &col,
        int indicatorNumber)
{
    if (indicatorNumber < INDIC_IME)
    {
        // We ignore allocatedIndicators to allow any indicators defined
        // elsewhere (e.g. in lexers) to be set.
        if (indicatorNumber < 0)
        {
            for (int i = 0; i < INDIC_IME; ++i)
                SendScintilla(SCI_INDICSETHOVERFORE, i, col);
        }
        else
        {
            SendScintilla(SCI_INDICSETHOVERFORE, indicatorNumber, col);
        }
    }
}


// Set the indicator hover style.
void QsciScintilla::setIndicatorHoverStyle(IndicatorStyle style,
        int indicatorNumber)
{
    if (indicatorNumber < INDIC_IME)
    {
        // We ignore allocatedIndicators to allow any indicators defined
        // elsewhere (e.g. in lexers) to be set.
        if (indicatorNumber < 0)
        {
            for (int i = 0; i < INDIC_IME; ++i)
                SendScintilla(SCI_INDICSETHOVERSTYLE, i,
                        static_cast<long>(style));
        }
        else
        {
            SendScintilla(SCI_INDICSETHOVERSTYLE, indicatorNumber,
                    static_cast<long>(style));
        }
    }
}


// Set the indicator outline colour.
void QsciScintilla::setIndicatorOutlineColor(const QColor &col, int indicatorNumber)
{
    if (indicatorNumber < INDIC_IME)
    {
        int alpha = col.alpha();

        // We ignore allocatedIndicators to allow any indicators defined
        // elsewhere (e.g. in lexers) to be set.
        if (indicatorNumber < 0)
        {
            for (int i = 0; i < INDIC_IME; ++i)
                SendScintilla(SCI_INDICSETOUTLINEALPHA, i, alpha);
        }
        else
        {
            SendScintilla(SCI_INDICSETOUTLINEALPHA, indicatorNumber, alpha);
        }
    }
}


// Fill a range with an indicator.
void QsciScintilla::fillIndicatorRange(int lineFrom, int indexFrom,
        int lineTo, int indexTo, int indicatorNumber)
{
    if (indicatorNumber < INDIC_IME)
    {
        int start = positionFromLineIndex(lineFrom, indexFrom);
        int finish = positionFromLineIndex(lineTo, indexTo);

        // We ignore allocatedIndicators to allow any indicators defined
        // elsewhere (e.g. in lexers) to be set.
        if (indicatorNumber < 0)
        {
            for (int i = 0; i < INDIC_IME; ++i)
            {
                SendScintilla(SCI_SETINDICATORCURRENT, i);
                SendScintilla(SCI_INDICATORFILLRANGE, start, finish - start);
            }
        }
        else
        {
            SendScintilla(SCI_SETINDICATORCURRENT, indicatorNumber);
            SendScintilla(SCI_INDICATORFILLRANGE, start, finish - start);
        }
    }
}


// Clear a range with an indicator.
void QsciScintilla::clearIndicatorRange(int lineFrom, int indexFrom,
        int lineTo, int indexTo, int indicatorNumber)
{
    if (indicatorNumber < INDIC_IME)
    {
        int start = positionFromLineIndex(lineFrom, indexFrom);
        int finish = positionFromLineIndex(lineTo, indexTo);

        // We ignore allocatedIndicators to allow any indicators defined
        // elsewhere (e.g. in lexers) to be set.
        if (indicatorNumber < 0)
        {
            for (int i = 0; i < INDIC_IME; ++i)
            {
                SendScintilla(SCI_SETINDICATORCURRENT, i);
                SendScintilla(SCI_INDICATORCLEARRANGE, start, finish - start);
            }
        }
        else
        {
            SendScintilla(SCI_SETINDICATORCURRENT, indicatorNumber);
            SendScintilla(SCI_INDICATORCLEARRANGE, start, finish - start);
        }
    }
}


// Define a marker based on a symbol.
int QsciScintilla::markerDefine(MarkerSymbol sym, int markerNumber)
{
    checkMarker(markerNumber);

    if (markerNumber >= 0)
        SendScintilla(SCI_MARKERDEFINE, markerNumber, static_cast<long>(sym));

    return markerNumber;
}


// Define a marker based on a character.
int QsciScintilla::markerDefine(char ch, int markerNumber)
{
    checkMarker(markerNumber);

    if (markerNumber >= 0)
        SendScintilla(SCI_MARKERDEFINE, markerNumber,
                static_cast<long>(SC_MARK_CHARACTER) + ch);

    return markerNumber;
}


// Define a marker based on a QPixmap.
int QsciScintilla::markerDefine(const QPixmap &pm, int markerNumber)
{
    checkMarker(markerNumber);

    if (markerNumber >= 0)
        SendScintilla(SCI_MARKERDEFINEPIXMAP, markerNumber, pm);

    return markerNumber;
}


// Define a marker based on a QImage.
int QsciScintilla::markerDefine(const QImage &im, int markerNumber)
{
    checkMarker(markerNumber);

    if (markerNumber >= 0)
    {
        SendScintilla(SCI_RGBAIMAGESETHEIGHT, im.height());
        SendScintilla(SCI_RGBAIMAGESETWIDTH, im.width());
        SendScintilla(SCI_MARKERDEFINERGBAIMAGE, markerNumber, im);
    }

    return markerNumber;
}


// Add a marker to a line.
int QsciScintilla::markerAdd(int linenr, int markerNumber)
{
    if (markerNumber < 0 || markerNumber > MARKER_MAX || (allocatedMarkers & (1 << markerNumber)) == 0)
        return -1;

    return SendScintilla(SCI_MARKERADD, linenr, markerNumber);
}


// Get the marker mask for a line.
unsigned QsciScintilla::markersAtLine(int linenr) const
{
    return SendScintilla(SCI_MARKERGET, linenr);
}


// Delete a marker from a line.
void QsciScintilla::markerDelete(int linenr, int markerNumber)
{
    if (markerNumber <= MARKER_MAX)
    {
        if (markerNumber < 0)
        {
            unsigned am = allocatedMarkers;

            for (int m = 0; m <= MARKER_MAX; ++m)
            {
                if (am & 1)
                    SendScintilla(SCI_MARKERDELETE, linenr, m);

                am >>= 1;
            }
        }
        else if (allocatedMarkers & (1 << markerNumber))
            SendScintilla(SCI_MARKERDELETE, linenr, markerNumber);
    }
}


// Delete a marker from the text.
void QsciScintilla::markerDeleteAll(int markerNumber)
{
    if (markerNumber <= MARKER_MAX)
    {
        if (markerNumber < 0)
            SendScintilla(SCI_MARKERDELETEALL, -1);
        else if (allocatedMarkers & (1 << markerNumber))
            SendScintilla(SCI_MARKERDELETEALL, markerNumber);
    }
}


// Delete a marker handle from the text.
void QsciScintilla::markerDeleteHandle(int mhandle)
{
    SendScintilla(SCI_MARKERDELETEHANDLE, mhandle);
}


// Return the line containing a marker instance.
int QsciScintilla::markerLine(int mhandle) const
{
    return SendScintilla(SCI_MARKERLINEFROMHANDLE, mhandle);
}


// Search forwards for a marker.
int QsciScintilla::markerFindNext(int linenr, unsigned mask) const
{
    return SendScintilla(SCI_MARKERNEXT, linenr, mask);
}


// Search backwards for a marker.
int QsciScintilla::markerFindPrevious(int linenr, unsigned mask) const
{
    return SendScintilla(SCI_MARKERPREVIOUS, linenr, mask);
}


// Set the marker background colour.
void QsciScintilla::setMarkerBackgroundColor(const QColor &col, int markerNumber)
{
    if (markerNumber <= MARKER_MAX)
    {
        int alpha = col.alpha();

        // An opaque background would make the text invisible.
        if (alpha == 255)
            alpha = SC_ALPHA_NOALPHA;

        if (markerNumber < 0)
        {
            unsigned am = allocatedMarkers;

            for (int m = 0; m <= MARKER_MAX; ++m)
            {
                if (am & 1)
                {
                    SendScintilla(SCI_MARKERSETBACK, m, col);
                    SendScintilla(SCI_MARKERSETALPHA, m, alpha);
                }

                am >>= 1;
            }
        }
        else if (allocatedMarkers & (1 << markerNumber))
        {
            SendScintilla(SCI_MARKERSETBACK, markerNumber, col);
            SendScintilla(SCI_MARKERSETALPHA, markerNumber, alpha);
        }
    }
}


// Set the marker foreground colour.
void QsciScintilla::setMarkerForegroundColor(const QColor &col, int markerNumber)
{
    if (markerNumber <= MARKER_MAX)
    {
        if (markerNumber < 0)
        {
            unsigned am = allocatedMarkers;

            for (int m = 0; m <= MARKER_MAX; ++m)
            {
                if (am & 1)
                    SendScintilla(SCI_MARKERSETFORE, m, col);

                am >>= 1;
            }
        }
        else if (allocatedMarkers & (1 << markerNumber))
        {
            SendScintilla(SCI_MARKERSETFORE, markerNumber, col);
        }
    }
}


// Check a marker, allocating a marker number if necessary.
void QsciScintilla::checkMarker(int &markerNumber)
{
    allocateId(markerNumber, allocatedMarkers, 0, MARKER_MAX);
}


// Check an indicator, allocating an indicator number if necessary.
void QsciScintilla::checkIndicator(int &indicatorNumber)
{
    allocateId(indicatorNumber, allocatedIndicators, INDIC_CONTAINER,
            INDIC_IME - 1);
}


// Make sure an identifier is valid and allocate it if necessary.
void QsciScintilla::allocateId(int &id, unsigned &allocated, int min, int max)
{
    if (id >= 0)
    {
        // Note that we allow existing identifiers to be explicitly redefined.
        if (id > max)
            id = -1;
    }
    else
    {
        unsigned aids = allocated >> min;

        // Find the smallest unallocated identifier.
        for (id = min; id <= max; ++id)
        {
            if ((aids & 1) == 0)
                break;

            aids >>= 1;
        }
    }

    // Allocate the identifier if it is valid.
    if (id >= 0)
        allocated |= (1 << id);
}


// Reset the fold margin colours.
void QsciScintilla::resetFoldMarginColors()
{
    SendScintilla(SCI_SETFOLDMARGINHICOLOUR, 0, 0L);
    SendScintilla(SCI_SETFOLDMARGINCOLOUR, 0, 0L);
}


// Set the fold margin colours.
void QsciScintilla::setFoldMarginColors(const QColor &fore, const QColor &back)
{
    SendScintilla(SCI_SETFOLDMARGINHICOLOUR, 1, fore);
    SendScintilla(SCI_SETFOLDMARGINCOLOUR, 1, back);
}


// Set the call tips background colour.
void QsciScintilla::setCallTipsBackgroundColor(const QColor &col)
{
    SendScintilla(SCI_CALLTIPSETBACK, col);
}


// Set the call tips foreground colour.
void QsciScintilla::setCallTipsForegroundColor(const QColor &col)
{
    SendScintilla(SCI_CALLTIPSETFORE, col);
}


// Set the call tips highlight colour.
void QsciScintilla::setCallTipsHighlightColor(const QColor &col)
{
    SendScintilla(SCI_CALLTIPSETFOREHLT, col);
}


// Set the matched brace background colour.
void QsciScintilla::setMatchedBraceBackgroundColor(const QColor &col)
{
    SendScintilla(SCI_STYLESETBACK, STYLE_BRACELIGHT, col);
}


// Set the matched brace foreground colour.
void QsciScintilla::setMatchedBraceForegroundColor(const QColor &col)
{
    SendScintilla(SCI_STYLESETFORE, STYLE_BRACELIGHT, col);
}


// Set the matched brace indicator.
void QsciScintilla::setMatchedBraceIndicator(int indicatorNumber)
{
    SendScintilla(SCI_BRACEHIGHLIGHTINDICATOR, 1, indicatorNumber);
}


// Reset the matched brace indicator.
void QsciScintilla::resetMatchedBraceIndicator()
{
    SendScintilla(SCI_BRACEHIGHLIGHTINDICATOR, 0, 0L);
}


// Set the unmatched brace background colour.
void QsciScintilla::setUnmatchedBraceBackgroundColor(const QColor &col)
{
    SendScintilla(SCI_STYLESETBACK, STYLE_BRACEBAD, col);
}


// Set the unmatched brace foreground colour.
void QsciScintilla::setUnmatchedBraceForegroundColor(const QColor &col)
{
    SendScintilla(SCI_STYLESETFORE, STYLE_BRACEBAD, col);
}


// Set the unmatched brace indicator.
void QsciScintilla::setUnmatchedBraceIndicator(int indicatorNumber)
{
    SendScintilla(SCI_BRACEBADLIGHTINDICATOR, 1, indicatorNumber);
}


// Reset the unmatched brace indicator.
void QsciScintilla::resetUnmatchedBraceIndicator()
{
    SendScintilla(SCI_BRACEBADLIGHTINDICATOR, 0, 0L);
}


// Detach any lexer.
void QsciScintilla::detachLexer()
{
    if (!lex.isNull())
    {
        lex->setEditor(0);
        lex->disconnect(this);

        SendScintilla(SCI_STYLERESETDEFAULT);
        SendScintilla(SCI_STYLECLEARALL);
    }
}


// Set the lexer.
void QsciScintilla::setLexer(QsciLexer *lexer)
{
    // Detach any current lexer.
    detachLexer();

    // Connect up the new lexer.
    lex = lexer;

    if (lex)
    {
        SendScintilla(SCI_CLEARDOCUMENTSTYLE);

        if (lex->lexer())
            SendScintilla(SCI_SETLEXERLANGUAGE, lex->lexer());
        else
            SendScintilla(SCI_SETLEXER, lex->lexerId());

        lex->setEditor(this);

        connect(lex,SIGNAL(colorChanged(const QColor &, int)),
                SLOT(handleStyleColorChange(const QColor &, int)));
        connect(lex,SIGNAL(eolFillChanged(bool, int)),
                SLOT(handleStyleEolFillChange(bool, int)));
        connect(lex,SIGNAL(fontChanged(const QFont &, int)),
                SLOT(handleStyleFontChange(const QFont &, int)));
        connect(lex,SIGNAL(paperChanged(const QColor &, int)),
                SLOT(handleStylePaperChange(const QColor &, int)));
        connect(lex,SIGNAL(propertyChanged(const char *, const char *)),
                SLOT(handlePropertyChange(const char *, const char *)));

        SendScintilla(SCI_SETPROPERTY, "fold", "1");
        SendScintilla(SCI_SETPROPERTY, "fold.html", "1");

        // Set the keywords.  Scintilla allows for sets numbered 0 to
        // KEYWORDSET_MAX (although the lexers only seem to exploit 0 to
        // KEYWORDSET_MAX - 1).  We number from 1 in line with SciTE's property
        // files.
        for (int k = 0; k <= KEYWORDSET_MAX; ++k)
        {
            const char *kw = lex -> keywords(k + 1);

            if (!kw)
                kw = "";

            SendScintilla(SCI_SETKEYWORDS, k, kw);
        }

        // Initialise each style.  Do the default first so its (possibly
        // incorrect) font setting gets reset when style 0 is set.
        setLexerStyle(STYLE_DEFAULT);

        int nrStyles = 1 << SendScintilla(SCI_GETSTYLEBITS);

        for (int s = 0; s < nrStyles; ++s)
            if (!lex->description(s).isEmpty())
                setLexerStyle(s);

        // Initialise the properties.
        lex->refreshProperties();

        // Set the auto-completion fillups and word separators.
        setAutoCompletionFillupsEnabled(fillups_enabled);
        wseps = lex->autoCompletionWordSeparators();

        wchars = lex->wordCharacters();

        if (!wchars)
            wchars = defaultWordChars;

        SendScintilla(SCI_AUTOCSETIGNORECASE, !lex->caseSensitive());

        recolor();
    }
    else
    {
        SendScintilla(SCI_SETLEXER, SCLEX_CONTAINER);

        setColor(nl_text_colour);
        setPaper(nl_paper_colour);

        SendScintilla(SCI_AUTOCSETFILLUPS, "");
        SendScintilla(SCI_AUTOCSETIGNORECASE, false);
        wseps.clear();
        wchars = defaultWordChars;
    }
}


// Set a particular style of the current lexer.
void QsciScintilla::setLexerStyle(int style)
{
    handleStyleColorChange(lex->color(style), style);
    handleStyleEolFillChange(lex->eolFill(style), style);
    handleStyleFontChange(lex->font(style), style);
    handleStylePaperChange(lex->paper(style), style);
}


// Get the current lexer.
QsciLexer *QsciScintilla::lexer() const
{
    return lex;
}


// Handle a change in lexer style foreground colour.
void QsciScintilla::handleStyleColorChange(const QColor &c, int style)
{
    SendScintilla(SCI_STYLESETFORE, style, c);
}


// Handle a change in lexer style end-of-line fill.
void QsciScintilla::handleStyleEolFillChange(bool eolfill, int style)
{
    SendScintilla(SCI_STYLESETEOLFILLED, style, eolfill);
}


// Handle a change in lexer style font.
void QsciScintilla::handleStyleFontChange(const QFont &f, int style)
{
    setStylesFont(f, style);

    if (style == lex->braceStyle())
    {
        setStylesFont(f, STYLE_BRACELIGHT);
        setStylesFont(f, STYLE_BRACEBAD);
    }
}


// Set the font for a style.
void QsciScintilla::setStylesFont(const QFont &f, int style)
{
    SendScintilla(SCI_STYLESETFONT, style, f.family().toLatin1().data());
    SendScintilla(SCI_STYLESETSIZEFRACTIONAL, style,
            long(f.pointSizeF() * SC_FONT_SIZE_MULTIPLIER));

    // Pass the Qt weight via the back door.
    SendScintilla(SCI_STYLESETWEIGHT, style, -f.weight());

    SendScintilla(SCI_STYLESETITALIC, style, f.italic());
    SendScintilla(SCI_STYLESETUNDERLINE, style, f.underline());

    // Tie the font settings of the default style to that of style 0 (the style
    // conventionally used for whitespace by lexers).  This is needed so that
    // fold marks, indentations, edge columns etc are set properly.
    if (style == 0)
        setStylesFont(f, STYLE_DEFAULT);
}


// Handle a change in lexer style background colour.
void QsciScintilla::handleStylePaperChange(const QColor &c, int style)
{
    SendScintilla(SCI_STYLESETBACK, style, c);
}


// Handle a change in lexer property.
void QsciScintilla::handlePropertyChange(const char *prop, const char *val)
{
    SendScintilla(SCI_SETPROPERTY, prop, val);
}


// Handle a change to the user visible user interface.
void QsciScintilla::handleUpdateUI(int)
{
    int newPos = SendScintilla(SCI_GETCURRENTPOS);

    if (newPos != oldPos)
    {
        oldPos = newPos;

        int line = SendScintilla(SCI_LINEFROMPOSITION, newPos);
        int col = SendScintilla(SCI_GETCOLUMN, newPos);

        emit cursorPositionChanged(line, col);
    }

    if (braceMode != NoBraceMatch)
        braceMatch();
}


// Handle brace matching.
void QsciScintilla::braceMatch()
{
    long braceAtCaret, braceOpposite;

    findMatchingBrace(braceAtCaret, braceOpposite, braceMode);

    if (braceAtCaret >= 0 && braceOpposite < 0)
    {
        SendScintilla(SCI_BRACEBADLIGHT, braceAtCaret);
        SendScintilla(SCI_SETHIGHLIGHTGUIDE, 0UL);
    }
    else
    {
        char chBrace = SendScintilla(SCI_GETCHARAT, braceAtCaret);

        SendScintilla(SCI_BRACEHIGHLIGHT, braceAtCaret, braceOpposite);

        long columnAtCaret = SendScintilla(SCI_GETCOLUMN, braceAtCaret);
        long columnOpposite = SendScintilla(SCI_GETCOLUMN, braceOpposite);

        if (chBrace == ':')
        {
            long lineStart = SendScintilla(SCI_LINEFROMPOSITION, braceAtCaret);
            long indentPos = SendScintilla(SCI_GETLINEINDENTPOSITION,
                    lineStart);
            long indentPosNext = SendScintilla(SCI_GETLINEINDENTPOSITION,
                    lineStart + 1);

            columnAtCaret = SendScintilla(SCI_GETCOLUMN, indentPos);

            long columnAtCaretNext = SendScintilla(SCI_GETCOLUMN,
                    indentPosNext);
            long indentSize = SendScintilla(SCI_GETINDENT);

            if (columnAtCaretNext - indentSize > 1)
                columnAtCaret = columnAtCaretNext - indentSize;

            if (columnOpposite == 0)
                columnOpposite = columnAtCaret;
        }

        long column = columnAtCaret;

        if (column > columnOpposite)
            column = columnOpposite;

        SendScintilla(SCI_SETHIGHLIGHTGUIDE, column);
    }
}


// Check if the character at a position is a brace.
long QsciScintilla::checkBrace(long pos, int brace_style, bool &colonMode)
{
    long brace_pos = -1;
    char ch = SendScintilla(SCI_GETCHARAT, pos);

    if (ch == ':')
    {
        // A bit of a hack, we should really use a virtual.
        if (!lex.isNull() && qstrcmp(lex->lexer(), "python") == 0)
        {
            brace_pos = pos;
            colonMode = true;
        }
    }
    else if (ch && strchr("[](){}<>", ch))
    {
        if (brace_style < 0)
            brace_pos = pos;
        else
        {
            int style = SendScintilla(SCI_GETSTYLEAT, pos) & 0x1f;

            if (style == brace_style)
                brace_pos = pos;
        }
    }

    return brace_pos;
}


// Find a brace and it's match.  Return true if the current position is inside
// a pair of braces.
bool QsciScintilla::findMatchingBrace(long &brace, long &other,BraceMatch mode)
{
    bool colonMode = false;
    int brace_style = (lex.isNull() ? -1 : lex->braceStyle());

    brace = -1;
    other = -1;

    long caretPos = SendScintilla(SCI_GETCURRENTPOS);

    if (caretPos > 0)
        brace = checkBrace(caretPos - 1, brace_style, colonMode);

    bool isInside = false;

    if (brace < 0 && mode == SloppyBraceMatch)
    {
        brace = checkBrace(caretPos, brace_style, colonMode);

        if (brace >= 0 && !colonMode)
            isInside = true;
    }

    if (brace >= 0)
    {
        if (colonMode)
        {
            // Find the end of the Python indented block.
            long lineStart = SendScintilla(SCI_LINEFROMPOSITION, brace);
            long lineMaxSubord = SendScintilla(SCI_GETLASTCHILD, lineStart, -1);

            other = SendScintilla(SCI_GETLINEENDPOSITION, lineMaxSubord);
        }
        else
            other = SendScintilla(SCI_BRACEMATCH, brace);

        if (other > brace)
            isInside = !isInside;
    }

    return isInside;
}


// Move to the matching brace.
void QsciScintilla::moveToMatchingBrace()
{
    gotoMatchingBrace(false);
}


// Select to the matching brace.
void QsciScintilla::selectToMatchingBrace()
{
    gotoMatchingBrace(true);
}


// Move to the matching brace and optionally select the text.
void QsciScintilla::gotoMatchingBrace(bool select)
{
    long braceAtCaret;
    long braceOpposite;

    bool isInside = findMatchingBrace(braceAtCaret, braceOpposite,
            SloppyBraceMatch);

    if (braceOpposite >= 0)
    {
        // Convert the character positions into caret positions based on
        // whether the caret position was inside or outside the braces.
        if (isInside)
        {
            if (braceOpposite > braceAtCaret)
                braceAtCaret++;
            else
                braceOpposite++;
        }
        else
        {
            if (braceOpposite > braceAtCaret)
                braceOpposite++;
            else
                braceAtCaret++;
        }

        ensureLineVisible(SendScintilla(SCI_LINEFROMPOSITION, braceOpposite));

        if (select)
            SendScintilla(SCI_SETSEL, braceAtCaret, braceOpposite);
        else
            SendScintilla(SCI_SETSEL, braceOpposite, braceOpposite);
    }
}


// Return a position from a line number and an index within the line.
int QsciScintilla::positionFromLineIndex(int line, int index) const
{
    int pos = SendScintilla(SCI_POSITIONFROMLINE, line);

    // Allow for multi-byte characters.
    for(int i = 0; i < index; i++)
        pos = SendScintilla(SCI_POSITIONAFTER, pos);

    return pos;
}


// Return a line number and an index within the line from a position.
void QsciScintilla::lineIndexFromPosition(int position, int *line, int *index) const
{
    int lin = SendScintilla(SCI_LINEFROMPOSITION, position);
    int linpos = SendScintilla(SCI_POSITIONFROMLINE, lin);
    int indx = 0;

    // Allow for multi-byte characters.
    while (linpos < position)
    {
        int new_linpos = SendScintilla(SCI_POSITIONAFTER, linpos);

        // If the position hasn't moved then we must be at the end of the text
        // (which implies that the position passed was beyond the end of the
        // text).
        if (new_linpos == linpos)
            break;

        linpos = new_linpos;
        ++indx;
    }

    *line = lin;
    *index = indx;
}


// Set the source of the automatic auto-completion list.
void QsciScintilla::setAutoCompletionSource(AutoCompletionSource source)
{
    acSource = source;
}


// Set the threshold for automatic auto-completion.
void QsciScintilla::setAutoCompletionThreshold(int thresh)
{
    acThresh = thresh;
}


// Set the auto-completion word separators if there is no current lexer.
void QsciScintilla::setAutoCompletionWordSeparators(const QStringList &separators)
{
    if (lex.isNull())
        wseps = separators;
}


// Explicitly auto-complete from all sources.
void QsciScintilla::autoCompleteFromAll()
{
    startAutoCompletion(AcsAll, false, use_single != AcusNever);
}


// Explicitly auto-complete from the APIs.
void QsciScintilla::autoCompleteFromAPIs()
{
    startAutoCompletion(AcsAPIs, false, use_single != AcusNever);
}


// Explicitly auto-complete from the document.
void QsciScintilla::autoCompleteFromDocument()
{
    startAutoCompletion(AcsDocument, false, use_single != AcusNever);
}


// Check if a character can be in a word.
bool QsciScintilla::isWordCharacter(char ch) const
{
    return (strchr(wchars, ch) != NULL);
}


// Return the set of valid word characters.
const char *QsciScintilla::wordCharacters() const
{
    return wchars;
}


// Recolour the document.
void QsciScintilla::recolor(int start, int end)
{
    SendScintilla(SCI_COLOURISE, start, end);
}


// Registered a QPixmap image.
void QsciScintilla::registerImage(int id, const QPixmap &pm)
{
    SendScintilla(SCI_REGISTERIMAGE, id, pm);
}


// Registered a QImage image.
void QsciScintilla::registerImage(int id, const QImage &im)
{
    SendScintilla(SCI_RGBAIMAGESETHEIGHT, im.height());
    SendScintilla(SCI_RGBAIMAGESETWIDTH, im.width());
    SendScintilla(SCI_REGISTERRGBAIMAGE, id, im);
}


// Clear all registered images.
void QsciScintilla::clearRegisteredImages()
{
    SendScintilla(SCI_CLEARREGISTEREDIMAGES);
}


// Enable auto-completion fill-ups.
void QsciScintilla::setAutoCompletionFillupsEnabled(bool enable)
{
    const char *fillups;

    if (!enable)
        fillups = "";
    else if (!lex.isNull())
        fillups = lex->autoCompletionFillups();
    else
        fillups = explicit_fillups.data();

    SendScintilla(SCI_AUTOCSETFILLUPS, fillups);

    fillups_enabled = enable;
}


// See if auto-completion fill-ups are enabled.
bool QsciScintilla::autoCompletionFillupsEnabled() const
{
    return fillups_enabled;
}


// Set the fill-up characters for auto-completion if there is no current lexer.
void QsciScintilla::setAutoCompletionFillups(const char *fillups)
{
    explicit_fillups = fillups;
    setAutoCompletionFillupsEnabled(fillups_enabled);
}


// Set the case sensitivity for auto-completion.
void QsciScintilla::setAutoCompletionCaseSensitivity(bool cs)
{
    SendScintilla(SCI_AUTOCSETIGNORECASE, !cs);
}


// Return the case sensitivity for auto-completion.
bool QsciScintilla::autoCompletionCaseSensitivity() const
{
    return !SendScintilla(SCI_AUTOCGETIGNORECASE);
}


// Set the replace word mode for auto-completion.
void QsciScintilla::setAutoCompletionReplaceWord(bool replace)
{
    SendScintilla(SCI_AUTOCSETDROPRESTOFWORD, replace);
}


// Return the replace word mode for auto-completion.
bool QsciScintilla::autoCompletionReplaceWord() const
{
    return SendScintilla(SCI_AUTOCGETDROPRESTOFWORD);
}


// Set the single item mode for auto-completion.
void QsciScintilla::setAutoCompletionUseSingle(AutoCompletionUseSingle single)
{
    use_single = single;
}


// Return the single item mode for auto-completion.
QsciScintilla::AutoCompletionUseSingle QsciScintilla::autoCompletionUseSingle() const
{
    return use_single;
}


// Set the single item mode for auto-completion (deprecated).
void QsciScintilla::setAutoCompletionShowSingle(bool single)
{
    use_single = (single ? AcusExplicit : AcusNever);
}


// Return the single item mode for auto-completion (deprecated).
bool QsciScintilla::autoCompletionShowSingle() const
{
    return (use_single != AcusNever);
}


// Set current call tip position.
void QsciScintilla::setCallTipsPosition(CallTipsPosition position)
{
    SendScintilla(SCI_CALLTIPSETPOSITION, (position == CallTipsAboveText));
    call_tips_position = position;
}


// Set current call tip style.
void QsciScintilla::setCallTipsStyle(CallTipsStyle style)
{
    call_tips_style = style;
}


// Set maximum number of call tips displayed.
void QsciScintilla::setCallTipsVisible(int nr)
{
    maxCallTips = nr;
}


// Set the document to display.
void QsciScintilla::setDocument(const QsciDocument &document)
{
    if (doc.pdoc != document.pdoc)
    {
        doc.undisplay(this);
        doc.attach(document);
        doc.display(this,&document);
    }
}


// Ensure the document is read-write and return true if was was read-only.
bool QsciScintilla::ensureRW()
{
    bool ro = isReadOnly();

    if (ro)
        setReadOnly(false);

    return ro;
}


// Return the number of the first visible line.
int QsciScintilla::firstVisibleLine() const
{
    return SendScintilla(SCI_GETFIRSTVISIBLELINE);
}


// Set the number of the first visible line.
void QsciScintilla::setFirstVisibleLine(int linenr)
{
    SendScintilla(SCI_SETFIRSTVISIBLELINE, linenr);
}


// Return the height in pixels of the text in a particular line.
int QsciScintilla::textHeight(int linenr) const
{
    return SendScintilla(SCI_TEXTHEIGHT, linenr);
}


// See if auto-completion or user list is active.
bool QsciScintilla::isListActive() const
{
    return SendScintilla(SCI_AUTOCACTIVE);
}


// Cancel any current auto-completion or user list.
void QsciScintilla::cancelList()
{
    SendScintilla(SCI_AUTOCCANCEL);
}


// Handle a selection from the auto-completion list.
void QsciScintilla::handleAutoCompletionSelection()
{
    if (!lex.isNull())
    {
        QsciAbstractAPIs *apis = lex->apis();

        if (apis)
            apis->autoCompletionSelected(acSelection);
    }
}


// Display a user list.
void QsciScintilla::showUserList(int id, const QStringList &list)
{
    // Sanity check to make sure auto-completion doesn't get confused.
    if (id <= 0)
        return;

    SendScintilla(SCI_AUTOCSETSEPARATOR, userSeparator);

    ScintillaBytes s = textAsBytes(list.join(QChar(userSeparator)));
    SendScintilla(SCI_USERLISTSHOW, id, ScintillaBytesConstData(s));
}


// Translate the SCN_USERLISTSELECTION notification into something more useful.
void QsciScintilla::handleUserListSelection(const char *text, int id)
{
    emit userListActivated(id, QString(text));

    // Make sure the editor hasn't been deactivated as a side effect.
    activateWindow();
}


// Return the case sensitivity of any lexer.
bool QsciScintilla::caseSensitive() const
{
    return lex.isNull() ? true : lex->caseSensitive();
}


// Return true if the current list is an auto-completion list rather than a
// user list.
bool QsciScintilla::isAutoCompletionList() const
{
    return (SendScintilla(SCI_AUTOCGETSEPARATOR) == acSeparator);
}


// Read the text from a QIODevice.
bool QsciScintilla::read(QIODevice *io)
{
    const int min_size = 1024 * 8;

    int buf_size = min_size;
    char *buf = new char[buf_size];

    int data_len = 0;
    bool ok = true;

    qint64 part;

    // Read the whole lot in so we don't have to worry about character
    // boundaries.
    do
    {
        // Make sure there is a minimum amount of room.
        if (buf_size - data_len < min_size)
        {
            buf_size *= 2;
            char *new_buf = new char[buf_size * 2];

            memcpy(new_buf, buf, data_len);
            delete[] buf;
            buf = new_buf;
        }

        part = io->read(buf + data_len, buf_size - data_len - 1);
        data_len += part;
    }
    while (part > 0);

    if (part < 0)
        ok = false;
    else
    {
        buf[data_len] = '\0';

        bool ro = ensureRW();

        SendScintilla(SCI_SETTEXT, buf);
        SendScintilla(SCI_EMPTYUNDOBUFFER);

        setReadOnly(ro);
    }

    delete[] buf;

    return ok;
}


// Write the text to a QIODevice.
bool QsciScintilla::write(QIODevice *io) const
{
    const char *buf = reinterpret_cast<const char *>(SendScintillaPtrResult(SCI_GETCHARACTERPOINTER));

    const char *bp = buf;
    uint buflen = qstrlen(buf);

    while (buflen > 0)
    {
        qint64 part = io->write(bp, buflen);

        if (part < 0)
            return false;

        bp += part;
        buflen -= part;
    }

    return true;
}


// Return the word at the given coordinates.
QString QsciScintilla::wordAtLineIndex(int line, int index) const
{
    return wordAtPosition(positionFromLineIndex(line, index));
}


// Return the word at the given coordinates.
QString QsciScintilla::wordAtPoint(const QPoint &point) const
{
    long close_pos = SendScintilla(SCI_POSITIONFROMPOINTCLOSE, point.x(),
            point.y());

    return wordAtPosition(close_pos);
}


// Return the word at the given position.
QString QsciScintilla::wordAtPosition(int position) const
{
    if (position < 0)
        return QString();

    long start_pos = SendScintilla(SCI_WORDSTARTPOSITION, position, true);
    long end_pos = SendScintilla(SCI_WORDENDPOSITION, position, true);
    int word_len = end_pos - start_pos;

    if (word_len <= 0)
        return QString();

    char *buf = new char[word_len + 1];
    SendScintilla(SCI_GETTEXTRANGE, start_pos, end_pos, buf);
    QString word = bytesAsText(buf);
    delete[] buf;

    return word;
}


// Return the display style for annotations.
QsciScintilla::AnnotationDisplay QsciScintilla::annotationDisplay() const
{
    return (AnnotationDisplay)SendScintilla(SCI_ANNOTATIONGETVISIBLE);
}


// Set the display style for annotations.
void QsciScintilla::setAnnotationDisplay(QsciScintilla::AnnotationDisplay display)
{
    SendScintilla(SCI_ANNOTATIONSETVISIBLE, display);
    setScrollBars();
}


// Clear annotations.
void QsciScintilla::clearAnnotations(int line)
{
    if (line >= 0)
        SendScintilla(SCI_ANNOTATIONSETTEXT, line, (const char *)0);
    else
        SendScintilla(SCI_ANNOTATIONCLEARALL);

    setScrollBars();
}


// Annotate a line.
void QsciScintilla::annotate(int line, const QString &text, int style)
{
    int style_offset = SendScintilla(SCI_ANNOTATIONGETSTYLEOFFSET);

    ScintillaBytes s = textAsBytes(text);

    SendScintilla(SCI_ANNOTATIONSETTEXT, line, ScintillaBytesConstData(s));
    SendScintilla(SCI_ANNOTATIONSETSTYLE, line, style - style_offset);

    setScrollBars();
}


// Annotate a line.
void QsciScintilla::annotate(int line, const QString &text, const QsciStyle &style)
{
    style.apply(this);

    annotate(line, text, style.style());
}


// Annotate a line.
void QsciScintilla::annotate(int line, const QsciStyledText &text)
{
    text.apply(this);

    annotate(line, text.text(), text.style());
}


// Annotate a line.
void QsciScintilla::annotate(int line, const QList<QsciStyledText> &text)
{
    char *styles;
    ScintillaBytes styled_text = styleText(text, &styles,
            SendScintilla(SCI_ANNOTATIONGETSTYLEOFFSET));

    SendScintilla(SCI_ANNOTATIONSETTEXT, line,
            ScintillaBytesConstData(styled_text));
    SendScintilla(SCI_ANNOTATIONSETSTYLES, line, styles);

    delete[] styles;
}


// Get the annotation for a line, if any.
QString QsciScintilla::annotation(int line) const
{
    char *buf = new char[SendScintilla(SCI_ANNOTATIONGETTEXT, line, (const char *)0) + 1];

    buf[SendScintilla(SCI_ANNOTATIONGETTEXT, line, buf)] = '\0';

    QString qs = bytesAsText(buf);
    delete[] buf;

    return qs;
}


// Convert a list of styled text to the low-level arrays.
QsciScintillaBase::ScintillaBytes QsciScintilla::styleText(const QList<QsciStyledText> &styled_text, char **styles, int style_offset)
{
    QString text;
    int i;

    // Build the full text.
    for (i = 0; i < styled_text.count(); ++i)
    {
        const QsciStyledText &st = styled_text[i];

        st.apply(this);

        text.append(st.text());
    }

    ScintillaBytes s = textAsBytes(text);

    // There is a style byte for every byte.
    char *sp = *styles = new char[s.length()];

    for (i = 0; i < styled_text.count(); ++i)
    {
        const QsciStyledText &st = styled_text[i];
        ScintillaBytes part = textAsBytes(st.text());
        int part_length = part.length();

        for (int c = 0; c < part_length; ++c)
            *sp++ = (char)(st.style() - style_offset);
    }

    return s;
}


// Convert Scintilla modifiers to the Qt equivalent.
int QsciScintilla::mapModifiers(int modifiers)
{
    int state = 0;

    if (modifiers & SCMOD_SHIFT)
        state |= Qt::ShiftModifier;

    if (modifiers & SCMOD_CTRL)
        state |= Qt::ControlModifier;

    if (modifiers & SCMOD_ALT)
        state |= Qt::AltModifier;

    if (modifiers & (SCMOD_SUPER | SCMOD_META))
        state |= Qt::MetaModifier;

    return state;
}


// Re-implemented to handle shortcut overrides.
bool QsciScintilla::event(QEvent *e)
{
    if (e->type() == QEvent::ShortcutOverride && !isReadOnly())
    {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);

        if (ke->key())
        {
            // We want ordinary characters.
            if ((ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier || ke->modifiers() == Qt::KeypadModifier) && ke->key() < Qt::Key_Escape)
            {
                ke->accept();
                return true;
            }

            // We want any key that is bound.
            QsciCommand *cmd = stdCmds->boundTo(ke->key() | (ke->modifiers() & ~Qt::KeypadModifier));

            if (cmd)
            {
                ke->accept();
                return true;
            }
        }
    }

    return QsciScintillaBase::event(e);
}


// Re-implemented to handle chenges to the enabled state.
void QsciScintilla::changeEvent(QEvent *e)
{
    QsciScintillaBase::changeEvent(e);

    if (e->type() != QEvent::EnabledChange)
        return;

    if (isEnabled())
        SendScintilla(SCI_SETCARETSTYLE, CARETSTYLE_LINE);
    else
        SendScintilla(SCI_SETCARETSTYLE, CARETSTYLE_INVISIBLE);

    QColor fore = palette().color(QPalette::Disabled, QPalette::Text);
    QColor back = palette().color(QPalette::Disabled, QPalette::Base);

    if (lex.isNull())
    {
        if (isEnabled())
        {
            fore = nl_text_colour;
            back = nl_paper_colour;
        }

        SendScintilla(SCI_STYLESETFORE, 0, fore);

        // Assume style 0 applies to everything so that we don't need to use
        // SCI_STYLECLEARALL which clears everything.  We still have to set the
        // default style as well for the background without any text.
        SendScintilla(SCI_STYLESETBACK, 0, back);
        SendScintilla(SCI_STYLESETBACK, STYLE_DEFAULT, back);
    }
    else
    {
        setEnabledColors(STYLE_DEFAULT, fore, back);

        int nrStyles = 1 << SendScintilla(SCI_GETSTYLEBITS);

        for (int s = 0; s < nrStyles; ++s)
            if (!lex->description(s).isNull())
                setEnabledColors(s, fore, back);
    }
}


// Set the foreground and background colours for a style.
void QsciScintilla::setEnabledColors(int style, QColor &fore, QColor &back)
{
    if (isEnabled())
    {
        fore = lex->color(style);
        back = lex->paper(style);
    }

    handleStyleColorChange(fore, style);
    handleStylePaperChange(back, style);
}


// Re-implemented to implement a more Qt-like context menu.
void QsciScintilla::contextMenuEvent(QContextMenuEvent *e)
{
    QMenu *menu = createStandardContextMenu();

    if (menu)
    {
        menu->setAttribute(Qt::WA_DeleteOnClose);
        menu->popup(e->globalPos());
    }
}


// Create an instance of the standard context menu.
QMenu *QsciScintilla::createStandardContextMenu()
{
    bool read_only = isReadOnly();
    bool has_selection = hasSelectedText();
    QMenu *menu = new QMenu(this);
    QAction *action;

    if (!read_only)
    {
        action = menu->addAction(tr("&Undo"), this, SLOT(undo()));
        set_shortcut(action, QsciCommand::Undo);
        action->setEnabled(isUndoAvailable());

        action = menu->addAction(tr("&Redo"), this, SLOT(redo()));
        set_shortcut(action, QsciCommand::Redo);
        action->setEnabled(isRedoAvailable());

        menu->addSeparator();

        action = menu->addAction(tr("Cu&t"), this, SLOT(cut()));
        set_shortcut(action, QsciCommand::SelectionCut);
        action->setEnabled(has_selection);
    }

    action = menu->addAction(tr("&Copy"), this, SLOT(copy()));
    set_shortcut(action, QsciCommand::SelectionCopy);
    action->setEnabled(has_selection);

    if (!read_only)
    {
        action = menu->addAction(tr("&Paste"), this, SLOT(paste()));
        set_shortcut(action, QsciCommand::Paste);
        action->setEnabled(SendScintilla(SCI_CANPASTE));

        action = menu->addAction(tr("Delete"), this, SLOT(delete_selection()));
        action->setEnabled(has_selection);
    }

    if (!menu->isEmpty())
        menu->addSeparator();

    action = menu->addAction(tr("Select All"), this, SLOT(selectAll()));
    set_shortcut(action, QsciCommand::SelectAll);
    action->setEnabled(length() != 0);

    return menu;
}


// Set the shortcut for an action using any current key binding.
void QsciScintilla::set_shortcut(QAction *action, QsciCommand::Command cmd_id) const
{
    QsciCommand *cmd = stdCmds->find(cmd_id);

    if (cmd && cmd->key())
        action->setShortcut(QKeySequence(cmd->key()));
}


// Delete the current selection.
void QsciScintilla::delete_selection()
{
    SendScintilla(SCI_CLEAR);
}