File: sourcesyneditor.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (2959 lines) | stat: -rw-r--r-- 98,768 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
{
/***************************************************************************
                               SourceSynEditor
                             -------------------

 ***************************************************************************/

 ***************************************************************************
 *                                                                         *
 *   This source is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code is distributed in the hope that it will be useful, but      *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   General Public License for more details.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.   *
 *                                                                         *
 ***************************************************************************

  Abstract:
    SynEdit extensions for the IDE
    - DebugMarks: Mark lines with debug info
}
unit SourceSynEditor;

{$mode objfpc}{$H+}

interface

{$IFDEF Windows}
  {$IFnDEF WithoutWinIME}
    {$DEFINE WinIME}
  {$ENDIF}
{$ENDIF}

{$I ide.inc}

uses
  {$IFDEF WinIME}
  LazSynIMM,
  {$ENDIF}
  Classes, SysUtils,
  // LCL
  Controls, LCLProc, LCLType, Graphics, Menus, ImgList,
  // synedit
  SynEdit, SynEditMiscClasses, SynGutter, SynGutterBase, SynEditMarks,
  SynEditTypes, SynGutterLineNumber, SynGutterCodeFolding, SynGutterMarks,
  SynGutterChanges, SynGutterLineOverview, SynEditMarkup,
  SynEditMarkupGutterMark, SynEditMarkupSpecialLine, SynEditTextBuffer,
  SynEditFoldedView, SynTextDrawer, SynEditTextBase, LazSynEditText,
  SynPluginTemplateEdit, SynPluginSyncroEdit, LazSynTextArea,
  SynEditHighlighter, SynEditHighlighterFoldBase, SynHighlighterPas,
  SynEditMarkupHighAll, SynEditKeyCmds, SynEditMarkupIfDef, SynEditMiscProcs,
  SynPluginMultiCaret, SynEditPointClasses,
  SynEditMarkupFoldColoring,
  etSrcEditMarks, LazarusIDEStrConsts;

type

  TIDESynGutterMarks = class;
  {$IFDEF WithSynDebugGutter}
  TIDESynGutterDebugHL = class;
  {$ENDIF}

  { TSourceLazSynTopInfoView }

  TSourceLazSynTopInfoView = class(TLazSynDisplayViewEx)
  private
    FLineMapCount: integer;
    FLineMap: array of integer;
    function GetLineMap(Index: Integer): Integer;
    procedure SetLineMap(Index: Integer; AValue: Integer);
    procedure SetLineMapCount(AValue: integer);
  public
    procedure SetHighlighterTokensLine(ALine: TLineIdx; out ARealLine: TLineIdx); override;
    function GetLinesCount: Integer; override;
    function TextToViewIndex(AIndex: TLineIdx): TLineRange; override;
    function ViewToTextIndex(AIndex: TLineIdx): TLineIdx; override;
  public
    constructor Create;
    property LineMapCount: integer read FLineMapCount write SetLineMapCount;
    property LineMap[Index: Integer]: Integer read GetLineMap write SetLineMap;
  end;

  { TSourceLazSynSurfaceGutter }

  TSourceLazSynSurfaceGutter = class(TLazSynGutterArea)
  private
    procedure TextSizeChanged(Sender: TObject);
  protected
    procedure DoPaint(ACanvas: TCanvas; AClip: TRect); override;
    procedure SetTextArea(const ATextArea: TLazSynTextArea); override;
  end;

  { TSourceLazSynSurfaceManager }

  TSourceLazSynSurfaceManager = class(TLazSynSurfaceManager)
  private
    FExtraManager: TLazSynSurfaceManager;
    FOriginalManager: TLazSynSurfaceManager;
    FTopLineCount: Integer;
    procedure SetTopLineCount(AValue: Integer);
  protected
    function GetLeftGutterArea: TLazSynSurface; override;
    function GetRightGutterArea: TLazSynSurface; override;
    function GetTextArea: TLazSynTextArea; override;
  protected
    procedure SetBackgroundColor(AValue: TColor); override;
    procedure SetExtraCharSpacing(AValue: integer); override;
    procedure SetExtraLineSpacing(AValue: integer); override;
    procedure SetForegroundColor(AValue: TColor); override;
    procedure SetPadding(Side: TLazSynBorderSide; AValue: integer); override;
    procedure SetRightEdgeColor(AValue: TColor); override;
    procedure SetRightEdgeColumn(AValue: integer); override;
    procedure SetRightEdgeVisible(AValue: boolean); override;
    procedure SetVisibleSpecialChars(AValue: TSynVisibleSpecialChars); override;
    procedure SetHighlighter(AValue: TSynCustomHighlighter); override;
  protected
    procedure DoPaint(ACanvas: TCanvas; AClip: TRect); override;
    procedure BoundsChanged; override;
  public
    constructor Create(AOwner: TWinControl; AnOriginalManager: TLazSynSurfaceManager);
    destructor Destroy; override;
    procedure  InvalidateLines(FirstTextLine, LastTextLine: TLineIdx); override;
    procedure InvalidateTextLines(FirstTextLine, LastTextLine: TLineIdx); override;
    procedure InvalidateGutterLines(FirstTextLine, LastTextLine: TLineIdx); override;
    property ExtraManager: TLazSynSurfaceManager read FExtraManager write FExtraManager;
    property OriginalManager: TLazSynSurfaceManager read FOriginalManager write FOriginalManager;
    property TopLineCount: Integer read FTopLineCount write SetTopLineCount;
  end;

  { TSourceSynSearchTermList }

  TSourceSynSearchTermList = class(TSynSearchTermList)
  public
    function FindMatchFor(ATerm: String; ACasesSensitive: Boolean;
                          ABoundaries: TSynSearchTermOptsBounds;
                          AStartAtIndex: Integer = 0;
                          AIgnoreIndex: Integer = -1): Integer;
    function FindSimilarMatchFor(ATerm: String; ACasesSensitive: Boolean;
                          ABoundaries: TSynSearchTermOptsBounds;
                          AEnabled: Boolean;
                          AStartAtIndex: Integer = 0;
                          AIgnoreIndex: Integer = -1;
                          AnOnlyWeakerOrEqual: Boolean = False;
                          AnSkipDisabled: Boolean = False): Integer; // weaker = matches less (subset of stronger)
    function FindSimilarMatchFor(ATerm: TSynSearchTerm;
                          AStartAtIndex: Integer = 0;
                          AIgnoreIndex: Integer = -1;
                          AnOnlyWeakerOrEqual: Boolean = False;
                          AnSkipDisabled: Boolean = False): Integer; // weaker = matches less (subset of stronger)
    procedure ClearSimilarMatches;
  end;

  { TSourceSynSearchTermDict }

  TSourceSynSearchTermDict = class(TSynSearchTermDict)
  private
    FModifiedTerms: TSynSearchTermList;
    FAddedByKeyWords: TSynSearchTermList;
    FFirstLocal: Integer;
    function GetTerms: TSourceSynSearchTermList;
    function  AddSearchTerm(ATerm: String): Integer;
  public
    constructor Create(ATermListClass: TSynSearchTermListClass);
    destructor Destroy; override;
    procedure AddTermByKey(ATerm: String; ACaseSensitive: Boolean;
      ABounds: TSynSearchTermOptsBounds);
    procedure RemoveTermByKey(RemoveIdx: Integer);
    procedure RestoreLocalChanges;
    property Terms: TSourceSynSearchTermList read GetTerms;
  end;

  { TSourceSynEditMarkupHighlightAllMulti }

  TSourceSynEditMarkupHighlightAllMulti = class(TSynEditMarkupHighlightAllMulti)
  private
    FAddTermCmd: TSynEditorCommand;
    FKeyAddCase: Boolean;
    FKeyAddSelectBoundMaxLen: Integer;
    FKeyAddSelectSmart: Boolean;
    FKeyAddWordBoundMaxLen: Integer;
    FKeyAddTermBounds: TSynSearchTermOptsBounds;
    FRemoveTermCmd: TSynEditorCommand;
    FToggleTermCmd: TSynEditorCommand;

    procedure ProcessSynCommand(Sender: TObject; {%H-}AfterProcessing: boolean;
              var Handled: boolean; var Command: TSynEditorCommand;
              var {%H-}AChar: TUTF8Char; {%H-}Data: pointer; {%H-}HandlerData: pointer);
  protected
    function CreateTermsList: TSynSearchTermDict; override;
  public
    constructor Create(ASynEdit: TSynEditBase);
    destructor Destroy; override;
    procedure RestoreLocalChanges;
    property AddTermCmd: TSynEditorCommand read FAddTermCmd write FAddTermCmd;
    property RemoveTermCmd: TSynEditorCommand read FRemoveTermCmd write FRemoveTermCmd;
    property ToggleTermCmd: TSynEditorCommand read FToggleTermCmd write FToggleTermCmd;
    property KeyAddTermBounds: TSynSearchTermOptsBounds read FKeyAddTermBounds write FKeyAddTermBounds;
    property KeyAddCase: Boolean read FKeyAddCase write FKeyAddCase;
    property KeyAddWordBoundMaxLen: Integer read FKeyAddWordBoundMaxLen write FKeyAddWordBoundMaxLen;
    property KeyAddSelectBoundMaxLen: Integer read FKeyAddSelectBoundMaxLen write FKeyAddSelectBoundMaxLen;
    property KeyAddSelectSmart: Boolean read FKeyAddSelectSmart write FKeyAddSelectSmart;
  end;

  TSourceSynEditMarkupIfDef = class(TSynEditMarkupIfDef)
  public
    property IfDefTree;
  end;

  TSynMarkupIdentComplWindow = class // don't inherit from TSynEditMarkup, no regular markup
  private
    FBackgroundSelectedColor: TColor;
    FBorderColor: TColor;
    FHighlightColor: TColor;
    FTextColor: TColor;
    FTextSelectedColor: TColor;
    FWindowColor: TColor;
  public
    constructor Create;
  public
    property WindowColor: TColor read FWindowColor write FWindowColor;
    property TextColor: TColor read FTextColor write FTextColor;
    property BorderColor: TColor read FBorderColor write FBorderColor;
    property HighlightColor: TColor read FHighlightColor write FHighlightColor;
    property TextSelectedColor: TColor read FTextSelectedColor write FTextSelectedColor;
    property BackgroundSelectedColor: TColor read FBackgroundSelectedColor write FBackgroundSelectedColor;
  end;

  { TIDESynEditor }

  TIDESynEditor = class(TSynEdit)
  private
    FCaretColor: TColor;
    FCaretStamp: Int64;
    FMarkupIdentComplWindow: TSynMarkupIdentComplWindow;
    FShowTopInfo: boolean;
    FTopInfoNestList: TLazSynEditNestedFoldsList;
    FSyncroEdit: TSynPluginSyncroEdit;
    FTemplateEdit: TSynPluginTemplateEdit;
    FMultiCaret: TSynPluginMultiCaret;
    FMarkupForGutterMark: TSynEditMarkupGutterMark;
    FOnIfdefNodeStateRequest: TSynMarkupIfdefStateRequest;
    FMarkupIfDef: TSourceSynEditMarkupIfDef;
    FTopInfoDisplay: TSourceLazSynTopInfoView;
    FTopInfoLastTopLine: Integer;
    FSrcSynCaretChangedLock, FSrcSynCaretChangedNeeded: boolean;
    FExtraMarkupLine: TSynEditMarkupSpecialLine;
    FExtraMarkupMgr: TSynEditMarkupManager;
    FTopInfoMarkup: TSynSelectedColor;
    FUserWordsList: TFPList;

    function DoIfDefNodeStateRequest(Sender: TObject; LinePos,
      XStartPos: Integer; CurrentState: TSynMarkupIfdefNodeStateEx): TSynMarkupIfdefNodeState;
    function GetHighlightUserWordCount: Integer;
    function GetHighlightUserWords(AIndex: Integer): TSourceSynEditMarkupHighlightAllMulti;
    function GetIDEGutterMarks: TIDESynGutterMarks;
    function GetIsInMultiCaretMainExecution: Boolean;
    function GetIsInMultiCaretRepeatExecution: Boolean;
    function GetOnMultiCaretBeforeCommand: TSynMultiCaretBeforeCommand;
    procedure GetTopInfoMarkupForLine(Sender: TObject; {%H-}Line: integer; var Special: boolean;
      aMarkup: TSynSelectedColor);
    procedure SetCaretColor(AValue: TColor);
    procedure SetHighlightUserWordCount(AValue: Integer);
    procedure SetOnMultiCaretBeforeCommand(AValue: TSynMultiCaretBeforeCommand);
    procedure SetShowTopInfo(AValue: boolean);
    procedure SetTopInfoMarkup(AValue: TSynSelectedColor);
    procedure DoHighlightChanged(Sender: TSynEditStrings; {%H-}AIndex, {%H-}ACount : Integer);
    procedure SrcSynCaretChanged(Sender: TObject);
    function  GetHighlighter: TSynCustomFoldHighlighter;
  protected
    procedure DoOnStatusChange(Changes: TSynStatusChanges); override;
    function CreateGutter(AOwner : TSynEditBase; ASide: TSynGutterSide;
                          ATextDrawer: TheTextDrawer): TSynGutter; override;
    procedure SetHighlighter(const Value: TSynCustomHighlighter); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    function TextIndexToViewPos(aTextIndex : Integer) : Integer;
    property IDEGutterMarks: TIDESynGutterMarks read GetIDEGutterMarks;
    property TopView;
    property TextBuffer;
    property ViewedTextBuffer;
    property TemplateEdit: TSynPluginTemplateEdit read FTemplateEdit;
    property SyncroEdit: TSynPluginSyncroEdit read FSyncroEdit;
    property MultiCaret: TSynPluginMultiCaret read FMultiCaret;
    //////
    property TopInfoMarkup: TSynSelectedColor read FTopInfoMarkup write SetTopInfoMarkup;
    property ShowTopInfo: boolean read FShowTopInfo write SetShowTopInfo;
    {$IFDEF WinIME}
    procedure CreateMinimumIme;
    procedure CreateFullIme;
    {$ENDIF}
    property HighlightUserWordCount: Integer read GetHighlightUserWordCount write SetHighlightUserWordCount;
    property HighlightUserWords[AIndex: Integer]: TSourceSynEditMarkupHighlightAllMulti read GetHighlightUserWords;
    property MarkupMgr;
    function  IsIfdefMarkupActive: Boolean;
    procedure InvalidateAllIfdefNodes;
    procedure SetIfdefNodeState(ALinePos, AstartPos: Integer; AState: TSynMarkupIfdefNodeState);
    property  OnIfdefNodeStateRequest: TSynMarkupIfdefStateRequest read FOnIfdefNodeStateRequest write FOnIfdefNodeStateRequest;
    property  MarkupIfDef: TSourceSynEditMarkupIfDef read FMarkupIfDef;
    property  MarkupIdentComplWindow: TSynMarkupIdentComplWindow read FMarkupIdentComplWindow;
    property  IsInMultiCaretMainExecution: Boolean read GetIsInMultiCaretMainExecution;
    property  IsInMultiCaretRepeatExecution: Boolean read GetIsInMultiCaretRepeatExecution;
    property  OnMultiCaretBeforeCommand: TSynMultiCaretBeforeCommand read GetOnMultiCaretBeforeCommand write SetOnMultiCaretBeforeCommand;
    property CaretStamp: Int64 read FCaretStamp;
    property CaretColor: TColor read FCaretColor write SetCaretColor;
  end;

  TIDESynHighlighterPasRangeList = class(TSynHighlighterPasRangeList)
  protected
    FInterfaceLine, FImplementationLine,
    FInitializationLine, FFinalizationLine: Integer;
  end;

  { TIDESynPasSyn }

  TIDESynPasSyn = class(TSynPasSyn)
  private
    function GetFinalizationLine: Integer;
    function GetImplementationLine: Integer;
    function GetInitializationLine: Integer;
    function GetInterfaceLine: Integer;
  protected
    function CreateRangeList({%H-}ALines: TSynEditStringsBase): TSynHighlighterRangeList; override;
    function StartCodeFoldBlock(ABlockType: Pointer = nil;
      IncreaseLevel: Boolean = true; ForceDisabled: Boolean = False
      ): TSynCustomCodeFoldBlock; override;
  public
    procedure SetLine({$IFDEF FPC}const {$ENDIF}NewValue: string;
      LineNumber: Integer); override;
    property InterfaceLine: Integer read GetInterfaceLine;
    property ImplementationLine: Integer read GetImplementationLine;
    property InitializationLine: Integer read GetInitializationLine;
    property FinalizationLine: Integer read GetFinalizationLine;
  end;

  { TIDESynFreePasSyn }

  TIDESynFreePasSyn = class(TIDESynPasSyn)
  public
    constructor Create(AOwner: TComponent); override;
    procedure ResetRange; override;
  end;

  { TIDESynGutterLOvProviderPascal }

  TIDESynGutterLOvProviderPascal = class(TSynGutterLineOverviewProvider)
  private
    FColor2: TColor;
    FInterfaceLine, FImplementationLine,
    FInitializationLine, FFinalizationLine: Integer;
    FPixInterfaceLine, FPixImplementationLine,
    FPixInitializationLine, FPixFinalizationLine: Integer;
    FPixEndInterfaceLine, FPixEndImplementationLine,
    FPixEndInitializationLine, FPixEndFinalizationLine: Integer;
    FSingleLine: Boolean;
    FRGBColor2: TColorRef;
    procedure SetColor2(const AValue: TColor);
    procedure SetSingleLine(const AValue: Boolean);
  protected
    procedure BufferChanged(Sender: TObject);
    procedure HighlightChanged(Sender: TSynEditStrings; {%H-}AIndex, {%H-}ACount : Integer);
    procedure ReCalc; override;

    procedure Paint(Canvas: TCanvas; AClip: TRect; TopOffset: integer); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor  Destroy; override;
  published
    property SingleLine: Boolean read FSingleLine write SetSingleLine;
    property Color2: TColor read FColor2 write SetColor2;
  end;

  { TIDESynGutterLOvProviderIDEMarks }

  TIDESynGutterLOvProviderIDEMarks = class(TSynGutterLOvProviderBookmarks)
  // Bookmarks and breakpoints
  private
    FBreakColor: TColor;
    FBreakDisabledColor: TColor;
    FExecLineColor: TColor;
    FRGBBreakColor: TColorRef;
    FRGBBreakDisabledColor: TColor;
    FRGBExecLineColor: TColor;
    procedure SetBreakColor(const AValue: TColor);
    procedure SetBreakDisabledColor(AValue: TColor);
    procedure SetExecLineColor(AValue: TColor);
  protected
    procedure AdjustColorForMark(AMark: TSynEditMark; var AColor: TColor; var APriority: Integer); override;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property BreakColor: TColor read FBreakColor write SetBreakColor;
    property BreakDisabledColor: TColor read FBreakDisabledColor write SetBreakDisabledColor;
    property ExecLineColor: TColor read FExecLineColor write SetExecLineColor;
  end;

  { TIDESynGutter }

  TIDESynGutter = class(TSynGutter)
  protected
    procedure CreateDefaultGutterParts; override;
  public
  {$IFDEF WithSynDebugGutter}
  DebugGutter: TIDESynGutterDebugHL;
  {$ENDIF}
  end;

  { TIDESynDebugMarkInfo }

  TIDESynDebugMarkInfo = class(TSynManagedStorageMem)
  private
    FRefCount: Integer;
    function GetSrcLineToMarkLine(SrcIndex: Integer): Integer;
    procedure SetSrcLineToMarkLine(SrcIndex: Integer; const AValue: Integer);
  public
    constructor Create;
    procedure IncRefCount;
    procedure DecRefCount;
    // Index is the Current line-index (0 based) in editor (including source modification)
    // Result is the original Line-pos (1 based) as known by the debugger
    property SrcLineToMarkLine[SrcIndex: Integer]: Integer
             read GetSrcLineToMarkLine write SetSrcLineToMarkLine; default;
    property RefCount: Integer read FRefCount;
  end;

  { TIDESynGutterMarks }

  TIDESynGutterMarks = class(TSynGutterMarks)
  private
    FDebugMarkInfo: TIDESynDebugMarkInfo;
    FMarkInfoTextBuffer: TSynEditStrings;
  protected
    procedure CheckTextBuffer;       // Todo: Add a notification, when TextBuffer Changes
    Procedure PaintLine(aScreenLine: Integer; Canvas : TCanvas; AClip : TRect); override;
    function PreferedWidthAtCurrentPPI: Integer; override;

    function GetImgListRes(const ACanvas: TCanvas;
      const AImages: TCustomImageList): TScaledImageListResolution; override;
  public
    destructor Destroy; override;
    procedure BeginSetDebugMarks;
    procedure EndSetDebugMarks;
    procedure SetDebugMarks(AFirstLinePos, ALastLinePos: Integer);
    procedure ClearDebugMarks;
    function HasDebugMarks: Boolean;
    function DebugLineToSourceLine(aLinePos: Integer): Integer;
    function SourceLineToDebugLine(aLinePos: Integer; AdjustOnError: Boolean = False): Integer;
  end;

  { TIDESynGutterCodeFolding }

  TIDESynGutterCodeFolding = class(TSynGutterCodeFolding)
  protected
    procedure UnFoldIfdef(AInclDisabled, AInclEnabled: Boolean);
    procedure FoldIfdef(AInclTemp: Boolean);

    procedure PopClickedUnfoldAll(Sender: TObject);
    procedure PopClickedUnfoldComment(Sender: TObject);
    procedure PopClickedFoldComment(Sender: TObject);
    procedure PopClickedHideComment(Sender: TObject);
    procedure PopClickedFoldIfdef(Sender: TObject);
    procedure PopClickedFoldIfdefNoMixed(Sender: TObject);
    procedure PopClickedUnfoldIfdefActive(Sender: TObject);
    procedure PopClickedUnfolDIfdefAll(Sender: TObject);
    procedure PopClickedUnfoldIfdefInactiv(Sender: TObject);
    procedure CreatePopUpMenuEntries(var APopUp: TPopupMenu; ALine: Integer); override;
  end;

  {$IFDEF WithSynDebugGutter}
  { TIDESynGutterDebugHL }

  TIDESynGutterDebugHL = class(TSynGutterPartBase)
    procedure PopContentClicked(Sender: TObject);
    procedure PopSizeClicked(Sender: TObject);
  private
    FTheLinesView: TSynEditStrings;
    FPopUp: TPopupMenu;
    FContent: Integer;
  protected
    function  PreferedWidth: Integer; override;
    function MaybeHandleMouseAction(var AnInfo: TSynEditMouseActionInfo;
               HandleActionProc: TSynEditMouseActionHandler): Boolean; override;
    procedure PaintFoldLvl(Canvas: TCanvas; AClip: TRect; FirstLine, LastLine: integer);
    procedure PaintCharWidths(Canvas: TCanvas; AClip: TRect; FirstLine, LastLine: integer);
  public
    constructor Create(AOwner: TComponent); override;
    procedure Paint(Canvas: TCanvas; AClip: TRect; FirstLine, LastLine: integer);
      override;
    property TheLinesView:  TSynEditStrings       read FTheLinesView  write FTheLinesView;
  end;
  {$ENDIF}

implementation

uses SourceMarks;

{ TSynMarkupIdentComplWindow }

constructor TSynMarkupIdentComplWindow.Create;
begin
  inherited Create;

  FBackgroundSelectedColor := clNone;
  FBorderColor := clNone;
  FHighlightColor := clNone;
  FTextColor := clNone;
  FTextSelectedColor := clNone;
  FWindowColor := clNone;
end;

{ TSourceSynSearchTermDict }

function TSourceSynSearchTermDict.GetTerms: TSourceSynSearchTermList;
begin
  Result := TSourceSynSearchTermList(inherited Terms);
end;

function TSourceSynSearchTermDict.AddSearchTerm(ATerm: String): Integer;
var
  Itm: TSynSearchTerm;
begin
  Itm := Terms.Add;
  Itm.SearchTerm := ATerm;
  Result := Itm.Index;
end;

constructor TSourceSynSearchTermDict.Create(ATermListClass: TSynSearchTermListClass);
begin
  inherited Create(ATermListClass);
  FModifiedTerms := TSynSearchTermList.Create;
  FAddedByKeyWords := TSynSearchTermList.Create;
end;

destructor TSourceSynSearchTermDict.Destroy;
begin
  inherited Destroy;
  FreeAndNil(FModifiedTerms);
  FreeAndNil(FAddedByKeyWords);
end;

procedure TSourceSynSearchTermDict.AddTermByKey(ATerm: String; ACaseSensitive: Boolean;
  ABounds: TSynSearchTermOptsBounds);
var
  i, j, PresetIdx: Integer;
begin
  // check for pre-defined, compare text only
  PresetIdx := Terms.IndexOfSearchTerm(ATerm, False);
  if PresetIdx >= FFirstLocal then
    PresetIdx := -1;

  // Disable or remove weaker terms
  i := Terms.FindSimilarMatchFor(ATerm, ACaseSensitive, ABounds, True, 0, -1, True, True);
  while i >= 0 do begin
    if i >= FFirstLocal then begin
      j := FAddedByKeyWords.IndexOfSearchTerm(Terms[i]);
      Terms.Delete(i);
      if j >= 0 then
        FAddedByKeyWords.Delete(j);
    end
    else begin
      Terms[i].Enabled := False;
      j := FModifiedTerms.IndexOfSearchTerm(Terms[i]);
      if j < 0 then
        FModifiedTerms.Add.Assign(Terms[i])
      else
        FModifiedTerms[j].Assign(Terms[i]);
    end;
    i := Terms.FindSimilarMatchFor(ATerm, ACaseSensitive, ABounds, True, 0, -1, True, True);
  end;

  if PresetIdx >= 0 then begin
    while PresetIdx >= 0 do begin
      Terms[PresetIdx].Enabled := True;
      j := FModifiedTerms.IndexOfSearchTerm(Terms[PresetIdx]);
      if j < 0 then
        FModifiedTerms.Add.Assign(Terms[PresetIdx])
      else
        FModifiedTerms[j].Assign(Terms[PresetIdx]);
      PresetIdx := Terms.IndexOfSearchTerm(ATerm, False, PresetIdx+1);
      if PresetIdx >= FFirstLocal then
        PresetIdx := -1;
    end;
  end
  else begin
    // Could be adding selection that is not at bounds, but forcing bounds
    if Terms.FindMatchFor(ATerm, ACaseSensitive, ABounds) >= FFirstLocal then
      exit;
    i := AddSearchTerm(ATerm);
    Terms[i].MatchCase := ACaseSensitive;
    Terms[i].MatchWordBounds := ABounds;
    FAddedByKeyWords.Add.Assign(Terms[i]);
  end;
end;

procedure TSourceSynSearchTermDict.RemoveTermByKey(RemoveIdx: Integer);
var
  i: Integer;
begin
  if RemoveIdx >= FFirstLocal then begin
    i := FAddedByKeyWords.IndexOfSearchTerm(Terms[RemoveIdx]);
    Assert(i >= 0, 'FAddedByKeyWords.IndexOfSearchTerm(Terms[RemoveIdx])');
    FAddedByKeyWords.Delete(i);
    Terms.Delete(RemoveIdx);
  end
  else begin
    Terms[RemoveIdx].Enabled := False;
    i := FModifiedTerms.IndexOfSearchTerm(Terms[RemoveIdx]);
    if i < 0 then
      FModifiedTerms.Add.Assign(Terms[RemoveIdx])
    else
      FModifiedTerms[i].Assign(Terms[RemoveIdx]);
  end;
end;

procedure TSourceSynSearchTermDict.RestoreLocalChanges;
var
  i, j, k: Integer;
begin
  FFirstLocal := Terms.Count;
  IncChangeNotifyLock;
  try

    for i := FModifiedTerms.Count - 1 downto 0 do begin
      j := Terms.IndexOfSearchTerm(FModifiedTerms[i]);
      if (j < 0) or (Terms[j].Enabled = FModifiedTerms[i].Enabled) then
        FModifiedTerms.Delete(i)
      else
        Terms[j].Enabled := FModifiedTerms[i].Enabled;
    end;

    for i := 0 to FAddedByKeyWords.Count - 1 do begin
      // disable global (there may be new globals)
      j := Terms.FindSimilarMatchFor(FAddedByKeyWords[i], 0, -1, True, True);
      while j >= 0 do begin
        Assert(j < FFirstLocal, 'DISABLE preset in RESTORE j < FFirstLocal');
        if j < FFirstLocal then begin  // should always be true
  DebugLn(['DISABLE preset in RESTORE ',j]);
          Terms[j].Enabled := False;
          k := FModifiedTerms.IndexOfSearchTerm(Terms[j]);
          if k < 0 then
            FModifiedTerms.Add.Assign(Terms[j])
          else
            FModifiedTerms[k].Assign(Terms[j]);
        end;
        j := Terms.FindSimilarMatchFor(FAddedByKeyWords[i], 0, -1, True, True);
      end;

      Terms.Add.Assign(FAddedByKeyWords[i]);
    end;

  finally
    DecChangeNotifyLock;
  end;
end;

{ TSourceSynSearchTermList }

function TSourceSynSearchTermList.FindMatchFor(ATerm: String; ACasesSensitive: Boolean;
  ABoundaries: TSynSearchTermOptsBounds; AStartAtIndex: Integer;
  AIgnoreIndex: Integer): Integer;
var
  c: Integer;
  Entry: TSynSearchTerm;
begin
  Result := AStartAtIndex - 1;
  c := Count - 1;
  while Result < c do begin
    inc(Result);
    if Result = AIgnoreIndex then
      continue;

    Entry := Items[Result];
    if (ATerm = Entry.SearchTerm) and
       (ACasesSensitive = Entry.MatchCase) and
       (ABoundaries = Entry.MatchWordBounds)
    then
      exit;
  end;
   Result := -1;
end;

function TSourceSynSearchTermList.FindSimilarMatchFor(ATerm: String; ACasesSensitive: Boolean;
  ABoundaries: TSynSearchTermOptsBounds; AEnabled: Boolean; AStartAtIndex: Integer;
  AIgnoreIndex: Integer; AnOnlyWeakerOrEqual: Boolean; AnSkipDisabled: Boolean): Integer;
var
  c: Integer;
  Entry: TSynSearchTerm;
  WeakerByEnabled, WeakerByCase, WeakerByBounds: (wParam,  wEntry, wEqual);
begin
  Result := AStartAtIndex - 1;
  c := Count - 1;
  while Result < c do begin
    inc(Result);
    if Result = AIgnoreIndex then
      continue;

    Entry := Items[Result];
    (* if one has soBoundsAtStart, and the other has soBoundsAtEnd then they
        match 2 different sets, which may overlap
       In all other cases, one will match a subset of the other
    *)
    if [ABoundaries, Entry.MatchWordBounds] = [soBoundsAtStart, soBoundsAtEnd] then
      Continue; // Match different sets
    if AnSkipDisabled and not Entry.Enabled then
      Continue;


    WeakerByEnabled := wEqual;
    if (not Entry.Enabled) and AEnabled then WeakerByEnabled := wEntry;
    if Entry.Enabled and (not AEnabled) then WeakerByEnabled := wParam;

    if AnOnlyWeakerOrEqual and (WeakerByEnabled = wParam) then  // Entry can not be weaker
      continue;


    if (ATerm <> Entry.SearchTerm) and
       ( (ACasesSensitive and Entry.MatchCase) or
         (LowerCase(ATerm) <> LowerCase(Entry.SearchTerm))
       )
    then
      continue;


    // which one is weakerByCase?
    WeakerByCase := wEqual;
    if (ACasesSensitive) and (not Entry.MatchCase) then
      WeakerByCase := wParam  // param matches a sub-set of entry
    else
    if (not ACasesSensitive) and (Entry.MatchCase) then
      WeakerByCase := wEntry;  // Entry matches a sub-set of param

    if AnOnlyWeakerOrEqual and (WeakerByCase = wParam) then  // Entry can not be weaker
      continue;


    WeakerByBounds := wEqual;
    case ABoundaries of
      soNoBounds: begin
          if Entry.MatchWordBounds <> soNoBounds then
            WeakerByBounds := wEntry; // Entry matches less
        end;
      soBoundsAtStart, soBoundsAtEnd: begin // Combination of one at Start, other at End has already been filtered
          if Entry.MatchWordBounds = soNoBounds then
            WeakerByBounds := wParam
          else
          if Entry.MatchWordBounds = soBothBounds then
            WeakerByBounds := wEntry;
        end;
      soBothBounds: begin
          if Entry.MatchWordBounds <> soBothBounds then
            WeakerByBounds := wParam;
        end;
    end;

    if AnOnlyWeakerOrEqual and (WeakerByBounds = wParam) then  // Entry can not be weaker
      continue;

    if ( ([WeakerByEnabled, WeakerByBounds, WeakerByCase] - [wEqual] = [wEntry]) or
         ([WeakerByEnabled, WeakerByBounds, WeakerByCase] - [wEqual] = [wParam]) or
         ([WeakerByEnabled, WeakerByBounds, WeakerByCase] = [wEqual])
       )
    then
      exit;

  end;
  Result := -1;
end;

function TSourceSynSearchTermList.FindSimilarMatchFor(ATerm: TSynSearchTerm;
  AStartAtIndex: Integer; AIgnoreIndex: Integer; AnOnlyWeakerOrEqual: Boolean;
  AnSkipDisabled: Boolean): Integer;
begin
  Result := FindSimilarMatchFor(ATerm.SearchTerm, ATerm.MatchCase, ATerm.MatchWordBounds,
    ATerm.Enabled, AStartAtIndex, AIgnoreIndex, AnOnlyWeakerOrEqual, AnSkipDisabled);
end;

procedure TSourceSynSearchTermList.ClearSimilarMatches;
var
  i, j: Integer;
begin
  i := 0;
  while (i < Count) do begin
    j := FindSimilarMatchFor(Items[i].SearchTerm,
      Items[i].MatchCase, Items[i].MatchWordBounds, Items[i].Enabled,
      0, i, True);
    if (j >= 0) then begin
      Delete(j);
      if j < i then // May have more than one weaker duplicate
        dec(i);
    end
    else
      inc(i);
  end;
end;

{ TSourceSynEditMarkupHighlightAllMulti }

procedure TSourceSynEditMarkupHighlightAllMulti.ProcessSynCommand(Sender: TObject;
  AfterProcessing: boolean; var Handled: boolean; var Command: TSynEditorCommand;
  var AChar: TUTF8Char; Data: pointer; HandlerData: pointer);
var
  syn: TIDESynEditor;
  TermDict: TSourceSynSearchTermDict;

  function FindTermAtCaret: Integer;
  var
    i, y, x, x1, x2: Integer;
    s: string;
    b1, b2: Boolean;
    t: TSynSearchTerm;
  begin
    Result := -1;
    y := syn.CaretY;
    i := Matches.IndexOfFirstMatchForLine(y);
    if i < 0 then exit;
    x := syn.LogicalCaretXY.x;
    while (i < Matches.Count) and (Matches[i].StartPoint.y <= y) do begin
      if ((Matches[i].StartPoint.y < y) or (Matches[i].StartPoint.x <= x)) and
         ((Matches[i].EndPoint.y > y) or (Matches[i].EndPoint.x >= x))
      then
        break;
      inc(i);
    end;
    if (i >= Matches.Count) or (Matches[i].StartPoint.y > y) or (Matches[i].StartPoint.x > x) then
      exit;

    x1 := Matches[i].StartPoint.x;
    x2 := Matches[i].EndPoint.x;
    //if Matches[i].StartPoint.y < y then x1 := 1; // only one liners allowed
    s := syn.ViewedTextBuffer[y-1];
    b1 := (x1 = 1) or (s[x1-1] in WordBreakChars);
    b2 := (x2 > length(s)) or (s[x2] in WordBreakChars);
    s := copy(s, x1, x2-x1);

    Result := 0;
    while Result < Terms.Count do begin
      t := Terms[Result];
      if t.Enabled and
         ( (t.SearchTerm = s) or
           ( (not t.MatchCase) and (LowerCase(t.SearchTerm)= LowerCase(s)) )  ) and
         ( (t.MatchWordBounds = soNoBounds) or
           ( (t.MatchWordBounds = soBoundsAtStart) and b1 ) or
           ( (t.MatchWordBounds = soBoundsAtEnd) and b2 ) or
           ( (t.MatchWordBounds = soBothBounds) and b1 and b2 )
         )
      then
        exit;
      inc(Result);
    end;

    assert(false, 'TSourceSynEditMarkupHighlightAllMulti match not found');
    Result := -1; // Should never reach
  end;

  procedure AddTermByKey;
  var
    NewTerm, LineTxt: String;
    B1, B2: Boolean;
    NewBounds: TSynSearchTermOptsBounds;
  begin
    NewTerm := '';
    B1 := False;
    B2 := False;
    if syn.SelAvail and (syn.BlockBegin.y = syn.BlockEnd.y) then begin
      NewTerm := syn.SelText;
      LineTxt := syn.Lines[syn.CaretY-1];
      B1 := (KeyAddTermBounds in [soBoundsAtStart, soBothBounds]) and
            ( (KeyAddSelectBoundMaxLen < 1) or (length(NewTerm) <= KeyAddSelectBoundMaxLen) ) and
            ( (not KeyAddSelectSmart) or
              ( (Syn.BlockBegin.X <= 1) or (LineTxt[Syn.BlockBegin.X-1] in WordBreakChars) )
            );
      B2 := (KeyAddTermBounds in [soBoundsAtEnd, soBothBounds]) and
            ( (KeyAddSelectBoundMaxLen < 1) or (length(NewTerm) <= KeyAddSelectBoundMaxLen) ) and
            ( (not KeyAddSelectSmart) or
              ( (Syn.BlockEnd.X > length(LineTxt)) or (LineTxt[Syn.BlockEnd.X] in WordBreakChars) )
            );
    end
    else
    if not syn.SelAvail then begin
      NewTerm := syn.GetWordAtRowCol(syn.LogicalCaretXY);
      if NewTerm <> '' then begin
        B1 := (KeyAddTermBounds in [soBoundsAtStart, soBothBounds]) and
              ( (KeyAddWordBoundMaxLen < 1) or (length(NewTerm) <= KeyAddWordBoundMaxLen) );
        B2 := (KeyAddTermBounds in [soBoundsAtEnd, soBothBounds]) and
              ( (KeyAddWordBoundMaxLen < 1) or (length(NewTerm) <= KeyAddWordBoundMaxLen) );
      end;
    end;

    if B1 and B2 then NewBounds := soBothBounds
    else if B1   then NewBounds := soBoundsAtStart
    else if B2   then NewBounds := soBoundsAtEnd
    else              NewBounds := soNoBounds;

    TermDict.AddTermByKey(NewTerm, FKeyAddCase, NewBounds);
  end;

var
  i: Integer;
begin
  if Handled then
    exit;
  syn := TIDESynEditor(SynEdit);
  TermDict := (Terms as TSourceSynSearchTermDict);
  TermDict.IncChangeNotifyLock;
  try

    if Command = FAddTermCmd then begin
      AddTermByKey;
      Handled := True;
    end;

    if Command = FRemoveTermCmd then begin
      i := FindTermAtCaret;
      if i >= 0 then
        TermDict.RemoveTermByKey(i);
      Handled := True;
    end;

    if Command = FToggleTermCmd then begin
      i := FindTermAtCaret;
      if i >= 0 then
        TermDict.RemoveTermByKey(i)
      else
        AddTermByKey;
      Handled := True;
    end;

  finally
    TermDict.DecChangeNotifyLock;
  end;
end;

function TSourceSynEditMarkupHighlightAllMulti.CreateTermsList: TSynSearchTermDict;
begin
  Result := TSourceSynSearchTermDict.Create(TSourceSynSearchTermList);
end;

constructor TSourceSynEditMarkupHighlightAllMulti.Create(ASynEdit: TSynEditBase);
begin
  inherited Create(ASynEdit);
  TCustomSynEdit(SynEdit).RegisterCommandHandler(@ProcessSynCommand, nil, [hcfInit]);
end;

destructor TSourceSynEditMarkupHighlightAllMulti.Destroy;
begin
  inherited Destroy;
  TCustomSynEdit(SynEdit).UnregisterCommandHandler(@ProcessSynCommand);
end;

procedure TSourceSynEditMarkupHighlightAllMulti.RestoreLocalChanges;
begin
  (Terms as TSourceSynSearchTermDict).RestoreLocalChanges;
end;

{$IFDEF WithSynDebugGutter}
{ TIDESynGutterDebugHL }

procedure TIDESynGutterDebugHL.PopContentClicked(Sender: TObject);
begin
  FContent := TMenuItem(Sender).Tag;
  SynEdit.Invalidate;
end;

procedure TIDESynGutterDebugHL.PopSizeClicked(Sender: TObject);
begin
  Width := TMenuItem(Sender).Tag;
end;

function TIDESynGutterDebugHL.PreferedWidth: Integer;
begin
  Result := 15; // Gutter.TextDrawer.CharWidth * 15;
end;

function TIDESynGutterDebugHL.MaybeHandleMouseAction(var AnInfo: TSynEditMouseActionInfo;
  HandleActionProc: TSynEditMouseActionHandler): Boolean;
begin
  Result := False;
  if (AnInfo.Button <> mbXRight) then exit;
  Result := True;
  if (AnInfo.Dir = cdUp) then begin
    FPopUp.PopUp;
  end;
end;

procedure TIDESynGutterDebugHL.PaintFoldLvl(Canvas: TCanvas; AClip: TRect; FirstLine,
  LastLine: integer);
var
  TextDrawer: TheTextDrawer;
  c, i, iLine, LineHeight: Integer;
  rcLine: TRect;
  dc: HDC;
  s: String;
  RngLst: TSynHighlighterRangeList;
  r: TSynPasSynRange;
begin
  if TCustomSynEdit(SynEdit).Highlighter = nil then exit;
  if not(TCustomSynEdit(SynEdit).Highlighter is TSynPasSyn)  then exit;
  TCustomSynEdit(SynEdit).Highlighter.CurrentLines := TheLinesView;
  TextDrawer := Gutter.TextDrawer;
  dc := Canvas.Handle;
  //TSynHighlighterPasRangeList
  RngLst := TSynHighlighterRangeList(TheLinesView.Ranges[TCustomSynEdit(SynEdit).Highlighter]);

  // Clear all
  TextDrawer.BeginDrawing(dc);
  try
    TextDrawer.SetBackColor(Gutter.Color);
    TextDrawer.SetForeColor(TCustomSynEdit(SynEdit).Font.Color);
    TextDrawer.SetFrameColor(clNone);
     with AClip do
       TextDrawer.ExtTextOut(Left, Top, ETO_OPAQUE, AClip, nil, 0);

    rcLine := AClip;
    rcLine.Bottom := AClip.Top;
    LineHeight := TCustomSynEdit(SynEdit).LineHeight;
    c := TCustomSynEdit(SynEdit).Lines.Count;
    for i := FirstLine to LastLine do
    begin
      iLine := FoldView.DisplayNumber[i];
      if (iLine < 0) or (iLine >= c) then break;
      // next line rect
      rcLine.Top := rcLine.Bottom;
      rcLine.Bottom := rcLine.Bottom + LineHeight;

      if i > 0 then begin
        r := TSynPasSynRange(RngLst.Range[iLine-1]);
        s:= format('%2d %2d %2d  %2d %2d %2d ',
                   [r.PasFoldEndLevel, r.PasFoldMinLevel, r.PasFoldFixLevel,
                    r.CodeFoldStackSize, r.MinimumCodeFoldBlockLevel, r.LastLineCodeFoldLevelFix
                   ]
                  );
      end
      else
        s:= '';

      TextDrawer.ExtTextOut(rcLine.Left, rcLine.Top, ETO_OPAQUE or ETO_CLIPPED, rcLine,
        PChar(Pointer(S)),Length(S));
    end;

  finally
    TextDrawer.EndDrawing;
  end;
end;

procedure TIDESynGutterDebugHL.PaintCharWidths(Canvas: TCanvas; AClip: TRect; FirstLine,
  LastLine: integer);
var
  TextDrawer: TheTextDrawer;
  c, i, iLine, LineHeight: Integer;
  rcLine: TRect;
  dc: HDC;
  s, s2: String;
  CW: TPhysicalCharWidths;
  j: Integer;
begin
  TextDrawer := Gutter.TextDrawer;
  dc := Canvas.Handle;
  TextDrawer.BeginDrawing(dc);
  try
    TextDrawer.SetBackColor(Gutter.Color);
    TextDrawer.SetForeColor(TCustomSynEdit(SynEdit).Font.Color);
    TextDrawer.SetFrameColor(clNone);
     with AClip do
       TextDrawer.ExtTextOut(Left, Top, ETO_OPAQUE, AClip, nil, 0);

    rcLine := AClip;
    rcLine.Bottom := AClip.Top;
    LineHeight := TCustomSynEdit(SynEdit).LineHeight;
    c := TCustomSynEdit(SynEdit).Lines.Count;
    for i := FirstLine to LastLine do
    begin
      iLine := FoldView.DisplayNumber[i];
      if (iLine < 0) or (iLine >= c) then break;
      // next line rect
      rcLine.Top := rcLine.Bottom;
      rcLine.Bottom := rcLine.Bottom + LineHeight;

      if i >= 0 then begin
        CW := FTheLinesView.GetPhysicalCharWidths(iLine-1);
        s2 := FTheLinesView.Strings[iLine-1];
        s := '';
        for j := 0 to length(CW) - 1 do begin
          case FContent of
            1: s := s + IntToStr(CW[j]) + ',';
            2: s := s + IntToHex(ord(s2[j+1]),2) + ',';
            3: s := s + IntToHex(ord(s2[j+1]),2) + '(' + IntToStr(CW[j]) + '),';
          end;
          if (j+1 < length(s2)) and (s2[j+2] in [#$00..#$7f,#$C0..#$FF]) then
            s := s + ' ';
        end;
      end
      else
        s:= '';

      TextDrawer.ExtTextOut(rcLine.Left, rcLine.Top, ETO_OPAQUE or ETO_CLIPPED, rcLine,
        PChar(Pointer(S)),Length(S));
    end;

  finally
    TextDrawer.EndDrawing;
  end;
end;

constructor TIDESynGutterDebugHL.Create(AOwner: TComponent);
var
  Item: TMenuItem;
begin
  inherited Create(AOwner);
  FPopUp := TPopupMenu.Create(Self);
  AutoSize := False;
  Width := PreferedWidth;
  FContent := 0;

  Item := TMenuItem.Create(FPopUp);
  Item.OnClick := @PopSizeClicked;
  Item.Caption := 'Size 15';
  Item.Tag := 15;
  FPopUp.Items.Add(Item);

  Item := TMenuItem.Create(FPopUp);
  Item.OnClick := @PopSizeClicked;
  Item.Caption := 'Size 100';
  Item.Tag := 100;
  FPopUp.Items.Add(Item);

  Item := TMenuItem.Create(FPopUp);
  Item.OnClick := @PopSizeClicked;
  Item.Caption := 'Size 250';
  Item.Tag := 240;
  FPopUp.Items.Add(Item);

  Item := TMenuItem.Create(FPopUp);
  Item.OnClick := @PopSizeClicked;
  Item.Caption := 'Size 500';
  Item.Tag := 500;
  FPopUp.Items.Add(Item);

  Item := TMenuItem.Create(FPopUp);
  Item.Caption := '-';
  FPopUp.Items.Add(Item);

  Item := TMenuItem.Create(FPopUp);
  Item.OnClick := @PopContentClicked;
  Item.Caption := 'Content: Fold Level';
  Item.Tag := 0;
  FPopUp.Items.Add(Item);

  Item := TMenuItem.Create(FPopUp);
  Item.OnClick := @PopContentClicked;
  Item.Caption := 'Content: CharWidths';
  Item.Tag := 1;
  FPopUp.Items.Add(Item);

  Item := TMenuItem.Create(FPopUp);
  Item.OnClick := @PopContentClicked;
  Item.Caption := 'Content: Hex';
  Item.Tag := 2;
  FPopUp.Items.Add(Item);

  Item := TMenuItem.Create(FPopUp);
  Item.OnClick := @PopContentClicked;
  Item.Caption := 'Content: CharWidths + hex';
  Item.Tag := 3;
  FPopUp.Items.Add(Item);


end;

procedure TIDESynGutterDebugHL.Paint(Canvas: TCanvas; AClip: TRect; FirstLine,
  LastLine: integer);
begin
  case FContent of
    0: PaintFoldLvl(Canvas, AClip, FirstLine, LastLine);
    1,2,3: PaintCharWidths(Canvas, AClip, FirstLine, LastLine);
  end;
end;
{$ENDIF}

{ TSourceLazSynTopInfoView }

function TSourceLazSynTopInfoView.GetLineMap(Index: Integer): Integer;
begin
  Result := FLineMap[Index];
end;

procedure TSourceLazSynTopInfoView.SetLineMap(Index: Integer; AValue: Integer);
begin
  FLineMap[Index] := AValue;
end;

procedure TSourceLazSynTopInfoView.SetLineMapCount(AValue: integer);
begin
  if FLineMapCount = AValue then Exit;
  FLineMapCount := AValue;
  SetLength(FLineMap, AValue);
end;

procedure TSourceLazSynTopInfoView.SetHighlighterTokensLine(ALine: TLineIdx; out
  ARealLine: TLineIdx);
begin
  CurrentTokenLine := ALine;
  inherited SetHighlighterTokensLine(FLineMap[ALine], ARealLine);
end;

function TSourceLazSynTopInfoView.GetLinesCount: Integer;
begin
  Result := LineMapCount;
end;

function TSourceLazSynTopInfoView.TextToViewIndex(AIndex: TLineIdx): TLineRange;
var
  i: Integer;
  r: TLineRange;
begin
  Result.Top := -1;
  Result.Bottom := -1;
  r := inherited TextToViewIndex(AIndex);
  for i := 0 to LineMapCount - 1 do begin
    if LineMap[i] = r.Top then Result.Top  := i;
    if LineMap[i] = r.Bottom then Result.Bottom  := i;
  end;
  if Result.Bottom < Result.Top then
    Result.Bottom := Result.Top;
end;

function TSourceLazSynTopInfoView.ViewToTextIndex(AIndex: TLineIdx): TLineIdx;
begin
  Result := inherited ViewToTextIndex(AIndex);
end;

constructor TSourceLazSynTopInfoView.Create;
begin
  LineMapCount := 0;
end;

{ TSourceLazSynSurfaceGutter }

procedure TSourceLazSynSurfaceGutter.DoPaint(ACanvas: TCanvas; AClip: TRect);
begin
  // prevent output
  Gutter.Paint(ACanvas, Self, AClip, 0, -1);
end;

procedure TSourceLazSynSurfaceGutter.SetTextArea(
  const ATextArea: TLazSynTextArea);
begin
  inherited SetTextArea(ATextArea);
  ATextArea.AddTextSizeChangeHandler(@TextSizeChanged);
end;

procedure TSourceLazSynSurfaceGutter.TextSizeChanged(Sender: TObject);
begin
  Gutter.DoAutoSize;
end;

{ TSourceLazSynSurfaceManager }

procedure TSourceLazSynSurfaceManager.SetTopLineCount(AValue: Integer);
begin
  if FTopLineCount = AValue then Exit;
  FTopLineCount := AValue;
  BoundsChanged;
end;

function TSourceLazSynSurfaceManager.GetLeftGutterArea: TLazSynSurface;
begin
  Result := FOriginalManager.LeftGutterArea;
end;

function TSourceLazSynSurfaceManager.GetRightGutterArea: TLazSynSurface;
begin
  Result := FOriginalManager.RightGutterArea;
end;

function TSourceLazSynSurfaceManager.GetTextArea: TLazSynTextArea;
begin
  Result := FOriginalManager.TextArea;
end;

procedure TSourceLazSynSurfaceManager.SetBackgroundColor(AValue: TColor);
begin
  FOriginalManager.BackgroundColor := AValue;
  FExtraManager.BackgroundColor := AValue;
end;

procedure TSourceLazSynSurfaceManager.SetExtraCharSpacing(AValue: integer);
begin
  FOriginalManager.ExtraCharSpacing := AValue;
  FExtraManager.ExtraCharSpacing := AValue;
end;

procedure TSourceLazSynSurfaceManager.SetExtraLineSpacing(AValue: integer);
begin
  FOriginalManager.ExtraLineSpacing := AValue;
  FExtraManager.ExtraLineSpacing := AValue;
  BoundsChanged;
end;

procedure TSourceLazSynSurfaceManager.SetForegroundColor(AValue: TColor);
begin
  FOriginalManager.ForegroundColor := AValue;
  FExtraManager.ForegroundColor := AValue;
end;

procedure TSourceLazSynSurfaceManager.SetPadding(Side: TLazSynBorderSide; AValue: integer);
begin
  FOriginalManager.Padding[Side] := AValue;
  FExtraManager.Padding[Side] := AValue;
end;

procedure TSourceLazSynSurfaceManager.SetRightEdgeColor(AValue: TColor);
begin
  FOriginalManager.RightEdgeColor := AValue;
  FExtraManager.RightEdgeColor := AValue;
end;

procedure TSourceLazSynSurfaceManager.SetRightEdgeColumn(AValue: integer);
begin
  FOriginalManager.RightEdgeColumn := AValue;
  FExtraManager.RightEdgeColumn := AValue;
end;

procedure TSourceLazSynSurfaceManager.SetRightEdgeVisible(AValue: boolean);
begin
  FOriginalManager.RightEdgeVisible := AValue;
  FExtraManager.RightEdgeVisible := AValue;
end;

procedure TSourceLazSynSurfaceManager.SetVisibleSpecialChars(AValue: TSynVisibleSpecialChars);
begin
  FOriginalManager.VisibleSpecialChars := AValue;
  FExtraManager.VisibleSpecialChars := AValue;
end;

procedure TSourceLazSynSurfaceManager.SetHighlighter(AValue: TSynCustomHighlighter);
begin
  FOriginalManager.Highlighter := AValue;
  FExtraManager.Highlighter := AValue;
end;

procedure TSourceLazSynSurfaceManager.DoPaint(ACanvas: TCanvas; AClip: TRect);
begin
  FOriginalManager.Paint(ACanvas, AClip);
  FExtraManager.Paint(ACanvas, AClip);
end;

procedure TSourceLazSynSurfaceManager.BoundsChanged;
var
  t: Integer;
begin
  FExtraManager.LeftGutterWidth := LeftGutterWidth;
  FExtraManager.RightGutterWidth := RightGutterWidth;
  FOriginalManager.LeftGutterWidth := LeftGutterWidth;
  FOriginalManager.RightGutterWidth := RightGutterWidth;

  t := Min(Top + FTopLineCount * FExtraManager.TextArea.LineHeight,
           Max(Top, Bottom - FOriginalManager.TextArea.LineHeight)
          );
  FExtraManager.SetBounds(Top, Left, t, Right);
  FOriginalManager.SetBounds(t, Left, Bottom, Right);
end;

constructor TSourceLazSynSurfaceManager.Create(AOwner: TWinControl; AnOriginalManager: TLazSynSurfaceManager);
var
  txt: TLazSynTextArea;
  lgutter, rgutter: TLazSynGutterArea;
begin
  inherited Create(AOwner);
  FTopLineCount := 0;
  FOriginalManager := AnOriginalManager;

  txt := TLazSynTextArea.Create(AOwner, FOriginalManager.TextArea.TextDrawer);
  txt.Assign(FOriginalManager.TextArea);
  txt.TopLine := 1;
  txt.LeftChar := 1;

  lgutter:= TSourceLazSynSurfaceGutter.Create(AOwner);
  lgutter.Assign(FOriginalManager.LeftGutterArea);
  lgutter.TextArea := txt;

  rgutter:= TSourceLazSynSurfaceGutter.Create(AOwner);
  rgutter.Assign(FOriginalManager.RightGutterArea);
  rgutter.TextArea := txt;

  FExtraManager := TLazSynSurfaceManager.Create(AOwner);
  FExtraManager.TextArea := txt;
  FExtraManager.LeftGutterArea := lgutter;
  FExtraManager.RightGutterArea := rgutter;
end;

destructor TSourceLazSynSurfaceManager.Destroy;
begin
  inherited Destroy;
  FExtraManager.LeftGutterArea.Free;
  FExtraManager.RightGutterArea.Free;
  FExtraManager.TextArea.Free;
  FExtraManager.Free;
  FOriginalManager.Free;
end;

procedure TSourceLazSynSurfaceManager.InvalidateLines(FirstTextLine, LastTextLine: TLineIdx);
begin
  FOriginalManager.InvalidateLines(FirstTextLine, LastTextLine);
  FExtraManager.InvalidateLines(FirstTextLine, LastTextLine);
end;

procedure TSourceLazSynSurfaceManager.InvalidateTextLines(FirstTextLine, LastTextLine: TLineIdx);
begin
  FOriginalManager.InvalidateTextLines(FirstTextLine, LastTextLine);
  FExtraManager.InvalidateTextLines(FirstTextLine, LastTextLine);
end;

procedure TSourceLazSynSurfaceManager.InvalidateGutterLines(FirstTextLine, LastTextLine: TLineIdx);
begin
  FOriginalManager.InvalidateGutterLines(FirstTextLine, LastTextLine);
  FExtraManager.InvalidateGutterLines(FirstTextLine, LastTextLine);
end;

{ TIDESynEditor }

procedure TIDESynEditor.DoHighlightChanged(Sender: TSynEditStrings; AIndex, ACount: Integer);
begin
  FTopInfoNestList.Clear;
  if FSrcSynCaretChangedNeeded then
    SrcSynCaretChanged(nil);
end;

procedure TIDESynEditor.SrcSynCaretChanged(Sender: TObject);
  function RealTopLine: Integer;
  begin
    Result := TopLine - TSourceLazSynSurfaceManager(FPaintArea).TopLineCount;
  end;
var
  InfCnt, i, t, ListCnt: Integer;
  InfList: array [0..1] of
    record
      LineIndex: Integer;
      FoldType: TPascalCodeFoldBlockType;
    end;
  NodeFoldType: TPascalCodeFoldBlockType;
begin
  if (not FShowTopInfo) or (not HandleAllocated) or (TextView.HighLighter = nil) then exit;
  if FSrcSynCaretChangedLock or not(TextView.HighLighter is TSynPasSyn) then exit;

  if TextView.HighLighter.NeedScan then begin
    FSrcSynCaretChangedNeeded := True;
    exit;
  end;
  FSrcSynCaretChangedNeeded := False;

  FSrcSynCaretChangedLock := True;
  try
    ListCnt := 0;

    if CaretY >= RealTopLine then begin
      FTopInfoNestList.Lines := TextBuffer; // in case it changed
      FTopInfoNestList.Line := CaretY-1;
      FTopInfoNestList := FTopInfoNestList;

      InfCnt := FTopInfoNestList.Count;
      for i := InfCnt-1 downto 0 do begin
        NodeFoldType := TPascalCodeFoldBlockType({%H-}PtrUInt(FTopInfoNestList.NodeFoldType[i]));
        if not(NodeFoldType in
           [cfbtClass, cfbtClassSection, cfbtProcedure])
        then
          continue;

        if (NodeFoldType in [cfbtClassSection]) and (ListCnt = 0) then begin
          InfList[ListCnt].LineIndex := FTopInfoNestList.NodeLine[i];
          InfList[ListCnt].FoldType := NodeFoldType;
          inc(ListCnt);
        end;

        if (NodeFoldType in [cfbtClass]) and (ListCnt < 2) then begin
          InfList[ListCnt].LineIndex := FTopInfoNestList.NodeLine[i];
          InfList[ListCnt].FoldType := NodeFoldType;
          inc(ListCnt);
        end;

        if (NodeFoldType in [cfbtProcedure]) and (ListCnt < 2) then begin
          InfList[ListCnt].LineIndex := FTopInfoNestList.NodeLine[i];
          InfList[ListCnt].FoldType := NodeFoldType;
          inc(ListCnt);
        end;
        if (NodeFoldType in [cfbtProcedure]) and (ListCnt = 2) and
           (InfList[ListCnt-1].FoldType = cfbtProcedure)
        then begin
          InfList[ListCnt-1].LineIndex := FTopInfoNestList.NodeLine[i];
          InfList[ListCnt-1].FoldType := NodeFoldType;
        end;
      end;
    end;

    if TopLine <> FTopInfoLastTopLine then // if Sender = nil;
      ListCnt := Min(ListCnt, Max(0, CaretY - RealTopLine));

    t := TopLine + ListCnt - TSourceLazSynSurfaceManager(FPaintArea).TopLineCount;
    if (CaretY >= TopLine) and (CaretY < t) then
      t := CaretY;

    while ListCnt > 0 do begin
      if InfList[0].LineIndex + 1 >= t-1 then begin
        InfList[0] := InfList[1];
        dec(ListCnt);
        t := TopLine + ListCnt - TSourceLazSynSurfaceManager(FPaintArea).TopLineCount;
        if (CaretY >= TopLine) and (CaretY < t) then
          t := CaretY;
      end
      else
        break;
    end;

    FTopInfoDisplay.LineMapCount := ListCnt;

    if ListCnt <> TSourceLazSynSurfaceManager(FPaintArea).TopLineCount then begin
      TopLine := t;
      TSourceLazSynSurfaceManager(FPaintArea).TopLineCount := ListCnt;
      SizeOrFontChanged(FALSE);
      Invalidate; // TODO: move to PaintArea
    end;

    for i := 0 to ListCnt - 1 do begin
      if FTopInfoDisplay.LineMap[ListCnt-1-i] <> InfList[i].LineIndex then
        TSourceLazSynSurfaceManager(FPaintArea).ExtraManager.InvalidateLines(ListCnt-1-i, ListCnt-1-i);
      FTopInfoDisplay.LineMap[ListCnt-1-i] := InfList[i].LineIndex;
    end;

  finally
    FSrcSynCaretChangedLock := False;
    FTopInfoLastTopLine := TopLine;
  end;
end;

function TIDESynEditor.GetHighlighter: TSynCustomFoldHighlighter;
begin
  if Highlighter is TSynCustomFoldHighlighter then
    Result := TSynCustomFoldHighlighter(Highlighter)
  else
    Result := nil;
end;

procedure TIDESynEditor.DoOnStatusChange(Changes: TSynStatusChanges);
begin
  inherited DoOnStatusChange(Changes);
  if Changes * [scTopLine, scLinesInWindow] <> []then
      SrcSynCaretChanged(nil);
  {$push}{$R-}  // range check off
  if Changes * [scCaretX, scCaretY, scSelection] <> []then
    Inc(FCaretStamp);
  {$pop}
end;

procedure TIDESynEditor.GetTopInfoMarkupForLine(Sender: TObject; Line: integer;
  var Special: boolean; aMarkup: TSynSelectedColor);
begin
  Special := True;
  aMarkup.Assign(FTopInfoMarkup);
end;

procedure TIDESynEditor.SetCaretColor(AValue: TColor);
begin
  if FCaretColor = AValue then Exit;
  FCaretColor := AValue;
  if (AValue = clDefault) or (AValue = clNone) then begin
    FScreenCaretPainterClass{%H-} := TSynEditScreenCaretPainterSystem;
    if ScreenCaret.Painter.ClassType <> TSynEditScreenCaretPainterSystem then begin
      MultiCaret.ActiveMode := mcmNoCarets; // clear all carets, before changing the caret class
      ScreenCaret.ChangePainter(TSynEditScreenCaretPainterSystem);
  end;
  end
  else begin
    FScreenCaretPainterClass{%H-} := TSynEditScreenCaretPainterInternal;
    if ScreenCaret.Painter.ClassType <> TSynEditScreenCaretPainterInternal then begin
      MultiCaret.ActiveMode := mcmNoCarets; // clear all carets, before changing the caret class
      ScreenCaret.ChangePainter(TSynEditScreenCaretPainterInternal);
    end;
    TSynEditScreenCaretPainterInternal(ScreenCaret.Painter).Color := AValue;
  end;
end;

procedure TIDESynEditor.SetHighlightUserWordCount(AValue: Integer);
var
  m: TSourceSynEditMarkupHighlightAllMulti;
begin
  if AValue = FUserWordsList.Count then
    exit;

  while FUserWordsList.Count > AValue do begin
    TSynEditMarkupManager(MarkupMgr).RemoveMarkUp(TSourceSynEditMarkupHighlightAllMulti(FUserWordsList[AValue]));
    TSourceSynEditMarkupHighlightAllMulti(FUserWordsList[AValue]).Free;
    FUserWordsList.Delete(AValue);
  end;

  while AValue > FUserWordsList.Count do begin
    m := TSourceSynEditMarkupHighlightAllMulti.Create(self);
    if PaintLock > 0 then
      m.IncPaintLock;
    m.FoldView := TSynEditFoldedView(FoldedTextBuffer);
    if Highlighter <> nil then
      m.WordBreakChars := Highlighter.WordBreakChars + TSynWhiteChars;
    FUserWordsList.Add(m);
    TSynEditMarkupManager(MarkupMgr).AddMarkUp(m);
  end;
end;

procedure TIDESynEditor.SetOnMultiCaretBeforeCommand(AValue: TSynMultiCaretBeforeCommand);
begin
  FMultiCaret.OnBeforeCommand := AValue;
end;

procedure TIDESynEditor.SetShowTopInfo(AValue: boolean);
begin
  if FShowTopInfo = AValue then Exit;
  FShowTopInfo := AValue;
  if FShowTopInfo then begin
    SrcSynCaretChanged(nil)
  end
  else
  if TSourceLazSynSurfaceManager(FPaintArea).TopLineCount <> 0 then begin
    TSourceLazSynSurfaceManager(FPaintArea).TopLineCount := 0;
    Invalidate; // TODO: move to PaintArea
  end;
end;

procedure TIDESynEditor.SetTopInfoMarkup(AValue: TSynSelectedColor);
begin
  if FTopInfoMarkup = AValue then Exit;
  FTopInfoMarkup.Assign(AValue);
end;

function TIDESynEditor.GetIDEGutterMarks: TIDESynGutterMarks;
begin
  Result := TIDESynGutterMarks(Gutter.Parts.ByClass[TIDESynGutterMarks, 0]);
end;

function TIDESynEditor.GetIsInMultiCaretMainExecution: Boolean;
begin
  Result := FMultiCaret.IsInMainExecution;
end;

function TIDESynEditor.GetIsInMultiCaretRepeatExecution: Boolean;
begin
  Result := FMultiCaret.IsInRepeatExecution;
end;

function TIDESynEditor.GetOnMultiCaretBeforeCommand: TSynMultiCaretBeforeCommand;
begin
  Result := FMultiCaret.OnBeforeCommand;
end;

function TIDESynEditor.IsIfdefMarkupActive: Boolean;
begin
  Result := FMarkupIfDef.RealEnabled;
end;

function TIDESynEditor.DoIfDefNodeStateRequest(Sender: TObject; LinePos,
  XStartPos: Integer; CurrentState: TSynMarkupIfdefNodeStateEx): TSynMarkupIfdefNodeState;
begin
  //debugln(['TIDESynEditor.DoIfDefNodeStateRequest x=',XStartPos,' y=',LinePos,' ',DbgSName(Sender)]);
  if FOnIfdefNodeStateRequest <> nil then
    Result := FOnIfdefNodeStateRequest(Self, LinePos, XStartPos, CurrentState)
  else
    Result := idnInvalid;
end;

procedure TIDESynEditor.InvalidateAllIfdefNodes;
begin
  FMarkupIfDef.InvalidateAll;
end;

procedure TIDESynEditor.SetIfdefNodeState(ALinePos, AstartPos: Integer;
  AState: TSynMarkupIfdefNodeState);
begin
  FMarkupIfDef.SetNodeState(ALinePos, AstartPos, AState);
end;

function TIDESynEditor.GetHighlightUserWordCount: Integer;
begin
  Result := FUserWordsList.Count;
end;

function TIDESynEditor.GetHighlightUserWords(AIndex: Integer): TSourceSynEditMarkupHighlightAllMulti;
begin
  Result := TSourceSynEditMarkupHighlightAllMulti(FUserWordsList[AIndex])
end;

function TIDESynEditor.CreateGutter(AOwner: TSynEditBase; ASide: TSynGutterSide;
  ATextDrawer: TheTextDrawer): TSynGutter;
begin
  Result := TIDESynGutter.Create(AOwner, ASide, ATextDrawer);
end;

procedure TIDESynEditor.SetHighlighter(const Value: TSynCustomHighlighter);
var
  i: Integer;
begin
  if Value = Highlighter then begin
    inherited SetHighlighter(Value);
    exit
  end;

  FMarkupIfDef.Highlighter := nil;

  inherited SetHighlighter(Value);

//TSynEditMarkupFoldColors(MarkupByClass[TSynEditMarkupFoldColors]).Highlighter := Highlighter; // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  if Highlighter is TSynPasSyn then
    FMarkupIfDef.Highlighter := TSynPasSyn(Highlighter)
  else
    FMarkupIfDef.Highlighter := nil;

  if Highlighter is TSynCustomFoldHighlighter then
    FTopInfoNestList.Highlighter := TSynCustomFoldHighlighter(Highlighter)
  else
    FTopInfoNestList.Highlighter := nil;

  if FUserWordsList = nil then
    exit;
  if Highlighter <> nil then
    for i := 0 to FUserWordsList.Count - 1 do
      HighlightUserWords[i].WordBreakChars := Highlighter.WordBreakChars + TSynWhiteChars
  else
    for i := 0 to FUserWordsList.Count - 1 do
      HighlightUserWords[i].ResetWordBreaks;
end;

constructor TIDESynEditor.Create(AOwner: TComponent);
var
  MarkupFoldColors: TSynEditMarkupFoldColors;
begin
  inherited Create(AOwner);
  FCaretColor := clNone;
  FUserWordsList := TFPList.Create;
  FTemplateEdit:=TSynPluginTemplateEdit.Create(Self);
  FSyncroEdit := TSynPluginSyncroEdit.Create(Self);
  FMultiCaret := TSynPluginMultiCaret.Create(Self);
  FMultiCaret.MouseActions.Clear; // will be added to SynEdit
  FMultiCaret.KeyStrokes.Clear;
  FMultiCaret.SetCaretTypeSize(ctVerticalLine, 2, 1024, -1, 0, [ccsRelativeHeight]);
  FMultiCaret.SetCaretTypeSize(ctBlock, 1024, 1024, 0, 0, [ccsRelativeWidth, ccsRelativeHeight]);
  FMultiCaret.Color := $606060;

  FMarkupForGutterMark := TSynEditMarkupGutterMark.Create(Self, FWordBreaker);
  TSynEditMarkupManager(MarkupMgr).AddMarkUp(FMarkupForGutterMark);

  MarkupFoldColors := TSynEditMarkupFoldColors.Create(Self);
  //MarkupFoldColors.DefaultGroup := 0;
  TSynEditMarkupManager(MarkupMgr).AddMarkUp(MarkupFoldColors);

  FMarkupIfDef := TSourceSynEditMarkupIfDef.Create(Self);
  FMarkupIfDef.FoldView := TSynEditFoldedView(FoldedTextBuffer);
  //FMarkupIfDef.OnNodeStateRequest := @DoIfDefNodeStateRequest;
  TSynEditMarkupManager(MarkupMgr).AddMarkUp(FMarkupIfDef);

  FMarkupIdentComplWindow := TSynMarkupIdentComplWindow.Create;

  FPaintArea := TSourceLazSynSurfaceManager.Create(Self, FPaintArea);
  GetCaretObj.AddChangeHandler(@SrcSynCaretChanged);

  FTopInfoDisplay := TSourceLazSynTopInfoView.Create;
  FTopInfoDisplay.NextView := ViewedTextBuffer.DisplayView;
  TSourceLazSynSurfaceManager(FPaintArea).TopLineCount := 0;
//  TSourceLazSynSurfaceManager(FPaintArea).ExtraManager.TextArea.BackgroundColor := clSilver;
  TSourceLazSynSurfaceManager(FPaintArea).ExtraManager.DisplayView := FTopInfoDisplay;

  FTopInfoNestList := TLazSynEditNestedFoldsList.Create(TextBuffer);
  FTopInfoNestList.ResetFilter;
  FTopInfoNestList.FoldGroup := FOLDGROUP_PASCAL;
  FTopInfoNestList.FoldFlags := [sfbIncludeDisabled];
  FTopInfoNestList.IncludeOpeningOnLine := False;
  FTopInfoMarkup := TSynSelectedColor.Create;
  FTopInfoMarkup.Clear;

  ViewedTextBuffer.AddChangeHandler(senrHighlightChanged, @DoHighlightChanged);

  // Markup for top info hint
  FExtraMarkupLine := TSynEditMarkupSpecialLine.Create(Self);
  FExtraMarkupLine.OnSpecialLineMarkup  := @GetTopInfoMarkupForLine;
  FExtraMarkupMgr := TSynEditMarkupManager.Create(Self);
  FExtraMarkupMgr.AddMarkUp(TSynEditMarkup(MarkupMgr));
  FExtraMarkupMgr.AddMarkUp(FExtraMarkupLine);
  FExtraMarkupMgr.Lines := ViewedTextBuffer;
  FExtraMarkupMgr.Caret := GetCaretObj;
  FExtraMarkupMgr.InvalidateLinesMethod := @InvalidateLines;

  TSourceLazSynSurfaceManager(FPaintArea).ExtraManager.TextArea.MarkupManager :=
    FExtraMarkupMgr;
  {$IFDEF WithSynDebugGutter}
  TIDESynGutter(RightGutter).DebugGutter.TheLinesView := ViewedTextBuffer;
  {$ENDIF}
end;

destructor TIDESynEditor.Destroy;
begin
  HighlightUserWordCount := 0;
  Highlighter := nil;
  FreeAndNil(FUserWordsList);
  FExtraMarkupMgr.RemoveMarkUp(TSynEditMarkup(MarkupMgr));
  FreeAndNil(FTopInfoDisplay);
  FreeAndNil(FExtraMarkupMgr);
  FreeAndNil(FTopInfoMarkup);
  FreeAndNil(FTopInfoNestList);
  FreeAndNil(FMarkupIdentComplWindow);
  inherited Destroy;
end;

function TIDESynEditor.TextIndexToViewPos(aTextIndex: Integer): Integer;
begin
  Result := TextView.TextIndexToViewPos(aTextIndex - 1);
end;

{$IFDEF WinIME}
procedure TIDESynEditor.CreateMinimumIme;
var
  Ime: LazSynIme;
begin
  if ImeHandler is LazSynImeSimple then exit;
  Ime := LazSynImeSimple.Create(Self);
  LazSynImeSimple(Ime).TextDrawer := TextDrawer;
  Ime.InvalidateLinesMethod := @InvalidateLines;
  ImeHandler := Ime;
end;

procedure TIDESynEditor.CreateFullIme;
var
  Ime: LazSynIme;
begin
  if ImeHandler is LazSynImeFull then exit;
  Ime := LazSynImeFull.Create(Self);
  Ime.InvalidateLinesMethod := @InvalidateLines;
  ImeHandler := Ime;
end;

{$ENDIF}

{ TIDESynPasSyn }

function TIDESynPasSyn.GetFinalizationLine: Integer;
begin
  Result := TIDESynHighlighterPasRangeList(CurrentRanges).FFinalizationLine;
end;

function TIDESynPasSyn.GetImplementationLine: Integer;
begin
  Result := TIDESynHighlighterPasRangeList(CurrentRanges).FImplementationLine;
end;

function TIDESynPasSyn.GetInitializationLine: Integer;
begin
  Result := TIDESynHighlighterPasRangeList(CurrentRanges).FInitializationLine;
end;

function TIDESynPasSyn.GetInterfaceLine: Integer;
begin
  Result := TIDESynHighlighterPasRangeList(CurrentRanges).FInterfaceLine;
end;

function TIDESynPasSyn.CreateRangeList(ALines: TSynEditStringsBase): TSynHighlighterRangeList;
begin
  Result := TIDESynHighlighterPasRangeList.Create;
  TIDESynHighlighterPasRangeList(Result).FInterfaceLine := -1;
  TIDESynHighlighterPasRangeList(Result).FImplementationLine := -1;
  TIDESynHighlighterPasRangeList(Result).FInitializationLine := -1;
  TIDESynHighlighterPasRangeList(Result).FFinalizationLine := -1;
end;

function TIDESynPasSyn.StartCodeFoldBlock(ABlockType: Pointer;
  IncreaseLevel: Boolean; ForceDisabled: Boolean): TSynCustomCodeFoldBlock;
begin
  if (ABlockType = Pointer(PtrUInt(cfbtUnitSection))) or
     (ABlockType = Pointer(PtrUInt(cfbtUnitSection)) + {%H-}PtrUInt(CountPascalCodeFoldBlockOffset))
  then begin
    if KeyComp('Interface') then
      TIDESynHighlighterPasRangeList(CurrentRanges).FInterfaceLine := LineIndex  + 1;
    if KeyComp('Implementation') then
      TIDESynHighlighterPasRangeList(CurrentRanges).FImplementationLine := LineIndex  + 1;
    if KeyComp('Initialization') then
      TIDESynHighlighterPasRangeList(CurrentRanges).FInitializationLine := LineIndex  + 1;
    if KeyComp('Finalization') then
      TIDESynHighlighterPasRangeList(CurrentRanges).FFinalizationLine := LineIndex  + 1;
  end;
  Result := inherited;
end;

procedure TIDESynPasSyn.SetLine(const NewValue: string; LineNumber: Integer);
begin
  if assigned(CurrentRanges) then begin
    if TIDESynHighlighterPasRangeList(CurrentRanges).FInterfaceLine = LineNumber + 1 then
      TIDESynHighlighterPasRangeList(CurrentRanges).FInterfaceLine := -1;
    if TIDESynHighlighterPasRangeList(CurrentRanges).FImplementationLine = LineNumber + 1 then
      TIDESynHighlighterPasRangeList(CurrentRanges).FImplementationLine := -1;
    if TIDESynHighlighterPasRangeList(CurrentRanges).FInitializationLine = LineNumber + 1 then
      TIDESynHighlighterPasRangeList(CurrentRanges).FInitializationLine := -1;
    if TIDESynHighlighterPasRangeList(CurrentRanges).FFinalizationLine = LineNumber + 1 then
      TIDESynHighlighterPasRangeList(CurrentRanges).FFinalizationLine := -1;
  end;
  inherited SetLine(NewValue, LineNumber);
end;

{ TIDESynFreePasSyn }

constructor TIDESynFreePasSyn.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  CompilerMode:=pcmObjFPC;
end;

procedure TIDESynFreePasSyn.ResetRange;
begin
  inherited ResetRange;
  CompilerMode:=pcmObjFPC;
end;

{ TIDESynGutterLOvProviderPascal }

procedure TIDESynGutterLOvProviderPascal.SetSingleLine(const AValue: Boolean);
begin
  if FSingleLine = AValue then exit;
  FSingleLine := AValue;
  InvalidatePixelLines(0, Height);
end;

procedure TIDESynGutterLOvProviderPascal.SetColor2(const AValue: TColor);
begin
  if FColor2 = AValue then exit;
  FColor2 := AValue;
  FRGBColor2 := ColorToRGB(AValue);
  DoChange(Self);
end;

procedure TIDESynGutterLOvProviderPascal.BufferChanged(Sender: TObject);
begin
  TSynEditStringList(Sender).RemoveHanlders(self);
  TSynEditStringList(TextBuffer).AddChangeHandler(senrHighlightChanged,
    @HighlightChanged);
  TSynEditStringList(TextBuffer).AddNotifyHandler(senrTextBufferChanged,
    @BufferChanged);
  //LineCountChanged(nil, 0, 0);
  HighlightChanged(nil,-1,-1);
end;

procedure TIDESynGutterLOvProviderPascal.HighlightChanged(Sender: TSynEditStrings; AIndex,
  ACount: Integer);
var
  hl: TIDESynPasSyn;
  procedure Update(var TheVal: Integer; NewVal: Integer);
  begin
    if TheVal = NewVal then exit;
    if FSingleLine then begin
      InvalidatePixelLines(TheVal, TheVal);
      InvalidatePixelLines(NewVal, NewVal);
    end else begin
      InvalidatePixelLines(Min(TheVal, NewVal), Height);
    end;

    TheVal := NewVal;
  end;
var i1,i1e,i2,i2e,i3,i3e,i4,i4e: Integer;
begin
  i1  := FPixInterfaceLine;
  i1e := FPixEndInterfaceLine;
  i2  := FPixImplementationLine;
  i2e := FPixEndImplementationLine;
  i3  := FPixInitializationLine;
  i3e := FPixEndInitializationLine;
  i4  := FPixFinalizationLine;
  i4e := FPixEndFinalizationLine;
  if not(TSynEdit(SynEdit).Highlighter is TIDESynPasSyn) then begin
    FInterfaceLine := -1;
    FImplementationLine := -1;
    FInitializationLine := -1;
    FFinalizationLine := -1;
  end else begin
    hl := TSynEdit(SynEdit).Highlighter as TIDESynPasSyn;
    if hl.CurrentLines = nil then exit;
    FInterfaceLine :=      hl.InterfaceLine;
    FImplementationLine := hl.ImplementationLine;
    FInitializationLine := hl.InitializationLine;
    FFinalizationLine :=   hl.FinalizationLine;
  end;

  ReCalc;

  if (i1 <> FPixInterfaceLine) or (i1e <> FPixEndInterfaceLine) then begin
    InvalidatePixelLines(i1,i1e);
    InvalidatePixelLines(FPixInterfaceLine, FPixEndInterfaceLine);
  end;
  if (i2 <> FPixImplementationLine) or (i2e <> FPixEndImplementationLine) then begin
    InvalidatePixelLines(i2,i2e);
    InvalidatePixelLines(FPixImplementationLine, FPixEndImplementationLine);
  end;
  if (i3 <> FPixInitializationLine) or (i3e <> FPixEndInitializationLine) then begin
    InvalidatePixelLines(i3,i3e);
    InvalidatePixelLines(FPixInitializationLine, FPixEndInitializationLine);
  end;
  if (i4 <> FPixFinalizationLine) or (i4e <> FPixEndFinalizationLine) then begin
    InvalidatePixelLines(i4,i4e);
    InvalidatePixelLines(FPixFinalizationLine, FPixEndFinalizationLine);
  end;
end;

procedure TIDESynGutterLOvProviderPascal.ReCalc;
begin
  FPixInterfaceLine      := TextLineToPixel(FInterfaceLine);
  FPixImplementationLine := TextLineToPixel(FImplementationLine);
  FPixInitializationLine := TextLineToPixel(FInitializationLine);
  FPixFinalizationLine   := TextLineToPixel(FFinalizationLine);

  if SingleLine then begin
    if FPixInterfaceLine < 0 then
      FPixEndInterfaceLine := -1
    else
      FPixEndInterfaceLine      := TextLineToPixelEnd(FInterfaceLine) + 1;

    if FPixImplementationLine < 0 then
      FPixEndImplementationLine := -1
    else
      FPixEndImplementationLine := TextLineToPixelEnd(FImplementationLine) + 1;

    if FPixInitializationLine < 0 then
      FPixEndInitializationLine := -1
    else
      FPixEndInitializationLine := TextLineToPixelEnd(FInitializationLine) + 1;

    if FPixFinalizationLine < 0 then
      FPixEndFinalizationLine := -1
    else
      FPixEndFinalizationLine   := TextLineToPixelEnd(FFinalizationLine) + 1;
  end else begin
    if FPixInterfaceLine < 0 then
      FPixEndInterfaceLine := -1
    else if FPixImplementationLine >= 0 then
      FPixEndInterfaceLine := FPixImplementationLine - 1
    else if FPixInitializationLine >= 0 then
      FPixEndInterfaceLine := FPixInitializationLine - 1
    else if FPixFinalizationLine >= 0 then
      FPixEndInterfaceLine := FPixFinalizationLine - 1
    else
      FPixEndInterfaceLine := Height - 1;

    if FPixImplementationLine < 0 then
      FPixEndImplementationLine := -1
    else if FPixInitializationLine >= 0 then
      FPixEndImplementationLine := FPixInitializationLine - 1
    else if FPixFinalizationLine >= 0 then
      FPixEndImplementationLine := FPixFinalizationLine - 1
    else
      FPixEndImplementationLine := Height - 1;

    if FPixInitializationLine < 0 then
      FPixEndInitializationLine := -1
    else if FPixFinalizationLine >= 0 then
      FPixEndInitializationLine := FPixFinalizationLine - 1
    else
      FPixEndInitializationLine := Height - 1;

    if FPixFinalizationLine < 0 then
      FPixEndFinalizationLine := -1
    else
      FPixEndFinalizationLine := Height - 1;
  end;
end;

procedure TIDESynGutterLOvProviderPascal.Paint(Canvas: TCanvas; AClip: TRect;
  TopOffset: integer);
  procedure DrawArea(AStartLine, AEndLine: Integer; C: TColor);
  var r: TRect;
  begin
    if (C = clNone) and SingleLine then
      c := Color;
    if (C = clNone) then
      exit;

    if (AStartLine + TopOffset > AClip.Bottom) or
       (AEndLine + TopOffset < AClip.Top)
    then
      exit;
    r := AClip;
    r.Top    := Max(r.Top, AStartLine + TopOffset);
    r.Bottom := Min(r.Bottom, AEndLine + 1 + TopOffset);
    Canvas.Brush.Color := C;
    Canvas.FillRect(r);
  end;
var
  C2, C3: TColor;
begin
  if FPixInterfaceLine >= 0 then
    DrawArea(FPixInterfaceLine, FPixEndInterfaceLine, Color);

  if FPixImplementationLine >= 0 then
    DrawArea(FPixImplementationLine, FPixEndImplementationLine, Color2);

  C2 := Color;
  C3 := Color2;
  if FPixImplementationLine < 0 then begin
    C2 := Color2;
    if FPixInitializationLine >= 0 then
      C3 := Color;
  end;

  if FPixInitializationLine >= 0 then
    DrawArea(FPixInitializationLine, FPixEndInitializationLine, C2);

  if FPixFinalizationLine >= 0 then
    DrawArea(FPixFinalizationLine, FPixEndFinalizationLine, C3);
end;

constructor TIDESynGutterLOvProviderPascal.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  SingleLine := False;
  Color  := $D4D4D4;
  Color2 := $E8E8E8;
  TSynEditStringList(TextBuffer).AddChangeHandler(senrHighlightChanged,
    @HighlightChanged);
  TSynEditStringList(TextBuffer).AddNotifyHandler(senrTextBufferChanged,
    @BufferChanged);
end;

destructor TIDESynGutterLOvProviderPascal.Destroy;
begin
  TSynEditStringList(TextBuffer).RemoveHanlders(self);
  inherited Destroy;
end;

{ TIDESynGutterLOvProviderIDEMarks }

procedure TIDESynGutterLOvProviderIDEMarks.SetBreakColor(const AValue: TColor);
begin
  if FBreakColor = AValue then exit;
  FBreakColor := AValue;
  FRGBBreakColor := ColorToRGB(AValue);
  DoChange(Self);
end;

procedure TIDESynGutterLOvProviderIDEMarks.SetBreakDisabledColor(AValue: TColor);
begin
  if FBreakDisabledColor = AValue then Exit;
  FBreakDisabledColor := AValue;
  FRGBBreakDisabledColor := ColorToRGB(AValue);
  DoChange(Self);
end;

procedure TIDESynGutterLOvProviderIDEMarks.SetExecLineColor(AValue: TColor);
begin
  if FExecLineColor = AValue then Exit;
  FExecLineColor := AValue;
  FRGBExecLineColor := ColorToRGB(AValue);
  DoChange(Self);
end;

procedure TIDESynGutterLOvProviderIDEMarks.AdjustColorForMark(AMark: TSynEditMark;
  var AColor: TColor; var APriority: Integer);
var
  i: Integer;
  ETMark: TETMark;
begin
  if (AMark is TETMark) then begin
    ETMark:=TETMark(AMark);
    AColor:=ETMark.SourceMarks.MarkStyles[ETMark.Urgency].Color;
  end else begin
    inc(APriority, 1);
    if not AMark.IsBookmark then begin
      //if (AMark.ImageList = SourceEditorMarks.ImgList) then begin
      i := AMark.ImageIndex;
      if (i = SourceEditorMarks.CurrentLineImg) or
         (i = SourceEditorMarks.CurrentLineBreakPointImg) or
         (i = SourceEditorMarks.CurrentLineDisabledBreakPointImg)
      then begin
        dec(APriority, 1);
        AColor := TColor(FRGBExecLineColor);
      end
      else
      if (i = SourceEditorMarks.InactiveBreakPointImg) or
         (i = SourceEditorMarks.InvalidDisabledBreakPointImg) or
         (i = SourceEditorMarks.UnknownDisabledBreakPointImg)
      then begin
        inc(APriority, 2);
        AColor := TColor(FRGBBreakDisabledColor);
      end
      else begin
        AColor := TColor(FRGBBreakColor);
        inc(APriority, 1);
      end;
    end;
  end;
  inherited AdjustColorForMark(AMark, AColor, APriority);
end;

constructor TIDESynGutterLOvProviderIDEMarks.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  BreakColor         := $0080C8;
  BreakDisabledColor := $00D000;
  ExecLineColor      := $F000D0;
end;

{ TIDESynGutter }

procedure TIDESynGutter.CreateDefaultGutterParts;
begin
  IncChangeLock;
  try
    if Side = gsLeft then begin
      with TIDESynGutterMarks.Create(Parts) do
        Name := 'SynGutterMarks1';
      with TSynGutterLineNumber.Create(Parts) do
        Name := 'SynGutterLineNumber1';
      with TSynGutterChanges.Create(Parts) do
        Name := 'SynGutterChanges1';
      with TSynGutterSeparator.Create(Parts) do
        Name := 'SynGutterSeparator1';
      with TIDESynGutterCodeFolding.Create(Parts) do
        Name := 'SynGutterCodeFolding1';
    end
    else begin
      {$IFDEF WithSynDebugGutter}
      with TSynGutterSeparator.Create(Parts) do
        Name := 'SynGutterSeparatorR1';
      DebugGutter := TIDESynGutterDebugHL.Create(Parts);
      with DebugGutter do
        Name := 'TIDESynGutterDebugHL';
      {$ENDIF}
      with TSynGutterSeparator.Create(Parts) do
        Name := 'SynGutterSeparatorR2';
      with TSynGutterLineOverview.Create(Parts) do begin
        Name := 'SynGutterLineOverview1';
        with TIDESynGutterLOvProviderIDEMarks.Create(Providers) do
          Priority := 20;
        with TSynGutterLOvProviderModifiedLines.Create(Providers) do
          Priority := 9;
        with TSynGutterLOvProviderCurrentPage.Create(Providers) do begin
          Priority := 1;
          FoldedTextBuffer := TSynEditFoldedView(TIDESynEditor(Self.SynEdit).FoldedTextBuffer);
        end;
        with TIDESynGutterLOvProviderPascal.Create(Providers) do
          Priority := 0;
      end;
      with TSynGutterSeparator.Create(Parts) do begin
        Name := 'SynGutterSeparatorR3';
        AutoSize := False;
        Width := 1;
        LineWidth := 0;
      end;
    end;
  finally
    DecChangeLock;
  end;
end;

{ TIDESynGutterMarks }

procedure TIDESynGutterMarks.CheckTextBuffer;
begin
  if (FMarkInfoTextBuffer <> nil) and
     (FMarkInfoTextBuffer <> TIDESynEditor(SynEdit).TextBuffer)
  then begin
    FMarkInfoTextBuffer := nil;
    if FDebugMarkInfo <> nil then FDebugMarkInfo.DecRefCount;
    if (FDebugMarkInfo <> nil) and (FDebugMarkInfo.RefCount = 0) then
      FreeAndNil(FDebugMarkInfo);
  end;
end;

procedure TIDESynGutterMarks.PaintLine(aScreenLine: Integer; Canvas: TCanvas; AClip: TRect);
var
  aGutterOffs, TxtIdx: Integer;
  HasAnyMark: Boolean;

  procedure DrawDebugMark(Line: Integer);
  var
    itop : Longint;
    LineHeight: LongInt;
    img: TScaledImageListResolution;
  begin
    if Line < 0 then Exit;
    if Assigned(FBookMarkOpt.BookmarkImages) and
       (DebugMarksImageIndex <= FBookMarkOpt.BookmarkImages.Count) and
       (DebugMarksImageIndex >= 0) then
    begin
      LineHeight := TSynEdit(SynEdit).LineHeight;
      img := GetImgListRes(Canvas, FBookMarkOpt.BookmarkImages);
      iTop := 0;
      if LineHeight > img.Height then
        iTop := (LineHeight - img.Height) div 2;

      img.Draw
        (Canvas, AClip.Left + LeftMarginAtCurrentPPI + aGutterOffs * ColumnWidth,
         AClip.Top + iTop, DebugMarksImageIndex, True);
    end
  end;

begin
  CheckTextBuffer;
  aGutterOffs := 0;
  HasAnyMark := PaintMarks(aScreenLine, Canvas, AClip, aGutterOffs);
  TxtIdx := FoldView.TextIndex[aScreenLine];
  if (TxtIdx < 0) or (TxtIdx >= TSynEdit(SynEdit).Lines.Count) then
    exit;
  if (not HasAnyMark) and (HasDebugMarks) and (TxtIdx < FDebugMarkInfo.Count) and
     (FDebugMarkInfo.SrcLineToMarkLine[TxtIdx] > 0)
  then
    DrawDebugMark(aScreenLine);
end;

function TIDESynGutterMarks.PreferedWidthAtCurrentPPI: Integer;
var
  img: TScaledImageListResolution;
begin
  if Assigned(SourceEditorMarks) and Assigned(SourceEditorMarks.ImgList) then
  begin
    img := GetImgListRes(nil, SourceEditorMarks.ImgList);
    // + 1 => right margin
    Result := img.Width * 2 + LeftMarginAtCurrentPPI + Scale96ToFont(1);
  end else
    Result := inherited PreferedWidthAtCurrentPPI;
end;

destructor TIDESynGutterMarks.Destroy;
begin
  ClearDebugMarks;
  inherited;
end;

procedure TIDESynGutterMarks.BeginSetDebugMarks;
begin
  CheckTextBuffer;

  if FDebugMarkInfo = nil then begin
    FDebugMarkInfo := TIDESynDebugMarkInfo(TIDESynEditor(SynEdit).TextBuffer.Ranges[ClassType]);
    if FDebugMarkInfo = nil then begin
      FDebugMarkInfo := TIDESynDebugMarkInfo.Create;
      // Todo: Add a notification, when TextBuffer Changes
      FMarkInfoTextBuffer := TIDESynEditor(SynEdit).TextBuffer;
      TIDESynEditor(SynEdit).TextBuffer.Ranges[ClassType] := FDebugMarkInfo;
    end
    else
      FDebugMarkInfo.IncRefCount;
  end;
end;

procedure TIDESynGutterMarks.EndSetDebugMarks;
begin
  TSynEdit(SynEdit).InvalidateGutter;
end;

function TIDESynGutterMarks.GetImgListRes(const ACanvas: TCanvas;
  const AImages: TCustomImageList): TScaledImageListResolution;
const
  AllowedHeights: array[0..7] of Integer = (5, 7, 9, 11, 16, 22, 33, 44);
var
  Scale: Double;
  PPI, LineHeight, I, ImageHeight: Integer;
begin
  // image height must be equal to width
  if AImages.Width<>AImages.Height then
    raise Exception.Create('Internal error: AImages.Width<>AImages.Height');

  Scale := 1;
  PPI := 96;
  if SynEdit is TSynEdit then
  begin
    LineHeight := TSynEdit(SynEdit).LineHeight;
    if LineHeight - Max(0, TSynEdit(SynEdit).ExtraLineSpacing) > 11 then
      LineHeight := LineHeight - Max(0, TSynEdit(SynEdit).ExtraLineSpacing);
    if LineHeight > 22 then
      I := LineHeight div 8
    else
      I := 1;
    If LineHeight - I >= 11 then
      LineHeight := LineHeight - I;
    if LineHeight < 11 then begin
      LineHeight := TSynEdit(SynEdit).LineHeight;
      if LineHeight > 11 then
        LineHeight := LineHeight - 1;
    end;
    ImageHeight := AllowedHeights[0];
    for I := High(AllowedHeights) downto Low(AllowedHeights) do
      if AllowedHeights[I] <= LineHeight then
      begin
        ImageHeight := AllowedHeights[I];
        break;
      end;
    // don't set PPI here -> we don't want to scale the image anymore
  end else
  begin
    ImageHeight := AImages.Height;
    if ACanvas is TControlCanvas then
      PPI := TControlCanvas(ACanvas).Control.Font.PixelsPerInch;
  end;

  if ACanvas is TControlCanvas then
    Scale := TControlCanvas(ACanvas).Control.GetCanvasScaleFactor;
  Result := AImages.ResolutionForPPI[ImageHeight, PPI, Scale];
end;

procedure TIDESynGutterMarks.SetDebugMarks(AFirstLinePos, ALastLinePos: Integer);
var
  i: LongInt;
begin
  CheckTextBuffer;

  if ALastLinePos > FDebugMarkInfo.Count then begin
    //debugln(['Request to set debug-mark out of range: max-count=',FDebugMarkInfo.Count,' Marks=',AFirstLinePos,' to=',ALastLinePos]);
    ALastLinePos := FDebugMarkInfo.Count;
  end;
  if AFirstLinePos < 1 then begin
    //debugln(['Request to set debug-mark out of range: max-count=',FDebugMarkInfo.Count,' Marks=',AFirstLinePos,' to=',ALastLinePos]);
    AFirstLinePos := 1;
  end;
  for i := AFirstLinePos - 1 to ALastLinePos - 1 do
    FDebugMarkInfo[i] := i + 1;
end;

procedure TIDESynGutterMarks.ClearDebugMarks;
begin
  CheckTextBuffer;

  if FDebugMarkInfo = nil then exit;
  FDebugMarkInfo.DecRefCount;
  if FDebugMarkInfo.RefCount = 0 then begin
    TIDESynEditor(SynEdit).TextBuffer.Ranges[ClassType] := nil;
    FreeAndNil(FDebugMarkInfo);
  end;
  FDebugMarkInfo := nil;
  FMarkInfoTextBuffer := nil;
  TSynEdit(SynEdit).InvalidateGutter;
end;

function TIDESynGutterMarks.HasDebugMarks: Boolean;
begin
  CheckTextBuffer;
  if FDebugMarkInfo = nil then begin
    FDebugMarkInfo := TIDESynDebugMarkInfo(TIDESynEditor(SynEdit).TextBuffer.Ranges[ClassType]);
    if FDebugMarkInfo <> nil then begin
      FDebugMarkInfo.IncRefCount;
      TSynEdit(SynEdit).InvalidateGutter;
    end;
  end;
  Result := FDebugMarkInfo <> nil;
end;

function TIDESynGutterMarks.DebugLineToSourceLine(aLinePos: Integer): Integer;
var
  i, c: LongInt;
begin
  CheckTextBuffer;
  if (aLinePos < 1) or (not HasDebugMarks) then exit(aLinePos);
  Result := aLinePos - 1; // 0 based
  if (FDebugMarkInfo[Result] = 0) or (FDebugMarkInfo[Result] > aLinePos) then begin
    i := Result;
    repeat
      dec(i);
      while (i >= 0) and (FDebugMarkInfo[i] = 0) do dec(i);
      if (i < 0) or (FDebugMarkInfo[i] < aLinePos) then break;
      Result := i;
    until FDebugMarkInfo[Result] = aLinePos;
    if (FDebugMarkInfo[Result] > aLinePos) and // line not found
       (Result > 0) and (FDebugMarkInfo[Result - 1] = 0)
    then
      dec(Result);
  end;
  if (FDebugMarkInfo[Result] = 0) or (FDebugMarkInfo[Result] < aLinePos) then begin
    c := FDebugMarkInfo.Count;
    i := Result;
    repeat
      inc(i);
      while (i < c) and (FDebugMarkInfo[i] = 0) do inc(i);
      if (i >= c) or (FDebugMarkInfo[i] > aLinePos) then break;
      Result := i;
    until FDebugMarkInfo[Result] = aLinePos;
    if (FDebugMarkInfo[Result] < aLinePos) and // line not found
       (Result < c-1) and (FDebugMarkInfo[Result + 1] = 0)
    then
      inc(Result);
  end;
  inc(Result); // 1 based
end;

function TIDESynGutterMarks.SourceLineToDebugLine(aLinePos: Integer;
  AdjustOnError: Boolean): Integer;
begin
  CheckTextBuffer;
  if (aLinePos < 1) or (not HasDebugMarks) or (aLinePos >= FDebugMarkInfo.Count) then
    exit(aLinePos);
  Result := FDebugMarkInfo[aLinePos - 1];
  while (Result = 0) and AdjustOnError and (aLinePos < FDebugMarkInfo.Count-1) do begin
    inc(aLinePos);
    Result := FDebugMarkInfo[aLinePos - 1];
  end;
end;

{ TIDESynDebugMarkInfo }

function TIDESynDebugMarkInfo.GetSrcLineToMarkLine(SrcIndex: Integer): Integer;
begin
  Result := Integer(ItemPointer[SrcIndex]^);
end;

procedure TIDESynDebugMarkInfo.SetSrcLineToMarkLine(SrcIndex: Integer; const AValue: Integer);
begin
  Integer(ItemPointer[SrcIndex]^) := AValue;
end;

constructor TIDESynDebugMarkInfo.Create;
begin
  Inherited;
  ItemSize := SizeOf(Integer);
  FRefCount := 1;
end;

procedure TIDESynDebugMarkInfo.IncRefCount;
begin
  inc(FRefCount);
end;

procedure TIDESynDebugMarkInfo.DecRefCount;
begin
  dec(FRefCount);
end;

{ TIDESynGutterCodeFolding }

procedure TIDESynGutterCodeFolding.PopClickedFoldIfdef(Sender: TObject);
begin
  FoldIfdef(True);
end;

procedure TIDESynGutterCodeFolding.PopClickedFoldIfdefNoMixed(Sender: TObject);
begin
  FoldIfdef(False);
end;

procedure TIDESynGutterCodeFolding.PopClickedUnfoldIfdefActive(Sender: TObject);
begin
  UnFoldIfdef(False, True);
end;

procedure TIDESynGutterCodeFolding.PopClickedUnfolDIfdefAll(Sender: TObject);
begin
  UnFoldIfdef(True, True);
end;

procedure TIDESynGutterCodeFolding.PopClickedUnfoldIfdefInactiv(Sender: TObject);
begin
  UnFoldIfdef(True, False);
end;

procedure TIDESynGutterCodeFolding.UnFoldIfdef(AInclDisabled, AInclEnabled: Boolean);
var
  i, j, k, y1, y2: Integer;
  FldInf: TSynFoldNodeInfo;
  Tree: TSynMarkupHighIfDefLinesTree;
  IfLineNode: TSynMarkupHighIfDefLinesNodeInfo;
  IsDisabled: Boolean;
begin
  if TSynEdit(SynEdit).SelAvail then begin
    y1 := TSynEdit(SynEdit).BlockBegin.Y;
    y2 := TSynEdit(SynEdit).BlockEnd.Y;
    if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  end
  else begin
    y1 := 1;
    y2 := TSynEdit(SynEdit).Lines.Count - 1;
  end;
  Tree := TIDESynEditor(SynEdit).FMarkupIfDef.IfDefTree;

  if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  for i := y1-1 to y2-1 do begin
    j := FoldView.FoldProvider.FoldOpenCount(i);
    while j > 0 do begin
      dec(j);
      if FoldView.IsFoldedAtTextIndex(i,j) then begin
        FldInf := FoldView.FoldProvider.FoldOpenInfo(i, j);
        if TPascalCodeFoldBlockType({%H-}PtrUInt(FldInf.FoldType)) in [cfbtIfDef]
        then begin
          if AInclDisabled and AInclEnabled then begin
            FoldView.UnFoldAtTextIndex(i, j, 1, False, 1);
          end
          else begin
            IfLineNode := Tree.FindNodeAtPosition(ToPos(i), afmNil);
            k := IfLineNode.EntryCount - 1;
            while (k >= 0) and (IfLineNode.Entry[k].StartColumn <> FldInf.LogXStart) do
              dec(k);
            IsDisabled := (k >= 0) and (IfLineNode.Entry[k].IsDisabled);
            if (AInclDisabled and IsDisabled) or (AInclEnabled and not IsDisabled) then
              FoldView.UnFoldAtTextIndex(i, j, 1, False, 1);
          end;
        end;
      end; //FoldView.IsFoldedAtTextIndex(i,j)
    end;
  end;
end;

procedure TIDESynGutterCodeFolding.FoldIfdef(AInclTemp: Boolean);
var
  i, j, k, y1, y2: Integer;
  FldInf: TSynFoldNodeInfo;
  Tree: TSynMarkupHighIfDefLinesTree;
  IfLineNode: TSynMarkupHighIfDefLinesNodeInfo;
begin
  if TSynEdit(SynEdit).SelAvail then begin
    y1 := TSynEdit(SynEdit).BlockBegin.Y;
    y2 := TSynEdit(SynEdit).BlockEnd.Y;
    if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  end
  else begin
    y1 := 1;
    y2 := TSynEdit(SynEdit).Lines.Count - 1;
  end;
  Tree := TIDESynEditor(SynEdit).FMarkupIfDef.IfDefTree;
  if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  for i := y1-1 to y2-1 do begin
    j := FoldView.FoldProvider.FoldOpenCount(i);
    while j > 0 do begin
      dec(j);
      FldInf := FoldView.FoldProvider.FoldOpenInfo(i, j);
      if (TPascalCodeFoldBlockType({%H-}PtrUInt(FldInf.FoldType)) in [cfbtIfDef]) and
         (sfaFoldFold in FldInf.FoldAction)
      then begin
        IfLineNode := Tree.FindNodeAtPosition(ToPos(i), afmNil);
        k := IfLineNode.EntryCount - 1;
        while (k >= 0) and (IfLineNode.Entry[k].StartColumn <> FldInf.LogXStart) do
          dec(k);
        if (k >= 0) and (IfLineNode.Entry[k].IsDisabled) and
           ( (not (IfLineNode.Entry[k].IsTemp)) or AInclTemp )
        then
          FoldView.FoldAtTextIndex(i, j, 1, False, 1);
      end;
    end;
  end;
end;

procedure TIDESynGutterCodeFolding.PopClickedUnfoldAll(Sender: TObject);
var
  i, y1, y2: Integer;
begin
  if not TSynEdit(SynEdit).SelAvail then begin
    FoldView.UnfoldAll;
    exit;
  end;
  y1 := TSynEdit(SynEdit).BlockBegin.Y;
  y2 := TSynEdit(SynEdit).BlockEnd.Y;
  if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  for i := y1-1 to y2-1 do
    FoldView.UnFoldAtTextIndex(i);
end;

procedure TIDESynGutterCodeFolding.PopClickedUnfoldComment(Sender: TObject);
var
  i, j, y1, y2: Integer;
  FldInf: TSynFoldNodeInfo;
begin
  if TSynEdit(SynEdit).SelAvail then begin
    y1 := TSynEdit(SynEdit).BlockBegin.Y;
    y2 := TSynEdit(SynEdit).BlockEnd.Y;
    if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  end
  else begin
    y1 := 1;
    y2 := TSynEdit(SynEdit).Lines.Count - 1;
  end;

  for i := y1-1 to y2-1 do begin
    j := FoldView.FoldProvider.FoldOpenCount(i);
    while j > 0 do begin
      dec(j);
      if FoldView.IsFoldedAtTextIndex(i,j) then begin
        FldInf := FoldView.FoldProvider.FoldOpenInfo(i, j);
        if TPascalCodeFoldBlockType({%H-}PtrUInt(FldInf.FoldType)) in
           [cfbtAnsiComment, cfbtBorCommand, cfbtSlashComment]
        then begin
          FoldView.UnFoldAtTextIndex(i, j, 1, False, 0);
          FoldView.UnFoldAtTextIndex(i, j, 1, False, 1);
        end;
      end;
    end;
  end;
end;

procedure TIDESynGutterCodeFolding.PopClickedFoldComment(Sender: TObject);
var
  i, j, y1, y2: Integer;
  FldInf: TSynFoldNodeInfo;
begin
  if TSynEdit(SynEdit).SelAvail then begin
    y1 := TSynEdit(SynEdit).BlockBegin.Y;
    y2 := TSynEdit(SynEdit).BlockEnd.Y;
    if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  end
  else begin
    y1 := 1;
    y2 := TSynEdit(SynEdit).Lines.Count - 1;
  end;

  for i := y1-1 to y2-1 do begin
    j := FoldView.FoldProvider.FoldOpenCount(i);
    while j > 0 do begin
      dec(j);
      FldInf := FoldView.FoldProvider.FoldOpenInfo(i, j);
      if (TPascalCodeFoldBlockType({%H-}PtrUInt(FldInf.FoldType)) in
          [cfbtAnsiComment, cfbtBorCommand, cfbtSlashComment]) and
         (sfaFoldFold in FldInf.FoldAction)
      then begin
        FoldView.FoldAtTextIndex(i, j, 1, False, 1);
      end;
    end;
  end;
end;

procedure TIDESynGutterCodeFolding.PopClickedHideComment(Sender: TObject);
var
  i, j, y1, y2: Integer;
  FldInf: TSynFoldNodeInfo;
begin
  if TSynEdit(SynEdit).SelAvail then begin
    y1 := TSynEdit(SynEdit).BlockBegin.Y;
    y2 := TSynEdit(SynEdit).BlockEnd.Y;
    if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  end
  else begin
    y1 := 1;
    y2 := TSynEdit(SynEdit).Lines.Count - 1;
  end;

  for i := y1-1 to y2-1 do begin
    j := FoldView.FoldProvider.FoldOpenCount(i);
    while j > 0 do begin
      dec(j);
      FldInf := FoldView.FoldProvider.FoldOpenInfo(i, j);
      if (TPascalCodeFoldBlockType({%H-}PtrUInt(FldInf.FoldType)) in
          [cfbtAnsiComment, cfbtBorCommand, cfbtSlashComment]) and
         (sfaFoldHide in FldInf.FoldAction)
      then begin
        FoldView.FoldAtTextIndex(i, j, 1, False, 0);
      end;
    end;
  end;
end;

procedure TIDESynGutterCodeFolding.CreatePopUpMenuEntries(var APopUp: TPopupMenu; ALine: Integer);
var
  i, j, k, y1, y2: Integer;
  HasFolds, HasHideableComments, HasFoldableComments, HasCollapsedComments: Boolean;
  ft: TPascalCodeFoldBlockType;
  Foldable, HideAble: TPascalCodeFoldBlockTypes;
  lc: TSynEditFoldLineCapabilities;
  HasFoldableDisabledIfDef, HasFoldableTempDisabledIfDef,
  HasCollapsedActiveIfDef, HasCollapsedDisabledIfDef: Boolean; // HasCollapsedActiveIfDef includes all NOT disabled
  Tree: TSynMarkupHighIfDefLinesTree;
  IfLineNode: TSynMarkupHighIfDefLinesNodeInfo;
  FProv: TSynEditFoldProvider;
  inf: TSynFoldNodeInfo;
  HasComments, HasIfdef: Boolean;

  procedure CheckFoldConf(Val: TPascalCodeFoldBlockType);
  begin
    if not TSynPasSyn(FoldView.HighLighter).FoldConfig[ord(Val)].Enabled then
      exit;
    if fmFold in TSynPasSyn(FoldView.HighLighter).FoldConfig[ord(Val)].Modes then
      include(Foldable, Val);
    if fmHide in TSynPasSyn(FoldView.HighLighter).FoldConfig[ord(Val)].Modes then
      include(HideAble, Val);
  end;

  function AddPopUpItem(const ACaption: String): TMenuItem;
  begin
    Result := TMenuItem.Create(APopUp);
    Result.Caption := ACaption;
    APopUp.Items.Add(Result);
  end;


begin
  inherited CreatePopUpMenuEntries(APopUp, ALine);

  if not (FoldView.HighLighter is TSynPasSyn) then
    exit;

  Foldable := [];
  HideAble := [];
  CheckFoldConf(cfbtAnsiComment);
  CheckFoldConf(cfbtBorCommand);
  CheckFoldConf(cfbtSlashComment);
  if TIDESynEditor(SynEdit).IsIfdefMarkupActive then
    CheckFoldConf(cfbtIfDef);

  if (Foldable = []) and (HideAble = []) then
    exit;

  HasHideableComments           := False;
  HasFoldableComments           := False;
  HasCollapsedComments          := False;
  HasFoldableDisabledIfDef      := False;
  HasFoldableTempDisabledIfDef  := False;
  HasCollapsedActiveIfDef       := False;
  HasCollapsedDisabledIfDef     := False;

  HasComments := (Foldable*[cfbtAnsiComment, cfbtBorCommand, cfbtSlashComment] <> []) or
                 (HideAble*[cfbtAnsiComment, cfbtBorCommand, cfbtSlashComment] <> []);
  HasIfdef := (Foldable*[cfbtIfDef] <> []);

  if TSynEdit(SynEdit).SelAvail then begin
    y1 := TSynEdit(SynEdit).BlockBegin.Y;
    y2 := TSynEdit(SynEdit).BlockEnd.Y;
    if TSynEdit(SynEdit).BlockEnd.X = 1 then dec(y2);
  end
  else begin
    y1 := 1;
    y2 := TSynEdit(SynEdit).Lines.Count - 1;
  end;


  HasFolds := FoldView.TextIndexToViewPos(y2) - FoldView.TextIndexToViewPos(y1) <> y2 - y1;
  //debugln(['*** HasFolds=', HasFolds, ' y1=',y1, ' y2=',y2, ' VP1=',FoldView.TextIndexToViewPos(y1), ' VP2=',FoldView.TextIndexToViewPos(y2)]);

  FProv := FoldView.FoldProvider;
  Tree := TIDESynEditor(SynEdit).FMarkupIfDef.IfDefTree;
  IfLineNode.ClearInfo;

  i := ToIdx(y1);
  while i < y2 do begin // lines in selection
    lc := FProv.LineCapabilities[i];
    j := FProv.FoldOpenCount(i);

    while j > 0 do begin // foldnodes on line
      dec(j);
      inf := FProv.FoldOpenInfo(i, j);
      ft := TPascalCodeFoldBlockType({%H-}PtrUInt(inf.FoldType));
      if not ((ft in Foldable) or (ft in HideAble)) then
        continue;

      if ft = cfbtIfDef then begin
        if IfLineNode.StartLine <> ToPos(i) then
          IfLineNode := Tree.FindNodeAtPosition(ToPos(i), afmNil);
        k := IfLineNode.EntryCount - 1; // -1 if no node
        while (k >= 0) and (IfLineNode.Entry[k].StartColumn <> inf.LogXStart) do
          dec(k);
        if FoldView.IsFoldedAtTextIndex(i,j) then begin
          if (k >= 0) and (IfLineNode.Entry[k].IsDisabled) then
            HasCollapsedDisabledIfDef := True
          else
            HasCollapsedActiveIfDef := True;
        end
        else // IFDEF is only Fold-able, not hide-able
        if (k >= 0) and (IfLineNode.Entry[k].IsDisabled) then begin
          if IfLineNode.Entry[k].IsTemp then
            HasFoldableTempDisabledIfDef := True
          else
            HasFoldableDisabledIfDef := True;
        end;

      end
      else begin
        // comment
        if FoldView.IsFoldedAtTextIndex(i,j) then begin
          HasCollapsedComments := True;
        end
        else begin
          if (ft in Foldable) and (cfFoldStart in lc) then
            HasFoldableComments := True;
          if (ft in HideAble) and (cfHideStart in lc) then
            HasHideableComments := True;
        end;
      end;
    end;

    if (not HasComments) or
       ( (HasFoldableComments and HasHideableComments) and
         ((not HasFolds) or (HasCollapsedComments))
       )
    then begin
      // found all comment info
      if (not HasIfdef) or
         ( (HasFoldableDisabledIfDef and HasFoldableTempDisabledIfDef) and
           ((not HasFolds) or (HasCollapsedActiveIfDef and HasCollapsedDisabledIfDef))
         )
      then
        break;
      // only Ifdef needed
      if IfLineNode.HasNode and (IfLineNode.StartLine = ToPos(i)) then
        IfLineNode := IfLineNode.Successor
      else
        IfLineNode := Tree.FindNodeAtPosition(ToPos(i)+1, afmNext);
      if not IfLineNode.HasNode then
        break;
      i := ToIdx(IfLineNode.StartLine);
    end
    else
      inc(i);
  end;

  if (HasFolds) and (APopUp.Items.Count > 0) then
    AddPopUpItem(cLineCaption);
  If HasFolds then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfUnfoldAllInSelection).OnClick := @PopClickedUnfoldAll
    else AddPopUpItem(synfUnfoldAll).OnClick := @PopClickedUnfoldAll;


  if (HasCollapsedComments or HasFoldableComments or HasHideableComments) and
     (APopUp.Items.Count > 0)
  then
    AddPopUpItem(cLineCaption);

  If HasCollapsedComments then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfUnfoldCommentsInSelection).OnClick := @PopClickedUnfoldComment
    else AddPopUpItem(synfUnfoldComments).OnClick := @PopClickedUnfoldComment;
  If HasFoldableComments then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfFoldCommentsInSelection).OnClick := @PopClickedFoldComment
    else AddPopUpItem(synfFoldComments).OnClick := @PopClickedFoldComment;
  If HasHideableComments then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfHideCommentsInSelection).OnClick := @PopClickedHideComment
    else AddPopUpItem(synfHideComments).OnClick := @PopClickedHideComment;


  if (HasFoldableDisabledIfDef or HasCollapsedDisabledIfDef or
      HasCollapsedDisabledIfDef or HasCollapsedActiveIfDef) and
     (APopUp.Items.Count > 0)
  then
    AddPopUpItem(cLineCaption);

  If HasCollapsedActiveIfDef and HasCollapsedDisabledIfDef then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfUnfoldAllIfdefInSelection).OnClick := @PopClickedUnfolDIfdefAll
    else AddPopUpItem(synfUnfoldAllIfdef).OnClick := @PopClickedUnfolDIfdefAll;
  If HasCollapsedActiveIfDef then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfUnfoldActiveIfdefInSelection).OnClick := @PopClickedUnfoldIfdefActive
    else AddPopUpItem(synfUnfoldActiveIfdef).OnClick := @PopClickedUnfoldIfdefActive;
  If HasCollapsedDisabledIfDef then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfUnfoldInactiveIfdefInSelection).OnClick := @PopClickedUnfoldIfdefInactiv
    else AddPopUpItem(synfUnfoldInactiveIfdef).OnClick := @PopClickedUnfoldIfdefInactiv;

  If HasFoldableDisabledIfDef or HasFoldableTempDisabledIfDef then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfFoldInactiveIfdefInSelection).OnClick := @PopClickedFoldIfdef
    else AddPopUpItem(synfFoldInactiveIfdef).OnClick := @PopClickedFoldIfdef;
  If HasFoldableDisabledIfDef and HasFoldableTempDisabledIfDef then
    if TSynEdit(SynEdit).SelAvail
    then AddPopUpItem(synfFoldInactiveIfdefInSelectionExcludeMixedState).OnClick := @PopClickedFoldIfdefNoMixed
    else AddPopUpItem(synfFoldInactiveIfdefExcludeMixedState).OnClick := @PopClickedFoldIfdefNoMixed;
end;

end.