1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
|
// Scintilla source code edit control
/** @file Document.cxx
** Text document that handles notifications, DBCS, styling, words and end of line.
**/
// Copyright 1998-2011 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <cstddef>
#include <cstdlib>
#include <cstdint>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <array>
#include <map>
#include <forward_list>
#include <optional>
#include <algorithm>
#include <memory>
#include <chrono>
#ifndef NO_CXX11_REGEX
#include <regex>
#endif
#include "ScintillaTypes.h"
#include "ILoader.h"
#include "ILexer.h"
#include "Debugging.h"
#include "CharacterType.h"
#include "CharacterCategoryMap.h"
#include "Position.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "CellBuffer.h"
#include "PerLine.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "RESearch.h"
#include "UniConversion.h"
#include "ElapsedPeriod.h"
using namespace Scintilla;
using namespace Scintilla::Internal;
#if defined(__GNUC__) && !defined(__clang__)
// False warnings from g++ 14.1 for UTF-8 accumulation code where UTF8MaxBytes allocated.
#pragma GCC diagnostic ignored "-Wstringop-overflow"
#endif
LexInterface::LexInterface(Document *pdoc_) noexcept : pdoc(pdoc_), performingStyle(false) {
}
LexInterface::~LexInterface() noexcept = default;
void LexInterface::SetInstance(ILexer5 *instance_) noexcept {
instance.reset(instance_);
}
void LexInterface::Colourise(Sci::Position start, Sci::Position end) {
if (pdoc && instance && !performingStyle) {
// Protect against reentrance, which may occur, for example, when
// fold points are discovered while performing styling and the folding
// code looks for child lines which may trigger styling.
performingStyle = true;
const Sci::Position lengthDoc = pdoc->Length();
if (end == -1)
end = lengthDoc;
const Sci::Position len = end - start;
PLATFORM_ASSERT(len >= 0);
PLATFORM_ASSERT(start + len <= lengthDoc);
int styleStart = 0;
if (start > 0)
styleStart = pdoc->StyleAt(start - 1);
if (len > 0) {
instance->Lex(start, len, styleStart, pdoc);
instance->Fold(start, len, styleStart, pdoc);
}
performingStyle = false;
}
}
LineEndType LexInterface::LineEndTypesSupported() {
if (instance) {
return static_cast<LineEndType>(instance->LineEndTypesSupported());
}
return LineEndType::Default;
}
bool LexInterface::UseContainerLexing() const noexcept {
return !instance;
}
ActionDuration::ActionDuration(double duration_, double minDuration_, double maxDuration_) noexcept :
duration(duration_), minDuration(minDuration_), maxDuration(maxDuration_) {
}
void ActionDuration::AddSample(size_t numberActions, double durationOfActions) noexcept {
// Only adjust for multiple actions to avoid instability
if (numberActions < 8)
return;
// Alpha value for exponential smoothing.
// Most recent value contributes 25% to smoothed value.
constexpr double alpha = 0.25;
const double durationOne = durationOfActions / static_cast<double>(numberActions);
duration = std::clamp(alpha * durationOne + (1.0 - alpha) * duration,
minDuration, maxDuration);
}
double ActionDuration::Duration() const noexcept {
return duration;
}
size_t ActionDuration::ActionsInAllowedTime(double secondsAllowed) const noexcept {
return std::lround(secondsAllowed / Duration());
}
const CharacterExtracted characterEmpty(unicodeReplacementChar, 0);
const CharacterExtracted characterBadByte(unicodeReplacementChar, 1);
CharacterExtracted::CharacterExtracted(const unsigned char *charBytes, size_t widthCharBytes) noexcept {
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid) {
// Treat as invalid and use up just one byte
character = unicodeReplacementChar;
widthBytes = 1;
} else {
character = UnicodeFromUTF8(charBytes);
widthBytes = utf8status & UTF8MaskWidth;
}
}
Document::Document(DocumentOption options) :
refCount(0),
cb(!FlagSet(options, DocumentOption::StylesNone), FlagSet(options, DocumentOption::TextLarge)),
endStyled(0),
styleClock(0),
enteredModification(0),
enteredStyling(0),
enteredReadOnlyCount(0),
insertionSet(false),
#ifdef _WIN32
eolMode(EndOfLine::CrLf),
#else
eolMode(EndOfLine::Lf),
#endif
dbcsCodePage(CpUtf8),
lineEndBitSet(LineEndType::Default),
tabInChars(8),
indentInChars(0),
actualIndentInChars(8),
useTabs(true),
tabIndents(true),
backspaceUnindents(false),
durationStyleOneByte(0.000001, 0.0000001, 0.00001) {
perLineData[ldMarkers] = std::make_unique<LineMarkers>();
perLineData[ldLevels] = std::make_unique<LineLevels>();
perLineData[ldState] = std::make_unique<LineState>();
perLineData[ldMargin] = std::make_unique<LineAnnotation>();
perLineData[ldAnnotation] = std::make_unique<LineAnnotation>();
perLineData[ldEOLAnnotation] = std::make_unique<LineAnnotation>();
decorations = DecorationListCreate(IsLarge());
cb.SetPerLine(this);
cb.SetUTF8Substance(CpUtf8 == dbcsCodePage);
}
Document::~Document() {
for (const WatcherWithUserData &watcher : watchers) {
watcher.watcher->NotifyDeleted(this, watcher.userData);
}
}
// Increase reference count and return its previous value.
int SCI_METHOD Document::AddRef() noexcept {
return refCount++;
}
// Decrease reference count and return its previous value.
// Delete the document if reference count reaches zero.
int SCI_METHOD Document::Release() {
const int curRefCount = --refCount;
if (curRefCount == 0)
delete this;
return curRefCount;
}
void Document::Init() {
for (const std::unique_ptr<PerLine> &pl : perLineData) {
if (pl)
pl->Init();
}
}
void Document::InsertLine(Sci::Line line) {
for (const std::unique_ptr<PerLine> &pl : perLineData) {
if (pl)
pl->InsertLine(line);
}
}
void Document::InsertLines(Sci::Line line, Sci::Line lines) {
for (const auto &pl : perLineData) {
if (pl)
pl->InsertLines(line, lines);
}
}
void Document::RemoveLine(Sci::Line line) {
for (const std::unique_ptr<PerLine> &pl : perLineData) {
if (pl)
pl->RemoveLine(line);
}
}
LineMarkers *Document::Markers() const noexcept {
return static_cast<LineMarkers *>(perLineData[ldMarkers].get());
}
LineLevels *Document::Levels() const noexcept {
return static_cast<LineLevels *>(perLineData[ldLevels].get());
}
LineState *Document::States() const noexcept {
return static_cast<LineState *>(perLineData[ldState].get());
}
LineAnnotation *Document::Margins() const noexcept {
return static_cast<LineAnnotation *>(perLineData[ldMargin].get());
}
LineAnnotation *Document::Annotations() const noexcept {
return static_cast<LineAnnotation *>(perLineData[ldAnnotation].get());
}
LineAnnotation *Document::EOLAnnotations() const noexcept {
return static_cast<LineAnnotation *>(perLineData[ldEOLAnnotation].get());
}
LineEndType Document::LineEndTypesSupported() const {
if ((CpUtf8 == dbcsCodePage) && pli)
return pli->LineEndTypesSupported();
else
return LineEndType::Default;
}
bool Document::SetDBCSCodePage(int dbcsCodePage_) {
if (dbcsCodePage != dbcsCodePage_) {
dbcsCodePage = dbcsCodePage_;
SetCaseFolder(nullptr);
cb.SetLineEndTypes(lineEndBitSet & LineEndTypesSupported());
cb.SetUTF8Substance(CpUtf8 == dbcsCodePage);
ModifiedAt(0); // Need to restyle whole document
return true;
} else {
return false;
}
}
bool Document::SetLineEndTypesAllowed(LineEndType lineEndBitSet_) {
if (lineEndBitSet != lineEndBitSet_) {
lineEndBitSet = lineEndBitSet_;
const LineEndType lineEndBitSetActive = lineEndBitSet & LineEndTypesSupported();
if (lineEndBitSetActive != cb.GetLineEndTypes()) {
ModifiedAt(0);
cb.SetLineEndTypes(lineEndBitSetActive);
return true;
} else {
return false;
}
} else {
return false;
}
}
void Document::SetSavePoint() {
cb.SetSavePoint();
NotifySavePoint(true);
}
void Document::TentativeUndo() {
if (!TentativeActive())
return;
CheckReadOnly();
if (enteredModification == 0) {
enteredModification++;
if (!cb.IsReadOnly()) {
const bool startSavePoint = cb.IsSavePoint();
bool multiLine = false;
const int steps = cb.TentativeSteps();
//Platform::DebugPrintf("Steps=%d\n", steps);
for (int step = 0; step < steps; step++) {
const Sci::Line prevLinesTotal = LinesTotal();
const Action action = cb.GetUndoStep();
if (action.at == ActionType::remove) {
NotifyModified(DocModification(
ModificationFlags::BeforeInsert | ModificationFlags::Undo, action));
} else if (action.at == ActionType::container) {
DocModification dm(ModificationFlags::Container | ModificationFlags::Undo);
dm.token = action.position;
NotifyModified(dm);
} else {
NotifyModified(DocModification(
ModificationFlags::BeforeDelete | ModificationFlags::Undo, action));
}
cb.PerformUndoStep();
if (action.at != ActionType::container) {
ModifiedAt(action.position);
}
ModificationFlags modFlags = ModificationFlags::Undo;
// With undo, an insertion action becomes a deletion notification
if (action.at == ActionType::remove) {
modFlags |= ModificationFlags::InsertText;
} else if (action.at == ActionType::insert) {
modFlags |= ModificationFlags::DeleteText;
}
if (steps > 1)
modFlags |= ModificationFlags::MultiStepUndoRedo;
const Sci::Line linesAdded = LinesTotal() - prevLinesTotal;
if (linesAdded != 0)
multiLine = true;
if (step == steps - 1) {
modFlags |= ModificationFlags::LastStepInUndoRedo;
if (multiLine)
modFlags |= ModificationFlags::MultilineUndoRedo;
}
NotifyModified(DocModification(modFlags, action.position, action.lenData,
linesAdded, action.data));
}
const bool endSavePoint = cb.IsSavePoint();
if (startSavePoint != endSavePoint)
NotifySavePoint(endSavePoint);
cb.TentativeCommit();
}
enteredModification--;
}
}
int Document::UndoActions() const noexcept {
return cb.UndoActions();
}
void Document::SetUndoSavePoint(int action) noexcept {
cb.SetUndoSavePoint(action);
}
int Document::UndoSavePoint() const noexcept {
return cb.UndoSavePoint();
}
void Document::SetUndoDetach(int action) noexcept {
cb.SetUndoDetach(action);
}
int Document::UndoDetach() const noexcept {
return cb.UndoDetach();
}
void Document::SetUndoTentative(int action) noexcept {
cb.SetUndoTentative(action);
}
int Document::UndoTentative() const noexcept {
return cb.UndoTentative();
}
void Document::SetUndoCurrent(int action) {
cb.SetUndoCurrent(action);
}
int Document::UndoCurrent() const noexcept {
return cb.UndoCurrent();
}
int Document::UndoActionType(int action) const noexcept {
return cb.UndoActionType(action);
}
Sci::Position Document::UndoActionPosition(int action) const noexcept {
return cb.UndoActionPosition(action);
}
std::string_view Document::UndoActionText(int action) const noexcept {
return cb.UndoActionText(action);
}
void Document::PushUndoActionType(int type, Sci::Position position) {
cb.PushUndoActionType(type, position);
}
void Document::ChangeLastUndoActionText(size_t length, const char *text) {
cb.ChangeLastUndoActionText(length, text);
}
int Document::GetMark(Sci::Line line, bool includeChangeHistory) const {
int marksHistory = 0;
if (includeChangeHistory && (line < LinesTotal())) {
int marksEdition = 0;
const Sci::Position start = LineStart(line);
const Sci::Position lineNext = LineStart(line + 1);
for (Sci::Position position = start; position < lineNext;) {
const int edition = EditionAt(position);
if (edition) {
marksEdition |= 1 << (edition-1);
}
position = EditionEndRun(position);
}
const Sci::Position lineEnd = LineEnd(line);
for (Sci::Position position = start; position <= lineEnd;) {
marksEdition |= EditionDeletesAt(position);
position = EditionNextDelete(position);
}
/* Bits: RevertedToOrigin, Saved, Modified, RevertedToModified */
constexpr unsigned int editionShift = static_cast<unsigned int>(MarkerOutline::HistoryRevertedToOrigin);
marksHistory = marksEdition << editionShift;
}
return marksHistory | Markers()->MarkValue(line);
}
Sci::Line Document::MarkerNext(Sci::Line lineStart, int mask) const noexcept {
return Markers()->MarkerNext(lineStart, mask);
}
int Document::AddMark(Sci::Line line, int markerNum) {
if (line >= 0 && line < LinesTotal()) {
const int prev = Markers()->AddMark(line, markerNum, LinesTotal());
const DocModification mh(ModificationFlags::ChangeMarker, LineStart(line), 0, 0, nullptr, line);
NotifyModified(mh);
return prev;
} else {
return -1;
}
}
void Document::AddMarkSet(Sci::Line line, int valueSet) {
if (line < 0 || line >= LinesTotal()) {
return;
}
unsigned int m = valueSet;
for (int i = 0; m; i++, m >>= 1) {
if (m & 1)
Markers()->AddMark(line, i, LinesTotal());
}
const DocModification mh(ModificationFlags::ChangeMarker, LineStart(line), 0, 0, nullptr, line);
NotifyModified(mh);
}
void Document::DeleteMark(Sci::Line line, int markerNum) {
Markers()->DeleteMark(line, markerNum, false);
const DocModification mh(ModificationFlags::ChangeMarker, LineStart(line), 0, 0, nullptr, line);
NotifyModified(mh);
}
void Document::DeleteMarkFromHandle(int markerHandle) {
Markers()->DeleteMarkFromHandle(markerHandle);
DocModification mh(ModificationFlags::ChangeMarker);
mh.line = -1;
NotifyModified(mh);
}
void Document::DeleteAllMarks(int markerNum) {
bool someChanges = false;
for (Sci::Line line = 0; line < LinesTotal(); line++) {
if (Markers()->DeleteMark(line, markerNum, true))
someChanges = true;
}
if (someChanges) {
DocModification mh(ModificationFlags::ChangeMarker);
mh.line = -1;
NotifyModified(mh);
}
}
Sci::Line Document::LineFromHandle(int markerHandle) const noexcept {
return Markers()->LineFromHandle(markerHandle);
}
int Document::MarkerNumberFromLine(Sci::Line line, int which) const noexcept {
return Markers()->NumberFromLine(line, which);
}
int Document::MarkerHandleFromLine(Sci::Line line, int which) const noexcept {
return Markers()->HandleFromLine(line, which);
}
Sci_Position SCI_METHOD Document::LineStart(Sci_Position line) const {
return cb.LineStart(line);
}
Range Document::LineRange(Sci::Line line) const noexcept {
return {cb.LineStart(line), cb.LineStart(line + 1)};
}
bool Document::IsLineStartPosition(Sci::Position position) const noexcept {
return LineStartPosition(position) == position;
}
Sci_Position SCI_METHOD Document::LineEnd(Sci_Position line) const {
return cb.LineEnd(line);
}
int SCI_METHOD Document::DEVersion() const noexcept {
return deRelease0;
}
void SCI_METHOD Document::SetErrorStatus(int status) {
// Tell the watchers an error has occurred.
for (const WatcherWithUserData &watcher : watchers) {
watcher.watcher->NotifyErrorOccurred(this, watcher.userData, static_cast<Status>(status));
}
}
Sci_Position SCI_METHOD Document::LineFromPosition(Sci_Position pos) const {
return cb.LineFromPosition(pos);
}
Sci::Line Document::SciLineFromPosition(Sci::Position pos) const noexcept {
// Avoids casting in callers for this very common function
return cb.LineFromPosition(pos);
}
Sci::Position Document::LineStartPosition(Sci::Position position) const noexcept {
return cb.LineStart(cb.LineFromPosition(position));
}
Sci::Position Document::LineEndPosition(Sci::Position position) const noexcept {
return cb.LineEnd(cb.LineFromPosition(position));
}
bool Document::IsLineEndPosition(Sci::Position position) const noexcept {
return LineEndPosition(position) == position;
}
bool Document::IsPositionInLineEnd(Sci::Position position) const noexcept {
return position >= LineEndPosition(position);
}
Sci::Position Document::VCHomePosition(Sci::Position position) const {
const Sci::Line line = SciLineFromPosition(position);
const Sci::Position startPosition = LineStart(line);
const Sci::Position endLine = LineEnd(line);
Sci::Position startText = startPosition;
while (startText < endLine && IsSpaceOrTab(cb.CharAt(startText)))
startText++;
if (position == startText)
return startPosition;
else
return startText;
}
Sci::Position Document::IndexLineStart(Sci::Line line, LineCharacterIndexType lineCharacterIndex) const noexcept {
return cb.IndexLineStart(line, lineCharacterIndex);
}
Sci::Line Document::LineFromPositionIndex(Sci::Position pos, LineCharacterIndexType lineCharacterIndex) const noexcept {
return cb.LineFromPositionIndex(pos, lineCharacterIndex);
}
Sci::Line Document::LineFromPositionAfter(Sci::Line line, Sci::Position length) const noexcept {
const Sci::Position posAfter = cb.LineStart(line) + length;
if (posAfter >= LengthNoExcept()) {
return LinesTotal();
}
const Sci::Line lineAfter = SciLineFromPosition(posAfter);
if (lineAfter > line) {
return lineAfter;
} else {
// Want to make some progress so return next line
return lineAfter + 1;
}
}
int SCI_METHOD Document::SetLevel(Sci_Position line, int level) {
const int prev = Levels()->SetLevel(line, level, LinesTotal());
if (prev != level) {
DocModification mh(ModificationFlags::ChangeFold | ModificationFlags::ChangeMarker,
LineStart(line), 0, 0, nullptr, line);
mh.foldLevelNow = static_cast<FoldLevel>(level);
mh.foldLevelPrev = static_cast<FoldLevel>(prev);
NotifyModified(mh);
}
return prev;
}
int SCI_METHOD Document::GetLevel(Sci_Position line) const {
return Levels()->GetLevel(line);
}
FoldLevel Document::GetFoldLevel(Sci_Position line) const noexcept {
return Levels()->GetFoldLevel(line);
}
void Document::ClearLevels() {
Levels()->ClearLevels();
}
namespace {
constexpr bool IsSubordinate(FoldLevel levelStart, FoldLevel levelTry) noexcept {
if (LevelIsWhitespace(levelTry))
return true;
return LevelNumber(levelStart) < LevelNumber(levelTry);
}
}
Sci::Line Document::GetLastChild(Sci::Line lineParent, std::optional<FoldLevel> level, Sci::Line lastLine) {
const FoldLevel levelStart = LevelNumberPart(level ? *level : GetFoldLevel(lineParent));
const Sci::Line maxLine = LinesTotal();
const Sci::Line lookLastLine = (lastLine != -1) ? std::min(LinesTotal() - 1, lastLine) : -1;
Sci::Line lineMaxSubord = lineParent;
while (lineMaxSubord < maxLine - 1) {
EnsureStyledTo(LineStart(lineMaxSubord + 2));
if (!IsSubordinate(levelStart, GetFoldLevel(lineMaxSubord + 1)))
break;
if ((lookLastLine != -1) && (lineMaxSubord >= lookLastLine) && !LevelIsWhitespace(GetFoldLevel(lineMaxSubord)))
break;
lineMaxSubord++;
}
if (lineMaxSubord > lineParent) {
if (levelStart > LevelNumberPart(GetFoldLevel(lineMaxSubord + 1))) {
// Have chewed up some whitespace that belongs to a parent so seek back
if (LevelIsWhitespace(GetFoldLevel(lineMaxSubord))) {
lineMaxSubord--;
}
}
}
return lineMaxSubord;
}
Sci::Line Document::GetFoldParent(Sci::Line line) const noexcept {
return Levels()->GetFoldParent(line);
}
void Document::GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, Sci::Line line, Sci::Line lastLine) {
const FoldLevel level = GetFoldLevel(line);
const Sci::Line lookLastLine = std::max(line, lastLine) + 1;
Sci::Line lookLine = line;
FoldLevel lookLineLevel = level;
FoldLevel lookLineLevelNum = LevelNumberPart(lookLineLevel);
while ((lookLine > 0) && (LevelIsWhitespace(lookLineLevel) ||
(LevelIsHeader(lookLineLevel) && (lookLineLevelNum >= LevelNumberPart(GetFoldLevel(lookLine + 1)))))) {
lookLineLevel = GetFoldLevel(--lookLine);
lookLineLevelNum = LevelNumberPart(lookLineLevel);
}
Sci::Line beginFoldBlock = LevelIsHeader(lookLineLevel) ? lookLine : GetFoldParent(lookLine);
if (beginFoldBlock == -1) {
highlightDelimiter.Clear();
return;
}
Sci::Line endFoldBlock = GetLastChild(beginFoldBlock, {}, lookLastLine);
Sci::Line firstChangeableLineBefore = -1;
if (endFoldBlock < line) {
lookLine = beginFoldBlock - 1;
lookLineLevel = GetFoldLevel(lookLine);
lookLineLevelNum = LevelNumberPart(lookLineLevel);
while ((lookLine >= 0) && (lookLineLevelNum >= FoldLevel::Base)) {
if (LevelIsHeader(lookLineLevel)) {
if (GetLastChild(lookLine, {}, lookLastLine) == line) {
beginFoldBlock = lookLine;
endFoldBlock = line;
firstChangeableLineBefore = line - 1;
}
}
if ((lookLine > 0) && (lookLineLevelNum == FoldLevel::Base) && (LevelNumberPart(GetFoldLevel(lookLine - 1)) > lookLineLevelNum))
break;
lookLineLevel = GetFoldLevel(--lookLine);
lookLineLevelNum = LevelNumberPart(lookLineLevel);
}
}
if (firstChangeableLineBefore == -1) {
for (lookLine = line - 1, lookLineLevel = GetFoldLevel(lookLine), lookLineLevelNum = LevelNumberPart(lookLineLevel);
lookLine >= beginFoldBlock;
lookLineLevel = GetFoldLevel(--lookLine), lookLineLevelNum = LevelNumberPart(lookLineLevel)) {
if (LevelIsWhitespace(lookLineLevel) || (lookLineLevelNum > LevelNumberPart(level))) {
firstChangeableLineBefore = lookLine;
break;
}
}
}
if (firstChangeableLineBefore == -1)
firstChangeableLineBefore = beginFoldBlock - 1;
Sci::Line firstChangeableLineAfter = -1;
for (lookLine = line + 1, lookLineLevel = GetFoldLevel(lookLine), lookLineLevelNum = LevelNumberPart(lookLineLevel);
lookLine <= endFoldBlock;
lookLineLevel = GetFoldLevel(++lookLine), lookLineLevelNum = LevelNumberPart(lookLineLevel)) {
if (LevelIsHeader(lookLineLevel) && (lookLineLevelNum < LevelNumberPart(GetFoldLevel(lookLine + 1)))) {
firstChangeableLineAfter = lookLine;
break;
}
}
if (firstChangeableLineAfter == -1)
firstChangeableLineAfter = endFoldBlock + 1;
highlightDelimiter.beginFoldBlock = beginFoldBlock;
highlightDelimiter.endFoldBlock = endFoldBlock;
highlightDelimiter.firstChangeableLineBefore = firstChangeableLineBefore;
highlightDelimiter.firstChangeableLineAfter = firstChangeableLineAfter;
}
Sci::Position Document::ClampPositionIntoDocument(Sci::Position pos) const noexcept {
return std::clamp<Sci::Position>(pos, 0, LengthNoExcept());
}
bool Document::IsCrLf(Sci::Position pos) const noexcept {
if (pos < 0)
return false;
if (pos >= (LengthNoExcept() - 1))
return false;
return (cb.CharAt(pos) == '\r') && (cb.CharAt(pos + 1) == '\n');
}
int Document::LenChar(Sci::Position pos) const noexcept {
if (pos < 0 || pos >= LengthNoExcept()) {
// Returning 1 instead of 0 to defend against hanging with a loop that goes (or starts) out of bounds.
return 1;
} else if (IsCrLf(pos)) {
return 2;
}
const unsigned char leadByte = cb.UCharAt(pos);
if (!dbcsCodePage || UTF8IsAscii(leadByte)) {
// Common case: ASCII character
return 1;
}
if (CpUtf8 == dbcsCodePage) {
const int widthCharBytes = UTF8BytesOfLead[leadByte];
unsigned char charBytes[UTF8MaxBytes] = { leadByte, 0, 0, 0 };
for (int b = 1; b < widthCharBytes; b++) {
charBytes[b] = cb.UCharAt(pos + b);
}
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid) {
// Treat as invalid and use up just one byte
return 1;
} else {
return utf8status & UTF8MaskWidth;
}
} else {
if (IsDBCSLeadByteNoExcept(leadByte) && IsDBCSTrailByteNoExcept(cb.CharAt(pos + 1))) {
return 2;
} else {
return 1;
}
}
}
bool Document::InGoodUTF8(Sci::Position pos, Sci::Position &start, Sci::Position &end) const noexcept {
Sci::Position trail = pos;
while ((trail>0) && (pos-trail < UTF8MaxBytes) && UTF8IsTrailByte(cb.UCharAt(trail-1)))
trail--;
start = (trail > 0) ? trail-1 : trail;
const unsigned char leadByte = cb.UCharAt(start);
const int widthCharBytes = UTF8BytesOfLead[leadByte];
if (widthCharBytes == 1) {
return false;
} else {
const int trailBytes = widthCharBytes - 1;
const Sci::Position len = pos - start;
if (len > trailBytes)
// pos too far from lead
return false;
unsigned char charBytes[UTF8MaxBytes] = {leadByte,0,0,0};
for (Sci::Position b=1; b<widthCharBytes && ((start+b) < cb.Length()); b++)
charBytes[b] = cb.CharAt(start+b);
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid)
return false;
end = start + widthCharBytes;
return true;
}
}
// Normalise a position so that it is not part way through a multi-byte character.
// This can occur in two situations -
// When lines are terminated with \r\n pairs which should be treated as one character.
// When displaying DBCS text such as Japanese.
// If moving, move the position in the indicated direction.
Sci::Position Document::MovePositionOutsideChar(Sci::Position pos, Sci::Position moveDir, bool checkLineEnd) const noexcept {
//Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir);
// If out of range, just return minimum/maximum value.
if (pos <= 0)
return 0;
if (pos >= LengthNoExcept())
return LengthNoExcept();
// PLATFORM_ASSERT(pos > 0 && pos < LengthNoExcept());
if (checkLineEnd && IsCrLf(pos - 1)) {
if (moveDir > 0)
return pos + 1;
else
return pos - 1;
}
if (dbcsCodePage) {
if (CpUtf8 == dbcsCodePage) {
const unsigned char ch = cb.UCharAt(pos);
// If ch is not a trail byte then pos is valid intercharacter position
if (UTF8IsTrailByte(ch)) {
Sci::Position startUTF = pos;
Sci::Position endUTF = pos;
if (InGoodUTF8(pos, startUTF, endUTF)) {
// ch is a trail byte within a UTF-8 character
if (moveDir > 0)
pos = endUTF;
else
pos = startUTF;
}
// Else invalid UTF-8 so return position of isolated trail byte
}
} else {
// Step back until a non-lead-byte is found.
Sci::Position posCheck = pos;
while ((posCheck > 0) && IsDBCSLeadByteNoExcept(cb.CharAt(posCheck-1)))
posCheck--;
// Check from known start of character.
while (posCheck < pos) {
const int mbsize = IsDBCSDualByteAt(posCheck) ? 2 : 1;
if (posCheck + mbsize == pos) {
return pos;
} else if (posCheck + mbsize > pos) {
if (moveDir > 0) {
return posCheck + mbsize;
} else {
return posCheck;
}
}
posCheck += mbsize;
}
}
}
return pos;
}
// NextPosition moves between valid positions - it can not handle a position in the middle of a
// multi-byte character. It is used to iterate through text more efficiently than MovePositionOutsideChar.
// A \r\n pair is treated as two characters.
Sci::Position Document::NextPosition(Sci::Position pos, int moveDir) const noexcept {
// If out of range, just return minimum/maximum value.
const int increment = (moveDir > 0) ? 1 : -1;
if (pos + increment <= 0)
return 0;
if (pos + increment >= cb.Length())
return cb.Length();
if (dbcsCodePage) {
if (CpUtf8 == dbcsCodePage) {
if (increment == 1) {
// Simple forward movement case so can avoid some checks
const unsigned char leadByte = cb.UCharAt(pos);
if (UTF8IsAscii(leadByte)) {
// Single byte character or invalid
pos++;
} else {
const int widthCharBytes = UTF8BytesOfLead[leadByte];
unsigned char charBytes[UTF8MaxBytes] = {leadByte,0,0,0};
for (int b=1; b<widthCharBytes; b++)
charBytes[b] = cb.CharAt(pos+b);
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid)
pos++;
else
pos += utf8status & UTF8MaskWidth;
}
} else {
// Examine byte before position
pos--;
const unsigned char ch = cb.UCharAt(pos);
// If ch is not a trail byte then pos is valid intercharacter position
if (UTF8IsTrailByte(ch)) {
// If ch is a trail byte in a valid UTF-8 character then return start of character
Sci::Position startUTF = pos;
Sci::Position endUTF = pos;
if (InGoodUTF8(pos, startUTF, endUTF)) {
pos = startUTF;
}
// Else invalid UTF-8 so return position of isolated trail byte
}
}
} else {
if (moveDir > 0) {
const int mbsize = IsDBCSDualByteAt(pos) ? 2 : 1;
pos += mbsize;
if (pos > cb.Length())
pos = cb.Length();
} else {
// How to Go Backward in a DBCS String
// https://msdn.microsoft.com/en-us/library/cc194792.aspx
// DBCS-Enabled Programs vs. Non-DBCS-Enabled Programs
// https://msdn.microsoft.com/en-us/library/cc194790.aspx
if (IsDBCSLeadByteNoExcept(cb.CharAt(pos - 1))) {
// Should actually be trail byte
if (IsDBCSDualByteAt(pos - 2)) {
return pos - 2;
} else {
// Invalid byte pair so treat as one byte wide
return pos - 1;
}
} else {
// Otherwise, step back until a non-lead-byte is found.
Sci::Position posTemp = pos - 1;
while (--posTemp >= 0 && IsDBCSLeadByteNoExcept(cb.CharAt(posTemp)))
;
// Now posTemp+1 must point to the beginning of a character,
// so figure out whether we went back an even or an odd
// number of bytes and go back 1 or 2 bytes, respectively.
const Sci::Position widthLast = ((pos - posTemp) & 1) + 1;
if ((widthLast == 2) && (IsDBCSDualByteAt(pos - widthLast))) {
return pos - widthLast;
}
// Byte before pos may be valid character or may be an invalid second byte
return pos - 1;
}
}
}
} else {
pos += increment;
}
return pos;
}
bool Document::NextCharacter(Sci::Position &pos, int moveDir) const noexcept {
// Returns true if pos changed
Sci::Position posNext = NextPosition(pos, moveDir);
if (posNext == pos) {
return false;
} else {
pos = posNext;
return true;
}
}
CharacterExtracted Document::CharacterAfter(Sci::Position position) const noexcept {
if (position >= LengthNoExcept()) {
return characterEmpty;
}
const unsigned char leadByte = cb.UCharAt(position);
if (!dbcsCodePage || UTF8IsAscii(leadByte)) {
// Common case: ASCII character
return CharacterExtracted(leadByte, 1);
}
if (CpUtf8 == dbcsCodePage) {
const int widthCharBytes = UTF8BytesOfLead[leadByte];
unsigned char charBytes[UTF8MaxBytes] = { leadByte, 0, 0, 0 };
for (int b = 1; b<widthCharBytes; b++)
charBytes[b] = cb.UCharAt(position + b);
return CharacterExtracted(charBytes, widthCharBytes);
} else {
if (IsDBCSLeadByteNoExcept(leadByte)) {
const unsigned char trailByte = cb.UCharAt(position + 1);
if (IsDBCSTrailByteNoExcept(trailByte)) {
return CharacterExtracted::DBCS(leadByte, trailByte);
}
}
return CharacterExtracted(leadByte, 1);
}
}
CharacterExtracted Document::CharacterBefore(Sci::Position position) const noexcept {
if (position <= 0) {
return characterEmpty;
}
const unsigned char previousByte = cb.UCharAt(position - 1);
if (0 == dbcsCodePage) {
return CharacterExtracted(previousByte, 1);
}
if (CpUtf8 == dbcsCodePage) {
if (UTF8IsAscii(previousByte)) {
return CharacterExtracted(previousByte, 1);
}
position--;
// If previousByte is not a trail byte then its invalid
if (UTF8IsTrailByte(previousByte)) {
// If previousByte is a trail byte in a valid UTF-8 character then find start of character
Sci::Position startUTF = position;
Sci::Position endUTF = position;
if (InGoodUTF8(position, startUTF, endUTF)) {
const Sci::Position widthCharBytes = endUTF - startUTF;
unsigned char charBytes[UTF8MaxBytes] = { 0, 0, 0, 0 };
for (Sci::Position b = 0; b<widthCharBytes; b++)
charBytes[b] = cb.UCharAt(startUTF + b);
return CharacterExtracted(charBytes, widthCharBytes);
}
// Else invalid UTF-8 so return position of isolated trail byte
}
return characterBadByte;
} else {
// Moving backwards in DBCS is complex so use NextPosition
const Sci::Position posStartCharacter = NextPosition(position, -1);
return CharacterAfter(posStartCharacter);
}
}
// Return -1 on out-of-bounds
Sci_Position SCI_METHOD Document::GetRelativePosition(Sci_Position positionStart, Sci_Position characterOffset) const {
Sci::Position pos = positionStart;
if (dbcsCodePage) {
const int increment = (characterOffset > 0) ? 1 : -1;
while (characterOffset != 0) {
const Sci::Position posNext = NextPosition(pos, increment);
if (posNext == pos)
return Sci::invalidPosition;
pos = posNext;
characterOffset -= increment;
}
} else {
pos = positionStart + characterOffset;
if ((pos < 0) || (pos > Length()))
return Sci::invalidPosition;
}
return pos;
}
Sci::Position Document::GetRelativePositionUTF16(Sci::Position positionStart, Sci::Position characterOffset) const noexcept {
Sci::Position pos = positionStart;
if (dbcsCodePage) {
const int increment = (characterOffset > 0) ? 1 : -1;
while (characterOffset != 0) {
const Sci::Position posNext = NextPosition(pos, increment);
if (posNext == pos)
return Sci::invalidPosition;
if (std::abs(pos-posNext) > 3) // 4 byte character = 2*UTF16.
characterOffset -= increment;
pos = posNext;
characterOffset -= increment;
}
} else {
pos = positionStart + characterOffset;
if ((pos < 0) || (pos > LengthNoExcept()))
return Sci::invalidPosition;
}
return pos;
}
int SCI_METHOD Document::GetCharacterAndWidth(Sci_Position position, Sci_Position *pWidth) const {
int bytesInCharacter = 1;
const unsigned char leadByte = cb.UCharAt(position);
int character = leadByte;
if (dbcsCodePage && !UTF8IsAscii(leadByte)) {
if (CpUtf8 == dbcsCodePage) {
const int widthCharBytes = UTF8BytesOfLead[leadByte];
unsigned char charBytes[UTF8MaxBytes] = {leadByte,0,0,0};
for (int b=1; b<widthCharBytes; b++)
charBytes[b] = cb.UCharAt(position+b);
const int utf8status = UTF8Classify(charBytes, widthCharBytes);
if (utf8status & UTF8MaskInvalid) {
// Report as singleton surrogate values which are invalid Unicode
character = 0xDC80 + leadByte;
} else {
bytesInCharacter = utf8status & UTF8MaskWidth;
character = UnicodeFromUTF8(charBytes);
}
} else {
if (IsDBCSLeadByteNoExcept(leadByte)) {
const unsigned char trailByte = cb.UCharAt(position + 1);
if (IsDBCSTrailByteNoExcept(trailByte)) {
bytesInCharacter = 2;
character = (leadByte << 8) | trailByte;
}
}
}
}
if (pWidth) {
*pWidth = bytesInCharacter;
}
return character;
}
int SCI_METHOD Document::CodePage() const {
return dbcsCodePage;
}
bool SCI_METHOD Document::IsDBCSLeadByte(char ch) const {
// Used by lexers so must match IDocument method exactly
return IsDBCSLeadByteNoExcept(ch);
}
// Silence 'magic' number use since the set of DBCS lead and trail bytes differ
// between encodings and would require many constant declarations that would just
// obscure the behaviour.
// NOLINTBEGIN(*-magic-numbers)
bool Document::IsDBCSLeadByteNoExcept(char ch) const noexcept {
// Used inside core Scintilla
// Byte ranges found in Wikipedia articles with relevant search strings in each case
const unsigned char uch = ch;
switch (dbcsCodePage) {
case 932:
// Shift_jis
return ((uch >= 0x81) && (uch <= 0x9F)) ||
((uch >= 0xE0) && (uch <= 0xFC));
// Lead bytes F0 to FC may be a Microsoft addition.
case 936:
// GBK
return (uch >= 0x81) && (uch <= 0xFE);
case 949:
// Korean Wansung KS C-5601-1987
return (uch >= 0x81) && (uch <= 0xFE);
case 950:
// Big5
return (uch >= 0x81) && (uch <= 0xFE);
case 1361:
// Korean Johab KS C-5601-1992
return
((uch >= 0x84) && (uch <= 0xD3)) ||
((uch >= 0xD8) && (uch <= 0xDE)) ||
((uch >= 0xE0) && (uch <= 0xF9));
}
return false;
}
bool Document::IsDBCSTrailByteNoExcept(char ch) const noexcept {
const unsigned char trail = ch;
switch (dbcsCodePage) {
case 932:
// Shift_jis
return (trail != 0x7F) &&
((trail >= 0x40) && (trail <= 0xFC));
case 936:
// GBK
return (trail != 0x7F) &&
((trail >= 0x40) && (trail <= 0xFE));
case 949:
// Korean Wansung KS C-5601-1987
return
((trail >= 0x41) && (trail <= 0x5A)) ||
((trail >= 0x61) && (trail <= 0x7A)) ||
((trail >= 0x81) && (trail <= 0xFE));
case 950:
// Big5
return
((trail >= 0x40) && (trail <= 0x7E)) ||
((trail >= 0xA1) && (trail <= 0xFE));
case 1361:
// Korean Johab KS C-5601-1992
return
((trail >= 0x31) && (trail <= 0x7E)) ||
((trail >= 0x81) && (trail <= 0xFE));
}
return false;
}
unsigned char Document::DBCSMinTrailByte() const noexcept {
switch (dbcsCodePage) {
case 932:
// Shift_jis
return 0x40;
case 936:
// GBK
return 0x40;
case 949:
// Korean Wansung KS C-5601-1987
return 0x41;
case 950:
// Big5
return 0x40;
case 1361:
// Korean Johab KS C-5601-1992
return 0x31;
default:
// UTF-8 or single byte, should not occur as not DBCS
return 0;
}
}
// NOLINTEND(*-magic-numbers)
int Document::DBCSDrawBytes(std::string_view text) const noexcept {
if (text.length() <= 1) {
return static_cast<int>(text.length());
}
if (IsDBCSLeadByteNoExcept(text[0])) {
return IsDBCSTrailByteNoExcept(text[1]) ? 2 : 1;
} else {
return 1;
}
}
bool Document::IsDBCSDualByteAt(Sci::Position pos) const noexcept {
return IsDBCSLeadByteNoExcept(cb.CharAt(pos))
&& IsDBCSTrailByteNoExcept(cb.CharAt(pos + 1));
}
namespace {
// Remove any extra bytes after the last valid character.
void DiscardEndFragment(std::string_view &text) noexcept {
if (!text.empty()) {
if (UTF8IsFirstByte(text.back())) {
// Ending with start of character byte is invalid
text.remove_suffix(1);
} else if (UTF8IsTrailByte(text.back())) {
// go back to the start of last character.
const size_t maxTrail = std::max<size_t>(UTF8MaxBytes - 1, text.length());
size_t trail = 1;
while (trail < maxTrail && UTF8IsTrailByte(text[text.length() - trail])) {
trail++;
}
const std::string_view endPortion = text.substr(text.length() - trail);
if (!UTF8IsValid(endPortion)) {
text.remove_suffix(trail);
}
}
}
}
constexpr bool IsBaseOfGrapheme(CharacterCategory cc) {
switch (cc) {
// \p{L}\p{N}\p{P}\p{Sm}\p{Sc}\p{So}\p{Zs}
case ccLu:
case ccLl:
case ccLt:
case ccLm:
case ccLo:
case ccNd:
case ccNl:
case ccNo:
case ccPc:
case ccPd:
case ccPs:
case ccPe:
case ccPi:
case ccPf:
case ccPo:
case ccSm:
case ccSc:
case ccSo:
case ccZs:
// Control
case ccCc:
case ccCs:
case ccCo:
return true;
default:
// ccMn, ccMc, ccMe,
// ccSk,
// ccZl, ccZp,
// ccCf, ccCn
return false;
}
}
CharacterExtracted LastCharacter(std::string_view text) noexcept {
if (text.empty())
return characterEmpty;
const size_t length = text.length();
size_t trail = length;
while ((trail > 0) && (length - trail < UTF8MaxBytes) && UTF8IsTrailByte(text[trail - 1]))
trail--;
const size_t start = (trail > 0) ? trail - 1 : trail;
const int utf8status = UTF8Classify(text.substr(start));
if (utf8status & UTF8MaskInvalid) {
return characterBadByte;
}
return { static_cast<unsigned int>(UnicodeFromUTF8(text.substr(start))),
static_cast<unsigned int>(utf8status & UTF8MaskWidth) };
}
constexpr Sci::Position NextTab(Sci::Position pos, Sci::Position tabSize) noexcept {
return ((pos / tabSize) + 1) * tabSize;
}
std::string CreateIndentation(Sci::Position indent, int tabSize, bool insertSpaces) {
std::string indentation;
if (!insertSpaces) {
while (indent >= tabSize) {
indentation += '\t';
indent -= tabSize;
}
}
while (indent > 0) {
indentation += ' ';
indent--;
}
return indentation;
}
}
bool Scintilla::Internal::DiscardLastCombinedCharacter(std::string_view &text) noexcept {
// Handle the simple common case where a base character may be followed by
// accents and similar marks by discarding until start of base character.
//
// From Grapheme_Cluster_Boundaries
// combining character sequence = ccs-base? ccs-extend+
// ccs-base := [\p{L}\p{N}\p{P}\p{S}\p{Zs}]
// ccs-extend := [\p{M}\p{Join_Control}]
// Modified to move Sk (Symbol Modifier) from ccs-base to ccs-extend to preserve modified emoji
// May break before and after Control which is defined as most of ccC? but not some of ccCf and ccCn
// so treat ccCc, ccCs, ccCo as base for now.
std::string_view truncated = text;
while (truncated.length() > UTF8MaxBytes) {
// Give up when short
const CharacterExtracted ce = LastCharacter(truncated);
const CharacterCategory cc = CategoriseCharacter(static_cast<int>(ce.character));
truncated.remove_suffix(ce.widthBytes);
if (IsBaseOfGrapheme(cc)) {
text = truncated;
return true;
}
}
// No base character found so just leave as is
return false;
}
// Need to break text into segments near end but taking into account the
// encoding to not break inside a UTF-8 or DBCS character and also trying
// to avoid breaking inside a pair of combining characters, or inside
// ligatures.
// TODO: implement grapheme cluster boundaries,
// see https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries.
//
// The segment length must always be long enough (more than 4 bytes)
// so that there will be at least one whole character to make a segment.
// For UTF-8, text must consist only of valid whole characters.
// In preference order from best to worst:
// 1) Break before or after spaces or controls
// 2) Break at word and punctuation boundary for better kerning and ligature support
// 3) Break before letter in UTF-8 to avoid breaking combining characters
// 4) Break after whole character, this may break combining characters
size_t Document::SafeSegment(std::string_view text) const noexcept {
// check space first as most written language use spaces.
for (std::string_view::iterator it = text.end() - 1; it != text.begin(); --it) {
if (IsBreakSpace(*it)) {
return it - text.begin();
}
}
if (!dbcsCodePage || dbcsCodePage == CpUtf8) {
if (dbcsCodePage) {
// UTF-8
DiscardEndFragment(text);
if (DiscardLastCombinedCharacter(text)) {
return text.length();
}
}
// backward iterate for UTF-8 and single byte encoding to find word and punctuation boundary.
std::string_view::iterator it = text.end() - 1;
const bool punctuation = IsPunctuation(*it);
do {
--it;
if (punctuation != IsPunctuation(*it)) {
return it - text.begin() + 1;
}
} while (it != text.begin());
return text.length() - 1;
}
{
// forward iterate for DBCS to find word and punctuation boundary.
size_t lastPunctuationBreak = 0;
size_t lastEncodingAllowedBreak = 0;
CharacterClass ccPrev = CharacterClass::space;
for (size_t j = 0; j < text.length();) {
const unsigned char ch = text[j];
lastEncodingAllowedBreak = j++;
CharacterClass cc = CharacterClass::word;
if (UTF8IsAscii(ch)) {
if (IsPunctuation(ch)) {
cc = CharacterClass::punctuation;
}
} else {
j += IsDBCSLeadByteNoExcept(ch);
}
if (cc != ccPrev) {
ccPrev = cc;
lastPunctuationBreak = lastEncodingAllowedBreak;
}
}
return lastPunctuationBreak ? lastPunctuationBreak : lastEncodingAllowedBreak;
}
}
EncodingFamily Document::CodePageFamily() const noexcept {
if (CpUtf8 == dbcsCodePage)
return EncodingFamily::unicode;
else if (dbcsCodePage)
return EncodingFamily::dbcs;
else
return EncodingFamily::eightBit;
}
void Document::ModifiedAt(Sci::Position pos) noexcept {
if (endStyled > pos)
endStyled = pos;
}
void Document::CheckReadOnly() {
if (cb.IsReadOnly() && enteredReadOnlyCount == 0) {
enteredReadOnlyCount++;
NotifyModifyAttempt();
enteredReadOnlyCount--;
}
}
void Document::TrimReplacement(std::string_view &text, Range &range) const noexcept {
while (!text.empty() && !range.Empty() && (text.front() == CharAt(range.start))) {
text.remove_prefix(1);
range.start++;
}
while (!text.empty() && !range.Empty() && (text.back() == CharAt(range.end-1))) {
text.remove_suffix(1);
range.end--;
}
}
// Document only modified by gateways DeleteChars, InsertString, Undo, Redo, and SetStyleAt.
// SetStyleAt does not change the persistent state of a document
bool Document::DeleteChars(Sci::Position pos, Sci::Position len) {
if (pos < 0)
return false;
if (len <= 0)
return false;
if ((pos + len) > LengthNoExcept())
return false;
CheckReadOnly();
if (enteredModification != 0) {
return false;
} else {
enteredModification++;
if (!cb.IsReadOnly()) {
if (cb.IsCollectingUndo() && cb.CanRedo()) {
// Abandoning some undo actions so truncate any later selections
TruncateUndoComments(cb.UndoCurrent());
}
NotifyModified(
DocModification(
ModificationFlags::BeforeDelete | ModificationFlags::User,
pos, len,
0, nullptr));
const Sci::Line prevLinesTotal = LinesTotal();
const bool startSavePoint = cb.IsSavePoint();
bool startSequence = false;
const char *text = cb.DeleteChars(pos, len, startSequence);
if (startSavePoint && cb.IsCollectingUndo())
NotifySavePoint(false);
if ((pos < LengthNoExcept()) || (pos == 0))
ModifiedAt(pos);
else
ModifiedAt(pos-1);
NotifyModified(
DocModification(
ModificationFlags::DeleteText | ModificationFlags::User |
(startSequence?ModificationFlags::StartAction:ModificationFlags::None),
pos, len,
LinesTotal() - prevLinesTotal, text));
}
enteredModification--;
}
return !cb.IsReadOnly();
}
/**
* Insert a string with a length.
*/
Sci::Position Document::InsertString(Sci::Position position, const char *s, Sci::Position insertLength) {
if (insertLength <= 0) {
return 0;
}
CheckReadOnly(); // Application may change read only state here
if (cb.IsReadOnly()) {
return 0;
}
if (enteredModification != 0) {
return 0;
}
enteredModification++;
insertionSet = false;
insertion.clear();
NotifyModified(
DocModification(
ModificationFlags::InsertCheck,
position, insertLength,
0, s));
if (insertionSet) {
s = insertion.c_str();
insertLength = insertion.length();
}
if (cb.IsCollectingUndo() && cb.CanRedo()) {
// Abandoning some undo actions so truncate any later selections
TruncateUndoComments(cb.UndoCurrent());
}
NotifyModified(
DocModification(
ModificationFlags::BeforeInsert | ModificationFlags::User,
position, insertLength,
0, s));
const Sci::Line prevLinesTotal = LinesTotal();
const bool startSavePoint = cb.IsSavePoint();
bool startSequence = false;
const char *text = cb.InsertString(position, s, insertLength, startSequence);
if (startSavePoint && cb.IsCollectingUndo())
NotifySavePoint(false);
ModifiedAt(position);
NotifyModified(
DocModification(
ModificationFlags::InsertText | ModificationFlags::User |
(startSequence?ModificationFlags::StartAction:ModificationFlags::None),
position, insertLength,
LinesTotal() - prevLinesTotal, text));
if (insertionSet) { // Free memory as could be large
std::string().swap(insertion);
}
enteredModification--;
return insertLength;
}
Sci::Position Document::InsertString(Sci::Position position, std::string_view sv) {
return InsertString(position, sv.data(), sv.length());
}
void Document::ChangeInsertion(const char *s, Sci::Position length) {
insertionSet = true;
insertion.assign(s, length);
}
int SCI_METHOD Document::AddData(const char *data, Sci_Position length) {
try {
const Sci::Position position = Length();
InsertString(position, data, length);
} catch (std::bad_alloc &) {
return static_cast<int>(Status::BadAlloc);
} catch (...) {
return static_cast<int>(Status::Failure);
}
return static_cast<int>(Status::Ok);
}
IDocumentEditable *Document::AsDocumentEditable() noexcept {
return static_cast<IDocumentEditable *>(this);
}
void *SCI_METHOD Document::ConvertToDocument() {
return AsDocumentEditable();
}
Sci::Position Document::Undo() {
Sci::Position newPos = -1;
CheckReadOnly();
if ((enteredModification == 0) && (cb.IsCollectingUndo())) {
enteredModification++;
if (!cb.IsReadOnly()) {
const bool startSavePoint = cb.IsSavePoint();
bool multiLine = false;
const int steps = cb.StartUndo();
//Platform::DebugPrintf("Steps=%d\n", steps);
Range coalescedRemove; // Default is empty at 0
for (int step = 0; step < steps; step++) {
const Sci::Line prevLinesTotal = LinesTotal();
const Action action = cb.GetUndoStep();
if (action.at == ActionType::remove) {
NotifyModified(DocModification(
ModificationFlags::BeforeInsert | ModificationFlags::Undo, action));
} else if (action.at == ActionType::container) {
DocModification dm(ModificationFlags::Container | ModificationFlags::Undo);
dm.token = action.position;
NotifyModified(dm);
} else {
NotifyModified(DocModification(
ModificationFlags::BeforeDelete | ModificationFlags::Undo, action));
}
cb.PerformUndoStep();
if (action.at != ActionType::container) {
ModifiedAt(action.position);
newPos = action.position;
}
ModificationFlags modFlags = ModificationFlags::Undo;
// With undo, an insertion action becomes a deletion notification
if (action.at == ActionType::remove) {
newPos += action.lenData;
modFlags |= ModificationFlags::InsertText;
if (coalescedRemove.Contains(action.position)) {
coalescedRemove.end += action.lenData;
newPos = coalescedRemove.end;
} else {
coalescedRemove = Range(action.position, action.position + action.lenData);
}
} else if (action.at == ActionType::insert) {
modFlags |= ModificationFlags::DeleteText;
coalescedRemove = Range();
}
if (steps > 1)
modFlags |= ModificationFlags::MultiStepUndoRedo;
const Sci::Line linesAdded = LinesTotal() - prevLinesTotal;
if (linesAdded != 0)
multiLine = true;
if (step == steps - 1) {
modFlags |= ModificationFlags::LastStepInUndoRedo;
if (multiLine)
modFlags |= ModificationFlags::MultilineUndoRedo;
}
NotifyModified(DocModification(modFlags, action.position, action.lenData,
linesAdded, action.data));
}
const bool endSavePoint = cb.IsSavePoint();
if (startSavePoint != endSavePoint)
NotifySavePoint(endSavePoint);
}
enteredModification--;
}
return newPos;
}
Sci::Position Document::Redo() {
Sci::Position newPos = -1;
CheckReadOnly();
if ((enteredModification == 0) && (cb.IsCollectingUndo())) {
enteredModification++;
if (!cb.IsReadOnly()) {
const bool startSavePoint = cb.IsSavePoint();
bool multiLine = false;
const int steps = cb.StartRedo();
for (int step = 0; step < steps; step++) {
const Sci::Line prevLinesTotal = LinesTotal();
const Action action = cb.GetRedoStep();
if (action.at == ActionType::insert) {
NotifyModified(DocModification(
ModificationFlags::BeforeInsert | ModificationFlags::Redo, action));
} else if (action.at == ActionType::container) {
DocModification dm(ModificationFlags::Container | ModificationFlags::Redo);
dm.token = action.position;
NotifyModified(dm);
} else {
NotifyModified(DocModification(
ModificationFlags::BeforeDelete | ModificationFlags::Redo, action));
}
cb.PerformRedoStep();
if (action.at != ActionType::container) {
ModifiedAt(action.position);
newPos = action.position;
}
ModificationFlags modFlags = ModificationFlags::Redo;
if (action.at == ActionType::insert) {
newPos += action.lenData;
modFlags |= ModificationFlags::InsertText;
} else if (action.at == ActionType::remove) {
modFlags |= ModificationFlags::DeleteText;
}
if (steps > 1)
modFlags |= ModificationFlags::MultiStepUndoRedo;
const Sci::Line linesAdded = LinesTotal() - prevLinesTotal;
if (linesAdded != 0)
multiLine = true;
if (step == steps - 1) {
modFlags |= ModificationFlags::LastStepInUndoRedo;
if (multiLine)
modFlags |= ModificationFlags::MultilineUndoRedo;
}
NotifyModified(
DocModification(modFlags, action.position, action.lenData,
linesAdded, action.data));
}
const bool endSavePoint = cb.IsSavePoint();
if (startSavePoint != endSavePoint)
NotifySavePoint(endSavePoint);
}
enteredModification--;
}
return newPos;
}
void Document::EndUndoAction() noexcept {
cb.EndUndoAction();
if (UndoSequenceDepth() == 0) {
// Broadcast notification to views to allow end of group processing.
// NotifyGroupCompleted may throw (for memory exhaustion) but this method
// may not as it is called in UndoGroup destructor so ignore exception.
try {
NotifyGroupCompleted();
} catch (...) {
// Ignore any exception
}
}
}
int Document::UndoSequenceDepth() const noexcept {
return cb.UndoSequenceDepth();
}
void Document::DelChar(Sci::Position pos) {
DeleteChars(pos, LenChar(pos));
}
void Document::DelCharBack(Sci::Position pos) {
if (pos <= 0) {
return;
} else if (IsCrLf(pos - 2)) {
DeleteChars(pos - 2, 2);
} else if (dbcsCodePage) {
const Sci::Position startChar = NextPosition(pos, -1);
DeleteChars(startChar, pos - startChar);
} else {
DeleteChars(pos - 1, 1);
}
}
int SCI_METHOD Document::GetLineIndentation(Sci_Position line) {
int indent = 0;
if ((line >= 0) && (line < LinesTotal())) {
const Sci::Position lineStart = LineStart(line);
const Sci::Position length = Length();
for (Sci::Position i = lineStart; i < length; i++) {
const char ch = cb.CharAt(i);
if (ch == ' ')
indent++;
else if (ch == '\t')
indent = static_cast<int>(NextTab(indent, tabInChars));
else
return indent;
}
}
return indent;
}
Sci::Position Document::SetLineIndentation(Sci::Line line, Sci::Position indent) {
const int indentOfLine = GetLineIndentation(line);
if (indent < 0)
indent = 0;
if (indent != indentOfLine) {
const std::string linebuf = CreateIndentation(indent, tabInChars, !useTabs);
const Sci::Position thisLineStart = LineStart(line);
const Sci::Position indentPos = GetLineIndentPosition(line);
UndoGroup ug(this);
DeleteChars(thisLineStart, indentPos - thisLineStart);
return thisLineStart + InsertString(thisLineStart, linebuf);
} else {
return GetLineIndentPosition(line);
}
}
Sci::Position Document::GetLineIndentPosition(Sci::Line line) const {
if (line < 0)
return 0;
Sci::Position pos = LineStart(line);
const Sci::Position length = Length();
while ((pos < length) && IsSpaceOrTab(cb.CharAt(pos))) {
pos++;
}
return pos;
}
Sci::Position Document::GetColumn(Sci::Position pos) const {
Sci::Position column = 0;
const Sci::Line line = SciLineFromPosition(pos);
if ((line >= 0) && (line < LinesTotal())) {
for (Sci::Position i = LineStart(line); i < pos;) {
const char ch = cb.CharAt(i);
if (ch == '\t') {
column = NextTab(column, tabInChars);
i++;
} else if (ch == '\r') {
return column;
} else if (ch == '\n') {
return column;
} else if (i >= Length()) {
return column;
} else if (UTF8IsAscii(ch)) {
column++;
i++;
} else {
column++;
i = NextPosition(i, 1);
}
}
}
return column;
}
Sci::Position Document::CountCharacters(Sci::Position startPos, Sci::Position endPos) const noexcept {
startPos = MovePositionOutsideChar(startPos, 1, false);
endPos = MovePositionOutsideChar(endPos, -1, false);
Sci::Position count = 0;
Sci::Position i = startPos;
while (i < endPos) {
count++;
i = NextPosition(i, 1);
}
return count;
}
Sci::Position Document::CountUTF16(Sci::Position startPos, Sci::Position endPos) const noexcept {
startPos = MovePositionOutsideChar(startPos, 1, false);
endPos = MovePositionOutsideChar(endPos, -1, false);
Sci::Position count = 0;
Sci::Position i = startPos;
while (i < endPos) {
count++;
const Sci::Position next = NextPosition(i, 1);
if ((next - i) > 3)
count++;
i = next;
}
return count;
}
Sci::Position Document::FindColumn(Sci::Line line, Sci::Position column) {
Sci::Position position = LineStart(line);
if ((line >= 0) && (line < LinesTotal())) {
Sci::Position columnCurrent = 0;
while ((columnCurrent < column) && (position < Length())) {
const char ch = cb.CharAt(position);
if (ch == '\t') {
columnCurrent = NextTab(columnCurrent, tabInChars);
if (columnCurrent > column)
return position;
position++;
} else if (ch == '\r') {
return position;
} else if (ch == '\n') {
return position;
} else {
columnCurrent++;
position = NextPosition(position, 1);
}
}
}
return position;
}
void Document::Indent(bool forwards, Sci::Line lineBottom, Sci::Line lineTop) {
// Dedent - suck white space off the front of the line to dedent by equivalent of a tab
for (Sci::Line line = lineBottom; line >= lineTop; line--) {
const Sci::Position indentOfLine = GetLineIndentation(line);
if (forwards) {
if (LineStart(line) < LineEnd(line)) {
SetLineIndentation(line, indentOfLine + IndentSize());
}
} else {
SetLineIndentation(line, indentOfLine - IndentSize());
}
}
}
namespace {
constexpr std::string_view EOLForMode(EndOfLine eolMode) noexcept {
switch (eolMode) {
case EndOfLine::CrLf:
return "\r\n";
case EndOfLine::Cr:
return "\r";
default:
return "\n";
}
}
}
// Convert line endings for a piece of text to a particular mode.
// Stop at len or when a NUL is found.
std::string Document::TransformLineEnds(const char *s, size_t len, EndOfLine eolModeWanted) {
std::string dest;
const std::string_view eol = EOLForMode(eolModeWanted);
for (size_t i = 0; (i < len) && (s[i]); i++) {
if (s[i] == '\n' || s[i] == '\r') {
dest.append(eol);
if ((s[i] == '\r') && (i+1 < len) && (s[i+1] == '\n')) {
i++;
}
} else {
dest.push_back(s[i]);
}
}
return dest;
}
void Document::ConvertLineEnds(EndOfLine eolModeSet) {
UndoGroup ug(this);
for (Sci::Position pos = 0; pos < Length(); pos++) {
const char ch = cb.CharAt(pos);
if (ch == '\r') {
if (cb.CharAt(pos + 1) == '\n') {
// CRLF
if (eolModeSet == EndOfLine::Cr) {
DeleteChars(pos + 1, 1); // Delete the LF
} else if (eolModeSet == EndOfLine::Lf) {
DeleteChars(pos, 1); // Delete the CR
} else {
pos++;
}
} else {
// CR
if (eolModeSet == EndOfLine::CrLf) {
pos += InsertString(pos + 1, "\n", 1); // Insert LF
} else if (eolModeSet == EndOfLine::Lf) {
pos += InsertString(pos, "\n", 1); // Insert LF
DeleteChars(pos, 1); // Delete CR
pos--;
}
}
} else if (ch == '\n') {
// LF
if (eolModeSet == EndOfLine::CrLf) {
pos += InsertString(pos, "\r", 1); // Insert CR
} else if (eolModeSet == EndOfLine::Cr) {
pos += InsertString(pos, "\r", 1); // Insert CR
DeleteChars(pos, 1); // Delete LF
pos--;
}
}
}
}
std::string_view Document::EOLString() const noexcept {
return EOLForMode(eolMode);
}
DocumentOption Document::Options() const noexcept {
return (IsLarge() ? DocumentOption::TextLarge : DocumentOption::Default) |
(cb.HasStyles() ? DocumentOption::Default : DocumentOption::StylesNone);
}
bool Document::IsWhiteLine(Sci::Line line) const {
Sci::Position currentChar = LineStart(line);
const Sci::Position endLine = LineEnd(line);
while (currentChar < endLine) {
if (!IsSpaceOrTab(cb.CharAt(currentChar))) {
return false;
}
++currentChar;
}
return true;
}
Sci::Position Document::ParaUp(Sci::Position pos) const {
Sci::Line line = SciLineFromPosition(pos);
const Sci::Position start = LineStart(line);
if (pos == start) {
line--;
}
while (line >= 0 && IsWhiteLine(line)) { // skip empty lines
line--;
}
while (line >= 0 && !IsWhiteLine(line)) { // skip non-empty lines
line--;
}
line++;
return LineStart(line);
}
Sci::Position Document::ParaDown(Sci::Position pos) const {
Sci::Line line = SciLineFromPosition(pos);
while (line < LinesTotal() && !IsWhiteLine(line)) { // skip non-empty lines
line++;
}
while (line < LinesTotal() && IsWhiteLine(line)) { // skip empty lines
line++;
}
if (line < LinesTotal())
return LineStart(line);
else // end of a document
return LineEnd(line-1);
}
CharacterClass Document::WordCharacterClass(unsigned int ch) const {
if (dbcsCodePage && (ch >= 0x80)) {
if (CpUtf8 == dbcsCodePage) {
// Use hard coded Unicode class
const CharacterCategory cc = charMap.CategoryFor(ch);
switch (cc) {
// Separator, Line/Paragraph
case ccZl:
case ccZp:
return CharacterClass::newLine;
// Separator, Space
case ccZs:
// Other
case ccCc:
case ccCf:
case ccCs:
case ccCo:
case ccCn:
return CharacterClass::space;
// Letter
case ccLu:
case ccLl:
case ccLt:
case ccLm:
case ccLo:
// Number
case ccNd:
case ccNl:
case ccNo:
// Mark - includes combining diacritics
case ccMn:
case ccMc:
case ccMe:
return CharacterClass::word;
// Punctuation
case ccPc:
case ccPd:
case ccPs:
case ccPe:
case ccPi:
case ccPf:
case ccPo:
// Symbol
case ccSm:
case ccSc:
case ccSk:
case ccSo:
return CharacterClass::punctuation;
}
} else {
// Asian DBCS
return CharacterClass::word;
}
}
return charClass.GetClass(static_cast<unsigned char>(ch));
}
/**
* Used by commands that want to select whole words.
* Finds the start of word at pos when delta < 0 or the end of the word when delta >= 0.
*/
Sci::Position Document::ExtendWordSelect(Sci::Position pos, int delta, bool onlyWordCharacters) const {
CharacterClass ccStart = CharacterClass::word;
if (delta < 0) {
if (!onlyWordCharacters) {
const CharacterExtracted ce = CharacterBefore(pos);
ccStart = WordCharacterClass(ce.character);
}
while (pos > 0) {
const CharacterExtracted ce = CharacterBefore(pos);
if (WordCharacterClass(ce.character) != ccStart)
break;
pos -= ce.widthBytes;
}
} else {
if (!onlyWordCharacters && pos < LengthNoExcept()) {
const CharacterExtracted ce = CharacterAfter(pos);
ccStart = WordCharacterClass(ce.character);
}
while (pos < LengthNoExcept()) {
const CharacterExtracted ce = CharacterAfter(pos);
if (WordCharacterClass(ce.character) != ccStart)
break;
pos += ce.widthBytes;
}
}
return MovePositionOutsideChar(pos, delta, true);
}
/**
* Find the start of the next word in either a forward (delta >= 0) or backwards direction
* (delta < 0).
* This is looking for a transition between character classes although there is also some
* additional movement to transit white space.
* Used by cursor movement by word commands.
*/
Sci::Position Document::NextWordStart(Sci::Position pos, int delta) const {
if (delta < 0) {
while (pos > 0) {
const CharacterExtracted ce = CharacterBefore(pos);
if (WordCharacterClass(ce.character) != CharacterClass::space)
break;
pos -= ce.widthBytes;
}
if (pos > 0) {
CharacterExtracted ce = CharacterBefore(pos);
const CharacterClass ccStart = WordCharacterClass(ce.character);
while (pos > 0) {
ce = CharacterBefore(pos);
if (WordCharacterClass(ce.character) != ccStart)
break;
pos -= ce.widthBytes;
}
}
} else {
CharacterExtracted ce = CharacterAfter(pos);
const CharacterClass ccStart = WordCharacterClass(ce.character);
while (pos < LengthNoExcept()) {
ce = CharacterAfter(pos);
if (WordCharacterClass(ce.character) != ccStart)
break;
pos += ce.widthBytes;
}
while (pos < LengthNoExcept()) {
ce = CharacterAfter(pos);
if (WordCharacterClass(ce.character) != CharacterClass::space)
break;
pos += ce.widthBytes;
}
}
return pos;
}
/**
* Find the end of the next word in either a forward (delta >= 0) or backwards direction
* (delta < 0).
* This is looking for a transition between character classes although there is also some
* additional movement to transit white space.
* Used by cursor movement by word commands.
*/
Sci::Position Document::NextWordEnd(Sci::Position pos, int delta) const {
if (delta < 0) {
if (pos > 0) {
CharacterExtracted ce = CharacterBefore(pos);
const CharacterClass ccStart = WordCharacterClass(ce.character);
if (ccStart != CharacterClass::space) {
while (pos > 0) {
ce = CharacterBefore(pos);
if (WordCharacterClass(ce.character) != ccStart)
break;
pos -= ce.widthBytes;
}
}
while (pos > 0) {
ce = CharacterBefore(pos);
if (WordCharacterClass(ce.character) != CharacterClass::space)
break;
pos -= ce.widthBytes;
}
}
} else {
while (pos < LengthNoExcept()) {
const CharacterExtracted ce = CharacterAfter(pos);
if (WordCharacterClass(ce.character) != CharacterClass::space)
break;
pos += ce.widthBytes;
}
if (pos < LengthNoExcept()) {
CharacterExtracted ce = CharacterAfter(pos);
const CharacterClass ccStart = WordCharacterClass(ce.character);
while (pos < LengthNoExcept()) {
ce = CharacterAfter(pos);
if (WordCharacterClass(ce.character) != ccStart)
break;
pos += ce.widthBytes;
}
}
}
return pos;
}
namespace {
constexpr bool IsWordEdge(CharacterClass cc, CharacterClass ccNext) noexcept {
return (cc != ccNext) &&
(cc == CharacterClass::word || cc == CharacterClass::punctuation);
}
}
/**
* Check that the character at the given position is a word or punctuation character and that
* the previous character is of a different character class.
*/
bool Document::IsWordStartAt(Sci::Position pos) const {
if (pos >= LengthNoExcept())
return false;
if (pos >= 0) {
const CharacterExtracted cePos = CharacterAfter(pos);
// At start of document, treat as if space before so can be word start
const CharacterExtracted cePrev = (pos > 0) ?
CharacterBefore(pos) : CharacterExtracted(' ', 1);
return IsWordEdge(WordCharacterClass(cePos.character), WordCharacterClass(cePrev.character));
}
return true;
}
/**
* Check that the character before the given position is a word or punctuation character and that
* the next character is of a different character class.
*/
bool Document::IsWordEndAt(Sci::Position pos) const {
if (pos <= 0)
return false;
if (pos <= LengthNoExcept()) {
// At end of document, treat as if space after so can be word end
const CharacterExtracted cePos = (pos < LengthNoExcept()) ?
CharacterAfter(pos) : CharacterExtracted(' ', 1);
const CharacterExtracted cePrev = CharacterBefore(pos);
return IsWordEdge(WordCharacterClass(cePrev.character), WordCharacterClass(cePos.character));
}
return true;
}
/**
* Check that the given range is has transitions between character classes at both
* ends and where the characters on the inside are word or punctuation characters.
*/
bool Document::IsWordAt(Sci::Position start, Sci::Position end) const {
return (start < end) && IsWordStartAt(start) && IsWordEndAt(end);
}
bool Document::MatchesWordOptions(bool word, bool wordStart, Sci::Position pos, Sci::Position length) const {
return (!word && !wordStart) ||
(word && IsWordAt(pos, pos + length)) ||
(wordStart && IsWordStartAt(pos));
}
bool Document::HasCaseFolder() const noexcept {
return pcf != nullptr;
}
void Document::SetCaseFolder(std::unique_ptr<CaseFolder> pcf_) noexcept {
pcf = std::move(pcf_);
}
CharacterExtracted Document::ExtractCharacter(Sci::Position position) const noexcept {
const unsigned char leadByte = cb.UCharAt(position);
if (UTF8IsAscii(leadByte)) {
// Common case: ASCII character
return CharacterExtracted(leadByte, 1);
}
const int widthCharBytes = UTF8BytesOfLead[leadByte];
unsigned char charBytes[UTF8MaxBytes] = { leadByte, 0, 0, 0 };
for (int b=1; b<widthCharBytes; b++)
charBytes[b] = cb.UCharAt(position + b);
return CharacterExtracted(charBytes, widthCharBytes);
}
namespace {
// Equivalent of memchr over the split view
ptrdiff_t SplitFindChar(const SplitView &view, size_t start, size_t length, int ch) noexcept {
size_t range1Length = 0;
if (start < view.length1) {
range1Length = std::min(length, view.length1 - start);
const char *match = static_cast<const char *>(memchr(view.segment1 + start, ch, range1Length));
if (match) {
return match - view.segment1;
}
start += range1Length;
}
const char *match2 = static_cast<const char *>(memchr(view.segment2 + start, ch, length - range1Length));
if (match2) {
return match2 - view.segment2;
}
return -1;
}
// Equivalent of memcmp over the split view
// This does not call memcmp as search texts are commonly too short to overcome the
// call overhead.
bool SplitMatch(const SplitView &view, size_t start, std::string_view text) noexcept {
for (size_t i = 0; i < text.length(); i++) {
if (view.CharAt(i + start) != text[i]) {
return false;
}
}
return true;
}
}
/**
* Find text in document, supporting both forward and backward
* searches (just pass minPos > maxPos to do a backward search)
* Has not been tested with backwards DBCS searches yet.
*/
Sci::Position Document::FindText(Sci::Position minPos, Sci::Position maxPos, const char *search,
FindOption flags, Sci::Position *length) {
if (*length <= 0)
return minPos;
const bool caseSensitive = FlagSet(flags, FindOption::MatchCase);
const bool word = FlagSet(flags, FindOption::WholeWord);
const bool wordStart = FlagSet(flags, FindOption::WordStart);
const bool regExp = FlagSet(flags, FindOption::RegExp);
if (regExp) {
if (!regex)
regex = std::unique_ptr<RegexSearchBase>(CreateRegexSearch(&charClass));
return regex->FindText(this, minPos, maxPos, search, caseSensitive, word, wordStart, flags, length);
} else {
const bool forward = minPos <= maxPos;
const int increment = forward ? 1 : -1;
// Range endpoints should not be inside DBCS characters, but just in case, move them.
const Sci::Position startPos = MovePositionOutsideChar(minPos, increment, false);
const Sci::Position endPos = MovePositionOutsideChar(maxPos, increment, false);
// Compute actual search ranges needed
const Sci::Position lengthFind = *length;
//Platform::DebugPrintf("Find %d %d %s %d\n", startPos, endPos, ft->lpstrText, lengthFind);
const Sci::Position limitPos = std::max(startPos, endPos);
Sci::Position pos = startPos;
if (!forward) {
// Back all of a character
pos = NextPosition(pos, increment);
}
const SplitView cbView = cb.AllView();
if (caseSensitive) {
const Sci::Position endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : endPos;
const unsigned char charStartSearch = search[0];
if (forward && ((0 == dbcsCodePage) || (CpUtf8 == dbcsCodePage && !UTF8IsTrailByte(charStartSearch)))) {
// This is a fast case where there is no need to test byte values to iterate
// so becomes the equivalent of a memchr+memcmp loop.
// UTF-8 search will not be self-synchronizing when starts with trail byte
const std::string_view suffix(search + 1, lengthFind - 1);
while (pos < endSearch) {
pos = SplitFindChar(cbView, pos, limitPos - pos, charStartSearch);
if (pos < 0) {
break;
}
if (SplitMatch(cbView, pos + 1, suffix) && MatchesWordOptions(word, wordStart, pos, lengthFind)) {
return pos;
}
pos++;
}
} else {
while (forward ? (pos < endSearch) : (pos >= endSearch)) {
const unsigned char leadByte = cbView.CharAt(pos);
if (leadByte == charStartSearch) {
bool found = (pos + lengthFind) <= limitPos;
// SplitMatch could be called here but it is slower with g++ -O2
for (int indexSearch = 1; (indexSearch < lengthFind) && found; indexSearch++) {
found = cbView.CharAt(pos + indexSearch) == search[indexSearch];
}
if (found && MatchesWordOptions(word, wordStart, pos, lengthFind)) {
return pos;
}
}
if (forward && UTF8IsAscii(leadByte)) {
pos++;
} else {
if (dbcsCodePage) {
if (!NextCharacter(pos, increment)) {
break;
}
} else {
pos += increment;
}
}
}
}
} else if (CpUtf8 == dbcsCodePage) {
constexpr size_t maxFoldingExpansion = 4;
std::vector<char> searchThing((lengthFind+1) * UTF8MaxBytes * maxFoldingExpansion + 1);
const size_t lenSearch =
pcf->Fold(searchThing.data(), searchThing.size(), search, lengthFind);
while (forward ? (pos < endPos) : (pos >= endPos)) {
int widthFirstCharacter = 1;
Sci::Position posIndexDocument = pos;
size_t indexSearch = 0;
bool characterMatches = true;
while (indexSearch < lenSearch) {
const unsigned char leadByte = cbView.CharAt(posIndexDocument);
int widthChar = 1;
size_t lenFlat = 1;
if (UTF8IsAscii(leadByte)) {
if ((posIndexDocument + 1) > limitPos) {
break;
}
characterMatches = searchThing[indexSearch] == MakeLowerCase(leadByte);
} else {
char bytes[UTF8MaxBytes]{ static_cast<char>(leadByte) };
const int widthCharBytes = UTF8BytesOfLead[leadByte];
for (int b = 1; b < widthCharBytes; b++) {
bytes[b] = cbView.CharAt(posIndexDocument + b);
}
widthChar = UTF8Classify(bytes, widthCharBytes) & UTF8MaskWidth;
if (!indexSearch) { // First character
widthFirstCharacter = widthChar;
}
if ((posIndexDocument + widthChar) > limitPos) {
break;
}
char folded[UTF8MaxBytes * maxFoldingExpansion + 1];
lenFlat = pcf->Fold(folded, sizeof(folded), bytes, widthChar);
// memcmp may examine lenFlat bytes in both arguments so assert it doesn't read past end of searchThing
assert((indexSearch + lenFlat) <= searchThing.size());
// Does folded match the buffer
characterMatches = 0 == memcmp(folded, searchThing.data() + indexSearch, lenFlat);
}
if (!characterMatches) {
break;
}
posIndexDocument += widthChar;
indexSearch += lenFlat;
}
if (characterMatches && (indexSearch == lenSearch)) {
if (MatchesWordOptions(word, wordStart, pos, posIndexDocument - pos)) {
*length = posIndexDocument - pos;
return pos;
}
}
if (forward) {
pos += widthFirstCharacter;
} else {
if (!NextCharacter(pos, increment)) {
break;
}
}
}
} else if (dbcsCodePage) {
constexpr size_t maxBytesCharacter = 2;
constexpr size_t maxFoldingExpansion = 4;
std::vector<char> searchThing((lengthFind+1) * maxBytesCharacter * maxFoldingExpansion + 1);
const size_t lenSearch = pcf->Fold(searchThing.data(), searchThing.size(), search, lengthFind);
while (forward ? (pos < endPos) : (pos >= endPos)) {
int widthFirstCharacter = 0;
Sci::Position indexDocument = 0;
size_t indexSearch = 0;
bool characterMatches = true;
while (((pos + indexDocument) < limitPos) &&
(indexSearch < lenSearch)) {
const unsigned char leadByte = cbView.CharAt(pos + indexDocument);
const int widthChar = (!UTF8IsAscii(leadByte) && IsDBCSLeadByteNoExcept(leadByte)) ? 2 : 1;
if (!widthFirstCharacter) {
widthFirstCharacter = widthChar;
}
if ((pos + indexDocument + widthChar) > limitPos) {
break;
}
size_t lenFlat = 1;
if (widthChar == 1) {
characterMatches = searchThing[indexSearch] == MakeLowerCase(leadByte);
} else {
const char bytes[maxBytesCharacter + 1] {
static_cast<char>(leadByte),
cbView.CharAt(pos + indexDocument + 1)
};
char folded[maxBytesCharacter * maxFoldingExpansion + 1];
lenFlat = pcf->Fold(folded, sizeof(folded), bytes, widthChar);
// memcmp may examine lenFlat bytes in both arguments so assert it doesn't read past end of searchThing
assert((indexSearch + lenFlat) <= searchThing.size());
// Does folded match the buffer
characterMatches = 0 == memcmp(folded, searchThing.data() + indexSearch, lenFlat);
}
if (!characterMatches) {
break;
}
indexDocument += widthChar;
indexSearch += lenFlat;
}
if (characterMatches && (indexSearch == lenSearch)) {
if (MatchesWordOptions(word, wordStart, pos, indexDocument)) {
*length = indexDocument;
return pos;
}
}
if (forward) {
pos += widthFirstCharacter;
} else {
if (!NextCharacter(pos, increment)) {
break;
}
}
}
} else {
const Sci::Position endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : endPos;
std::vector<char> searchThing(lengthFind + 1);
pcf->Fold(searchThing.data(), searchThing.size(), search, lengthFind);
while (forward ? (pos < endSearch) : (pos >= endSearch)) {
bool found = (pos + lengthFind) <= limitPos;
for (int indexSearch = 0; (indexSearch < lengthFind) && found; indexSearch++) {
const char ch = cbView.CharAt(pos + indexSearch);
const char chTest = searchThing[indexSearch];
if (UTF8IsAscii(ch)) {
found = chTest == MakeLowerCase(ch);
} else {
char folded[2];
pcf->Fold(folded, sizeof(folded), &ch, 1);
found = folded[0] == chTest;
}
}
if (found && MatchesWordOptions(word, wordStart, pos, lengthFind)) {
return pos;
}
pos += increment;
}
}
}
//Platform::DebugPrintf("Not found\n");
return -1;
}
const char *Document::SubstituteByPosition(const char *text, Sci::Position *length) {
if (regex)
return regex->SubstituteByPosition(this, text, length);
else
return nullptr;
}
LineCharacterIndexType Document::LineCharacterIndex() const noexcept {
return cb.LineCharacterIndex();
}
void Document::AllocateLineCharacterIndex(LineCharacterIndexType lineCharacterIndex) {
cb.AllocateLineCharacterIndex(lineCharacterIndex);
}
void Document::ReleaseLineCharacterIndex(LineCharacterIndexType lineCharacterIndex) {
cb.ReleaseLineCharacterIndex(lineCharacterIndex);
}
Sci::Line Document::LinesTotal() const noexcept {
return cb.Lines();
}
void Document::AllocateLines(Sci::Line lines) {
cb.AllocateLines(lines);
}
void Document::SetDefaultCharClasses(bool includeWordClass) {
charClass.SetDefaultCharClasses(includeWordClass);
}
void Document::SetCharClasses(const unsigned char *chars, CharacterClass newCharClass) {
charClass.SetCharClasses(chars, newCharClass);
}
int Document::GetCharsOfClass(CharacterClass characterClass, unsigned char *buffer) const {
return charClass.GetCharsOfClass(characterClass, buffer);
}
void Document::SetCharacterCategoryOptimization(int countCharacters) {
charMap.Optimize(countCharacters);
}
int Document::CharacterCategoryOptimization() const noexcept {
return charMap.Size();
}
void SCI_METHOD Document::StartStyling(Sci_Position position) {
endStyled = position;
}
bool SCI_METHOD Document::SetStyleFor(Sci_Position length, char style) {
if (enteredStyling != 0) {
return false;
} else {
enteredStyling++;
const Sci::Position prevEndStyled = endStyled;
if (cb.SetStyleFor(endStyled, length, style)) {
const DocModification mh(ModificationFlags::ChangeStyle | ModificationFlags::User,
prevEndStyled, length);
NotifyModified(mh);
}
endStyled += length;
enteredStyling--;
return true;
}
}
bool SCI_METHOD Document::SetStyles(Sci_Position length, const char *styles) {
if (enteredStyling != 0) {
return false;
} else {
enteredStyling++;
bool didChange = false;
Sci::Position startMod = 0;
Sci::Position endMod = 0;
for (int iPos = 0; iPos < length; iPos++, endStyled++) {
PLATFORM_ASSERT(endStyled < Length());
if (cb.SetStyleAt(endStyled, styles[iPos])) {
if (!didChange) {
startMod = endStyled;
}
didChange = true;
endMod = endStyled;
}
}
if (didChange) {
const DocModification mh(ModificationFlags::ChangeStyle | ModificationFlags::User,
startMod, endMod - startMod + 1);
NotifyModified(mh);
}
enteredStyling--;
return true;
}
}
void Document::EnsureStyledTo(Sci::Position pos) {
if ((enteredStyling == 0) && (pos > GetEndStyled())) {
IncrementStyleClock();
if (pli && !pli->UseContainerLexing()) {
const Sci::Position endStyledTo = LineStartPosition(GetEndStyled());
pli->Colourise(endStyledTo, pos);
} else {
// Ask the watchers to style, and stop as soon as one responds.
for (std::vector<WatcherWithUserData>::iterator it = watchers.begin();
(pos > GetEndStyled()) && (it != watchers.end()); ++it) {
it->watcher->NotifyStyleNeeded(this, it->userData, pos);
}
}
}
}
void Document::StyleToAdjustingLineDuration(Sci::Position pos) {
const Sci::Position stylingStart = GetEndStyled();
ElapsedPeriod epStyling;
EnsureStyledTo(pos);
durationStyleOneByte.AddSample(pos - stylingStart, epStyling.Duration());
}
LexInterface *Document::GetLexInterface() const noexcept {
return pli.get();
}
void Document::SetLexInterface(std::unique_ptr<LexInterface> pLexInterface) noexcept {
pli = std::move(pLexInterface);
}
void Document::SetViewState(void *view, ViewStateShared pVSS) {
if (pVSS) {
viewData[view] = std::move(pVSS);
} else {
viewData.erase(view);
}
}
ViewStateShared Document::GetViewState(void *view) const noexcept {
try {
const std::map<void *, ViewStateShared>::const_iterator it = viewData.find(view);
if (it != viewData.end()) {
return it->second;
}
} catch (...) {
}
return {};
}
void Document::TruncateUndoComments(int action) {
for (auto &[key, value] : viewData) {
value->TruncateUndo(action);
}
}
int SCI_METHOD Document::SetLineState(Sci_Position line, int state) {
const int statePrevious = States()->SetLineState(line, state, LinesTotal());
if (state != statePrevious) {
const DocModification mh(ModificationFlags::ChangeLineState, LineStart(line), 0, 0, nullptr,
static_cast<Sci::Line>(line));
NotifyModified(mh);
}
return statePrevious;
}
int SCI_METHOD Document::GetLineState(Sci_Position line) const {
return States()->GetLineState(line);
}
Sci::Line Document::GetMaxLineState() const noexcept {
return States()->GetMaxLineState();
}
void SCI_METHOD Document::ChangeLexerState(Sci_Position start, Sci_Position end) {
const DocModification mh(ModificationFlags::LexerState, start,
end-start, 0, nullptr, 0);
NotifyModified(mh);
}
StyledText Document::MarginStyledText(Sci::Line line) const noexcept {
const LineAnnotation *pla = Margins();
return StyledText(pla->Length(line), pla->Text(line),
pla->MultipleStyles(line), pla->Style(line), pla->Styles(line));
}
void Document::MarginSetText(Sci::Line line, const char *text) {
Margins()->SetText(line, text);
const DocModification mh(ModificationFlags::ChangeMargin, LineStart(line),
0, 0, nullptr, line);
NotifyModified(mh);
}
void Document::MarginSetStyle(Sci::Line line, int style) {
Margins()->SetStyle(line, style);
NotifyModified(DocModification(ModificationFlags::ChangeMargin, LineStart(line),
0, 0, nullptr, line));
}
void Document::MarginSetStyles(Sci::Line line, const unsigned char *styles) {
Margins()->SetStyles(line, styles);
NotifyModified(DocModification(ModificationFlags::ChangeMargin, LineStart(line),
0, 0, nullptr, line));
}
void Document::MarginClearAll() {
const Sci::Line maxEditorLine = LinesTotal();
for (Sci::Line l=0; l<maxEditorLine; l++)
MarginSetText(l, nullptr);
// Free remaining data
Margins()->ClearAll();
}
StyledText Document::AnnotationStyledText(Sci::Line line) const noexcept {
const LineAnnotation *pla = Annotations();
return StyledText(pla->Length(line), pla->Text(line),
pla->MultipleStyles(line), pla->Style(line), pla->Styles(line));
}
void Document::AnnotationSetText(Sci::Line line, const char *text) {
if (line >= 0 && line < LinesTotal()) {
const Sci::Line linesBefore = AnnotationLines(line);
Annotations()->SetText(line, text);
const int linesAfter = AnnotationLines(line);
DocModification mh(ModificationFlags::ChangeAnnotation, LineStart(line),
0, 0, nullptr, line);
mh.annotationLinesAdded = linesAfter - linesBefore;
NotifyModified(mh);
}
}
void Document::AnnotationSetStyle(Sci::Line line, int style) {
if (line >= 0 && line < LinesTotal()) {
Annotations()->SetStyle(line, style);
const DocModification mh(ModificationFlags::ChangeAnnotation, LineStart(line),
0, 0, nullptr, line);
NotifyModified(mh);
}
}
void Document::AnnotationSetStyles(Sci::Line line, const unsigned char *styles) {
if (line >= 0 && line < LinesTotal()) {
Annotations()->SetStyles(line, styles);
}
}
int Document::AnnotationLines(Sci::Line line) const noexcept {
return Annotations()->Lines(line);
}
void Document::AnnotationClearAll() {
if (Annotations()->Empty()) {
return;
}
const Sci::Line maxEditorLine = LinesTotal();
for (Sci::Line l=0; l<maxEditorLine; l++)
AnnotationSetText(l, nullptr);
// Free remaining data
Annotations()->ClearAll();
}
StyledText Document::EOLAnnotationStyledText(Sci::Line line) const noexcept {
const LineAnnotation *pla = EOLAnnotations();
return StyledText(pla->Length(line), pla->Text(line),
pla->MultipleStyles(line), pla->Style(line), pla->Styles(line));
}
void Document::EOLAnnotationSetText(Sci::Line line, const char *text) {
if (line >= 0 && line < LinesTotal()) {
EOLAnnotations()->SetText(line, text);
const DocModification mh(ModificationFlags::ChangeEOLAnnotation, LineStart(line),
0, 0, nullptr, line);
NotifyModified(mh);
}
}
void Document::EOLAnnotationSetStyle(Sci::Line line, int style) {
if (line >= 0 && line < LinesTotal()) {
EOLAnnotations()->SetStyle(line, style);
const DocModification mh(ModificationFlags::ChangeEOLAnnotation, LineStart(line),
0, 0, nullptr, line);
NotifyModified(mh);
}
}
void Document::EOLAnnotationClearAll() {
if (EOLAnnotations()->Empty()) {
return;
}
const Sci::Line maxEditorLine = LinesTotal();
for (Sci::Line l=0; l<maxEditorLine; l++)
EOLAnnotationSetText(l, nullptr);
// Free remaining data
EOLAnnotations()->ClearAll();
}
void Document::IncrementStyleClock() noexcept {
styleClock = (styleClock + 1) % 0x100000;
}
void SCI_METHOD Document::DecorationSetCurrentIndicator(int indicator) {
decorations->SetCurrentIndicator(indicator);
}
void SCI_METHOD Document::DecorationFillRange(Sci_Position position, int value, Sci_Position fillLength) {
const FillResult<Sci::Position> fr = decorations->FillRange(
position, value, fillLength);
if (fr.changed) {
const DocModification mh(ModificationFlags::ChangeIndicator | ModificationFlags::User,
fr.position, fr.fillLength);
NotifyModified(mh);
}
}
bool Document::AddWatcher(DocWatcher *watcher, void *userData) {
const WatcherWithUserData wwud(watcher, userData);
std::vector<WatcherWithUserData>::iterator it =
std::find(watchers.begin(), watchers.end(), wwud);
if (it != watchers.end())
return false;
watchers.push_back(wwud);
return true;
}
bool Document::RemoveWatcher(DocWatcher *watcher, void *userData) noexcept {
try {
// This can never fail as WatcherWithUserData constructor and == are noexcept
// but std::find is not noexcept.
std::vector<WatcherWithUserData>::iterator it =
std::find(watchers.begin(), watchers.end(), WatcherWithUserData(watcher, userData));
if (it != watchers.end()) {
watchers.erase(it);
return true;
}
} catch (...) {
// Ignore any exception
}
return false;
}
void Document::NotifyModifyAttempt() {
for (const WatcherWithUserData &watcher : watchers) {
watcher.watcher->NotifyModifyAttempt(this, watcher.userData);
}
}
void Document::NotifySavePoint(bool atSavePoint) {
for (const WatcherWithUserData &watcher : watchers) {
watcher.watcher->NotifySavePoint(this, watcher.userData, atSavePoint);
}
}
void Document::NotifyGroupCompleted() noexcept {
for (const WatcherWithUserData &watcher : watchers) {
watcher.watcher->NotifyGroupCompleted(this, watcher.userData);
}
}
void Document::NotifyModified(DocModification mh) {
if (FlagSet(mh.modificationType, ModificationFlags::InsertText)) {
decorations->InsertSpace(mh.position, mh.length);
} else if (FlagSet(mh.modificationType, ModificationFlags::DeleteText)) {
decorations->DeleteRange(mh.position, mh.length);
}
for (const WatcherWithUserData &watcher : watchers) {
watcher.watcher->NotifyModified(this, mh, watcher.userData);
}
}
bool Document::IsWordPartSeparator(unsigned int ch) const {
return (WordCharacterClass(ch) == CharacterClass::word) && IsPunctuation(ch);
}
Sci::Position Document::WordPartLeft(Sci::Position pos) const {
if (pos > 0) {
pos -= CharacterBefore(pos).widthBytes;
CharacterExtracted ceStart = CharacterAfter(pos);
if (IsWordPartSeparator(ceStart.character)) {
while (pos > 0 && IsWordPartSeparator(CharacterAfter(pos).character)) {
pos -= CharacterBefore(pos).widthBytes;
}
}
if (pos > 0) {
ceStart = CharacterAfter(pos);
pos -= CharacterBefore(pos).widthBytes;
if (IsLowerCase(ceStart.character)) {
while (pos > 0 && IsLowerCase(CharacterAfter(pos).character))
pos -= CharacterBefore(pos).widthBytes;
if (!IsUpperCase(CharacterAfter(pos).character) && !IsLowerCase(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (IsUpperCase(ceStart.character)) {
while (pos > 0 && IsUpperCase(CharacterAfter(pos).character))
pos -= CharacterBefore(pos).widthBytes;
if (!IsUpperCase(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (IsADigit(ceStart.character)) {
while (pos > 0 && IsADigit(CharacterAfter(pos).character))
pos -= CharacterBefore(pos).widthBytes;
if (!IsADigit(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (IsPunctuation(ceStart.character)) {
while (pos > 0 && IsPunctuation(CharacterAfter(pos).character))
pos -= CharacterBefore(pos).widthBytes;
if (!IsPunctuation(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (IsASpace(ceStart.character)) {
while (pos > 0 && IsASpace(CharacterAfter(pos).character))
pos -= CharacterBefore(pos).widthBytes;
if (!IsASpace(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (!IsASCII(ceStart.character)) {
while (pos > 0 && !IsASCII(CharacterAfter(pos).character))
pos -= CharacterBefore(pos).widthBytes;
if (IsASCII(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else {
pos += CharacterAfter(pos).widthBytes;
}
}
}
return pos;
}
Sci::Position Document::WordPartRight(Sci::Position pos) const {
CharacterExtracted ceStart = CharacterAfter(pos);
const Sci::Position length = LengthNoExcept();
if (IsWordPartSeparator(ceStart.character)) {
while (pos < length && IsWordPartSeparator(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
ceStart = CharacterAfter(pos);
}
if (!IsASCII(ceStart.character)) {
while (pos < length && !IsASCII(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (IsLowerCase(ceStart.character)) {
while (pos < length && IsLowerCase(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (IsUpperCase(ceStart.character)) {
if (IsLowerCase(CharacterAfter(pos + ceStart.widthBytes).character)) {
pos += CharacterAfter(pos).widthBytes;
while (pos < length && IsLowerCase(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else {
while (pos < length && IsUpperCase(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
}
if (IsLowerCase(CharacterAfter(pos).character) && IsUpperCase(CharacterBefore(pos).character))
pos -= CharacterBefore(pos).widthBytes;
} else if (IsADigit(ceStart.character)) {
while (pos < length && IsADigit(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (IsPunctuation(ceStart.character)) {
while (pos < length && IsPunctuation(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else if (IsASpace(ceStart.character)) {
while (pos < length && IsASpace(CharacterAfter(pos).character))
pos += CharacterAfter(pos).widthBytes;
} else {
pos += CharacterAfter(pos).widthBytes;
}
return pos;
}
Sci::Position Document::ExtendStyleRange(Sci::Position pos, int delta, bool singleLine) noexcept {
const char sStart = cb.StyleAt(pos);
if (delta < 0) {
while (pos > 0 && (cb.StyleAt(pos) == sStart) && (!singleLine || !IsEOLCharacter(cb.CharAt(pos))))
pos--;
pos++;
} else {
while (pos < (LengthNoExcept()) && (cb.StyleAt(pos) == sStart) && (!singleLine || !IsEOLCharacter(cb.CharAt(pos))))
pos++;
}
return pos;
}
namespace {
constexpr char BraceOpposite(char ch) noexcept {
switch (ch) {
case '(':
return ')';
case ')':
return '(';
case '[':
return ']';
case ']':
return '[';
case '{':
return '}';
case '}':
return '{';
case '<':
return '>';
case '>':
return '<';
default:
return '\0';
}
}
}
// TODO: should be able to extend styled region to find matching brace
Sci::Position Document::BraceMatch(Sci::Position position, Sci::Position /*maxReStyle*/, Sci::Position startPos, bool useStartPos) noexcept {
const unsigned char chBrace = CharAt(position);
const unsigned char chSeek = BraceOpposite(chBrace);
if (chSeek == '\0')
return -1;
const int styBrace = StyleIndexAt(position);
int direction = -1;
if (chBrace == '(' || chBrace == '[' || chBrace == '{' || chBrace == '<')
direction = 1;
int depth = 1;
position = useStartPos ? startPos : position + direction;
// Avoid using MovePositionOutsideChar to check DBCS trail byte
unsigned char maxSafeChar = 0xff;
if (dbcsCodePage != 0 && dbcsCodePage != CpUtf8) {
maxSafeChar = DBCSMinTrailByte() - 1;
}
while ((position >= 0) && (position < LengthNoExcept())) {
const unsigned char chAtPos = CharAt(position);
if (chAtPos == chBrace || chAtPos == chSeek) {
if (((position > GetEndStyled()) || (StyleIndexAt(position) == styBrace)) &&
(chAtPos <= maxSafeChar || position == MovePositionOutsideChar(position, direction, false))) {
depth += (chAtPos == chBrace) ? 1 : -1;
if (depth == 0)
return position;
}
}
position += direction;
}
return -1;
}
/**
* Implementation of RegexSearchBase for the default built-in regular expression engine
*/
class BuiltinRegex : public RegexSearchBase {
public:
explicit BuiltinRegex(CharClassify *charClassTable) : search(charClassTable) {}
Sci::Position FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
bool caseSensitive, bool word, bool wordStart, FindOption flags,
Sci::Position *length) override;
const char *SubstituteByPosition(Document *doc, const char *text, Sci::Position *length) override;
private:
RESearch search;
std::string substituted;
};
namespace {
/**
* RESearchRange keeps track of search range.
*/
class RESearchRange {
public:
int increment;
Sci::Position startPos;
Sci::Position endPos;
Sci::Line lineRangeStart;
Sci::Line lineRangeEnd;
Sci::Line lineRangeBreak;
RESearchRange(const Document *doc, Sci::Position minPos, Sci::Position maxPos) noexcept {
increment = (minPos <= maxPos) ? 1 : -1;
// Range endpoints should not be inside DBCS characters or between a CR and LF,
// but just in case, move them.
startPos = doc->MovePositionOutsideChar(minPos, 1, true);
endPos = doc->MovePositionOutsideChar(maxPos, 1, true);
lineRangeStart = doc->SciLineFromPosition(startPos);
lineRangeEnd = doc->SciLineFromPosition(endPos);
lineRangeBreak = lineRangeEnd + increment;
}
[[nodiscard]] Range LineRange(Sci::Line line, Sci::Position lineStartPos, Sci::Position lineEndPos) const noexcept {
Range range(lineStartPos, lineEndPos);
if (increment == 1) {
if (line == lineRangeStart)
range.start = startPos;
if (line == lineRangeEnd)
range.end = endPos;
} else {
if (line == lineRangeEnd)
range.start = endPos;
if (line == lineRangeStart)
range.end = startPos;
}
return range;
}
};
// Define a way for the Regular Expression code to access the document
class DocumentIndexer final : public CharacterIndexer {
Document *pdoc;
Sci::Position end;
public:
DocumentIndexer(Document *pdoc_, Sci::Position end_) noexcept :
pdoc(pdoc_), end(end_) {
}
[[nodiscard]] char CharAt(Sci::Position index) const noexcept override {
if (index < 0 || index >= end)
return 0;
else
return pdoc->CharAt(index);
}
[[nodiscard]] Sci::Position MovePositionOutsideChar(Sci::Position pos, Sci::Position moveDir) const noexcept override {
return pdoc->MovePositionOutsideChar(pos, moveDir, false);
}
};
#ifndef NO_CXX11_REGEX
class ByteIterator {
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = char;
using difference_type = ptrdiff_t;
using pointer = char*;
using reference = char&;
const Document *doc;
Sci::Position position;
explicit ByteIterator(const Document *doc_=nullptr, Sci::Position position_=0) noexcept :
doc(doc_), position(position_) {
}
char operator*() const noexcept {
return doc->CharAt(position);
}
ByteIterator &operator++() noexcept {
position++;
return *this;
}
ByteIterator operator++(int) noexcept {
ByteIterator retVal(*this);
position++;
return retVal;
}
ByteIterator &operator--() noexcept {
position--;
return *this;
}
bool operator==(const ByteIterator &other) const noexcept {
return doc == other.doc && position == other.position;
}
bool operator!=(const ByteIterator &other) const noexcept {
return doc != other.doc || position != other.position;
}
[[nodiscard]] Sci::Position Pos() const noexcept {
return position;
}
[[nodiscard]] Sci::Position PosRoundUp() const noexcept {
return position;
}
};
// On Windows, wchar_t is 16 bits wide and on Unix it is 32 bits wide.
// Would be better to use sizeof(wchar_t) or similar to differentiate
// but easier for now to hard-code platforms.
// C++11 has char16_t and char32_t but neither Clang nor Visual C++
// appear to allow specializing basic_regex over these.
#ifdef _WIN32
#define WCHAR_T_IS_16 1
#else
#define WCHAR_T_IS_16 0
#endif
#if WCHAR_T_IS_16
// On Windows, report non-BMP characters as 2 separate surrogates as that
// matches wregex since it is based on wchar_t.
class UTF8Iterator {
// These 3 fields determine the iterator position and are used for comparisons
const Document *doc;
Sci::Position position;
size_t characterIndex = 0;
// Remaining fields are derived from the determining fields so are excluded in comparisons
unsigned int lenBytes = 0;
size_t lenCharacters = 0;
wchar_t buffered[2]{};
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = wchar_t;
using difference_type = ptrdiff_t;
using pointer = wchar_t*;
using reference = wchar_t&;
explicit UTF8Iterator(const Document *doc_=nullptr, Sci::Position position_=0) noexcept :
doc(doc_), position(position_) {
if (doc) {
ReadCharacter();
}
}
wchar_t operator*() const noexcept {
assert(lenCharacters != 0);
return buffered[characterIndex];
}
UTF8Iterator &operator++() noexcept {
if ((characterIndex + 1) < (lenCharacters)) {
characterIndex++;
} else {
position += lenBytes;
ReadCharacter();
characterIndex = 0;
}
return *this;
}
UTF8Iterator operator++(int) noexcept {
UTF8Iterator retVal(*this);
if ((characterIndex + 1) < (lenCharacters)) {
characterIndex++;
} else {
position += lenBytes;
ReadCharacter();
characterIndex = 0;
}
return retVal;
}
UTF8Iterator &operator--() noexcept {
if (characterIndex) {
characterIndex--;
} else {
position = doc->NextPosition(position, -1);
ReadCharacter();
characterIndex = lenCharacters - 1;
}
return *this;
}
bool operator==(const UTF8Iterator &other) const noexcept {
// Only test the determining fields, not the character widths and values derived from this
return doc == other.doc &&
position == other.position &&
characterIndex == other.characterIndex;
}
bool operator!=(const UTF8Iterator &other) const noexcept {
// Only test the determining fields, not the character widths and values derived from this
return doc != other.doc ||
position != other.position ||
characterIndex != other.characterIndex;
}
[[nodiscard]] Sci::Position Pos() const noexcept {
return position;
}
[[nodiscard]] Sci::Position PosRoundUp() const noexcept {
if (characterIndex)
return position + lenBytes; // Force to end of character
else
return position;
}
private:
void ReadCharacter() noexcept {
const CharacterExtracted charExtracted = doc->ExtractCharacter(position);
lenBytes = charExtracted.widthBytes;
if (charExtracted.character == unicodeReplacementChar) {
lenCharacters = 1;
buffered[0] = static_cast<wchar_t>(charExtracted.character);
} else {
lenCharacters = UTF16FromUTF32Character(charExtracted.character, buffered);
}
}
};
#else
// On Unix, report non-BMP characters as single characters
class UTF8Iterator {
const Document *doc;
Sci::Position position;
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = wchar_t;
using difference_type = ptrdiff_t;
using pointer = wchar_t*;
using reference = wchar_t&;
explicit UTF8Iterator(const Document *doc_=nullptr, Sci::Position position_=0) noexcept :
doc(doc_), position(position_) {
}
wchar_t operator*() const noexcept {
const CharacterExtracted charExtracted = doc->ExtractCharacter(position);
return charExtracted.character;
}
UTF8Iterator &operator++() noexcept {
position = doc->NextPosition(position, 1);
return *this;
}
UTF8Iterator operator++(int) noexcept {
UTF8Iterator retVal(*this);
position = doc->NextPosition(position, 1);
return retVal;
}
UTF8Iterator &operator--() noexcept {
position = doc->NextPosition(position, -1);
return *this;
}
bool operator==(const UTF8Iterator &other) const noexcept {
return doc == other.doc && position == other.position;
}
bool operator!=(const UTF8Iterator &other) const noexcept {
return doc != other.doc || position != other.position;
}
Sci::Position Pos() const noexcept {
return position;
}
Sci::Position PosRoundUp() const noexcept {
return position;
}
};
#endif
std::regex_constants::match_flag_type MatchFlags(const Document *doc, Sci::Position startPos, Sci::Position endPos, Sci::Position lineStartPos, Sci::Position lineEndPos) {
std::regex_constants::match_flag_type flagsMatch = std::regex_constants::match_default;
if (startPos != lineStartPos) {
#ifdef _LIBCPP_VERSION
flagsMatch |= std::regex_constants::match_not_bol;
if (!doc->IsWordStartAt(startPos)) {
flagsMatch |= std::regex_constants::match_not_bow;
}
#else
flagsMatch |= std::regex_constants::match_prev_avail;
#endif
}
if (endPos != lineEndPos) {
flagsMatch |= std::regex_constants::match_not_eol;
if (!doc->IsWordEndAt(endPos)) {
flagsMatch |= std::regex_constants::match_not_eow;
}
}
return flagsMatch;
}
template<typename Iterator, typename Regex>
bool MatchOnLines(const Document *doc, const Regex ®exp, const RESearchRange &resr, RESearch &search) {
std::match_results<Iterator> match;
// MSVC and libc++ have problems with ^ and $ matching line ends inside a range.
// CRLF line ends are also a problem as ^ and $ only treat LF as a line end.
// The std::regex::multiline option was added to C++17 to improve behaviour but
// has not been implemented by compiler runtimes with MSVC always in multiline
// mode and libc++ and libstdc++ always in single-line mode.
// If multiline regex worked well then the line by line iteration could be removed
// for the forwards case and replaced with the following:
#ifdef REGEX_MULTILINE
const Sci::Position lineStartPos = doc->LineStart(resr.lineRangeStart);
const Sci::Position lineEndPos = doc->LineEnd(resr.lineRangeEnd);
Iterator itStart(doc, resr.startPos);
Iterator itEnd(doc, resr.endPos);
const std::regex_constants::match_flag_type flagsMatch = MatchFlags(doc, resr.startPos, resr.endPos, lineStartPos, lineEndPos);
const bool matched = std::regex_search(itStart, itEnd, match, regexp, flagsMatch);
#else
// Line by line.
bool matched = false;
for (Sci::Line line = resr.lineRangeStart; line != resr.lineRangeBreak; line += resr.increment) {
const Sci::Position lineStartPos = doc->LineStart(line);
const Sci::Position lineEndPos = doc->LineEnd(line);
const Range lineRange = resr.LineRange(line, lineStartPos, lineEndPos);
const Iterator itStart(doc, lineRange.start);
const Iterator itEnd(doc, lineRange.end);
const std::regex_constants::match_flag_type flagsMatch = MatchFlags(doc, lineRange.start, lineRange.end, lineStartPos, lineEndPos);
std::regex_iterator<Iterator> it(itStart, itEnd, regexp, flagsMatch);
for (const std::regex_iterator<Iterator> last; it != last; ++it) {
match = *it;
matched = true;
if (resr.increment > 0) {
break;
}
}
if (matched) {
break;
}
}
#endif
if (matched) {
for (size_t co = 0; co < match.size() && co < RESearch::MAXTAG; co++) {
search.bopat[co] = match[co].first.Pos();
search.eopat[co] = match[co].second.PosRoundUp();
}
}
return matched;
}
Sci::Position Cxx11RegexFindText(const Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
bool caseSensitive, Sci::Position *length, RESearch &search) {
const RESearchRange resr(doc, minPos, maxPos);
try {
//ElapsedPeriod ep;
std::regex::flag_type flagsRe = std::regex::ECMAScript;
// Flags that appear to have no effect:
// | std::regex::collate | std::regex::extended;
if (!caseSensitive)
flagsRe = flagsRe | std::regex::icase;
#if defined(REGEX_MULTILINE) && !defined(_MSC_VER)
flagsRe = flagsRe | std::regex::multiline;
#endif
// Clear the RESearch so can fill in matches
search.Clear();
bool matched = false;
if (CpUtf8 == doc->dbcsCodePage) {
const std::wstring ws = WStringFromUTF8(s);
std::wregex regexp;
regexp.assign(ws, flagsRe);
matched = MatchOnLines<UTF8Iterator>(doc, regexp, resr, search);
} else {
std::regex regexp;
regexp.assign(s, flagsRe);
matched = MatchOnLines<ByteIterator>(doc, regexp, resr, search);
}
Sci::Position posMatch = -1;
if (matched) {
posMatch = search.bopat[0];
*length = search.eopat[0] - search.bopat[0];
}
// Example - search in doc/ScintillaHistory.html for
// [[:upper:]]eta[[:space:]]
// On MacBook, normally around 1 second but with locale imbued -> 14 seconds.
//const double durSearch = ep.Duration(true);
//Platform::DebugPrintf("Search:%9.6g \n", durSearch);
return posMatch;
} catch (std::regex_error &) {
// Failed to create regular expression
throw RegexError();
} catch (...) {
// Failed in some other way
return -1;
}
}
#endif
}
Sci::Position BuiltinRegex::FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s,
bool caseSensitive, bool, bool, FindOption flags,
Sci::Position *length) {
#ifndef NO_CXX11_REGEX
if (FlagSet(flags, FindOption::Cxx11RegEx)) {
return Cxx11RegexFindText(doc, minPos, maxPos, s,
caseSensitive, length, search);
}
#endif
const RESearchRange resr(doc, minPos, maxPos);
const bool posix = FlagSet(flags, FindOption::Posix);
const char *errmsg = search.Compile(s, *length, caseSensitive, posix);
if (errmsg) {
return -1;
}
// Find a variable in a property file: \$(\([A-Za-z0-9_.]+\))
// Replace first '.' with '-' in each property file variable reference:
// Search: \$(\([A-Za-z0-9_-]+\)\.\([A-Za-z0-9_.]+\))
// Replace: $(\1-\2)
Sci::Position pos = -1;
Sci::Position lenRet = 0;
const bool searchforLineStart = s[0] == '^';
const char searchEnd = s[*length - 1];
const char searchEndPrev = (*length > 1) ? s[*length - 2] : '\0';
const bool searchforLineEnd = (searchEnd == '$') && (searchEndPrev != '\\');
for (Sci::Line line = resr.lineRangeStart; line != resr.lineRangeBreak; line += resr.increment) {
const Sci::Position lineStartPos = doc->LineStart(line);
const Sci::Position lineEndPos = doc->LineEnd(line);
Sci::Position startOfLine = lineStartPos;
Sci::Position endOfLine = lineEndPos;
if (resr.increment == 1) {
if (line == resr.lineRangeStart) {
if ((resr.startPos != startOfLine) && searchforLineStart)
continue; // Can't match start of line if start position after start of line
startOfLine = resr.startPos;
}
if (line == resr.lineRangeEnd) {
if ((resr.endPos != endOfLine) && searchforLineEnd)
continue; // Can't match end of line if end position before end of line
endOfLine = resr.endPos;
}
} else {
if (line == resr.lineRangeEnd) {
if ((resr.endPos != startOfLine) && searchforLineStart)
continue; // Can't match start of line if end position after start of line
startOfLine = resr.endPos;
}
if (line == resr.lineRangeStart) {
if ((resr.startPos != endOfLine) && searchforLineEnd)
continue; // Can't match end of line if start position before end of line
endOfLine = resr.startPos;
}
}
const DocumentIndexer di(doc, endOfLine);
search.SetLineRange(lineStartPos, lineEndPos);
int success = search.Execute(di, startOfLine, endOfLine);
if (success) {
Sci::Position endPos = search.eopat[0];
// There can be only one start of a line, so no need to look for last match in line
if ((resr.increment == -1) && !searchforLineStart) {
// Check for the last match on this line.
while (success && (endPos < endOfLine)) {
const RESearch::MatchPositions bopat = search.bopat;
const RESearch::MatchPositions eopat = search.eopat;
pos = endPos;
if (pos == bopat[0]) {
// empty match
pos = doc->NextPosition(pos, 1);
}
success = search.Execute(di, pos, endOfLine);
if (success) {
endPos = search.eopat[0];
} else {
search.bopat = bopat;
search.eopat = eopat;
}
}
}
pos = search.bopat[0];
lenRet = endPos - pos;
break;
}
}
*length = lenRet;
return pos;
}
const char *BuiltinRegex::SubstituteByPosition(Document *doc, const char *text, Sci::Position *length) {
substituted.clear();
for (Sci::Position j = 0; j < *length; j++) {
if (text[j] == '\\') {
const char chNext = text[++j];
if (chNext >= '0' && chNext <= '9') {
const unsigned int patNum = chNext - '0';
const Sci::Position startPos = search.bopat[patNum];
const Sci::Position len = search.eopat[patNum] - startPos;
if (len > 0) { // Will be null if try for a match that did not occur
const size_t size = substituted.length();
substituted.resize(size + len);
doc->GetCharRange(substituted.data() + size, startPos, len);
}
} else {
switch (chNext) {
case 'a':
substituted.push_back('\a');
break;
case 'b':
substituted.push_back('\b');
break;
case 'f':
substituted.push_back('\f');
break;
case 'n':
substituted.push_back('\n');
break;
case 'r':
substituted.push_back('\r');
break;
case 't':
substituted.push_back('\t');
break;
case 'v':
substituted.push_back('\v');
break;
case '\\':
substituted.push_back('\\');
break;
default:
substituted.push_back('\\');
j--;
}
}
} else {
substituted.push_back(text[j]);
}
}
*length = substituted.length();
return substituted.c_str();
}
#ifndef SCI_OWNREGEX
RegexSearchBase *Scintilla::Internal::CreateRegexSearch(CharClassify *charClassTable) {
return new BuiltinRegex(charClassTable);
}
#endif
|