summaryrefslogtreecommitdiffstats
path: root/generic/tkTextIndex.c
blob: 1e582c96d45c0989cc0d10f4f6c9a623261aa3a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
/*
 * tkTextIndex.c --
 *
 *	This module provides functions that manipulate indices for text widgets.
 *
 * Copyright (c) 1992-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright (c) 2015-2017 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "default.h"
#include "tkInt.h"
#include "tkText.h"
#include "tkTextTagSet.h"
#include "tkAlloc.h"
#include <stdlib.h>
#include <assert.h>

#ifndef MAX
# define MAX(a,b) (((int) a) < ((int) b) ? b : a)
#endif
#ifndef MIN
# define MIN(a,b) (((int) a) < ((int) b) ? a : b)
#endif

#ifdef NDEBUG
# define DEBUG(expr)
#else
# define DEBUG(expr) expr
#endif

/*
 * Modifiers for index parsing: 'display', 'any' or nothing.
 */

enum { TKINDEX_NONE, TKINDEX_DISPLAY, TKINDEX_CHAR };

/*
 * Forward declarations for functions defined later in this file:
 */

static const char *	ForwBack(TkText *textPtr, const char *string, TkTextIndex *indexPtr,
			    int charCount);
static const char *	StartEnd(TkText *textPtr, const char *string, TkTextIndex *indexPtr);
static TkTextSegment *	IndexToSeg(const TkTextIndex *indexPtr, int *offsetPtr);
static int		SegToIndex(const TkTextLine *linePtr, const TkTextSegment *segPtr);

/*
 * A note about sizeof(char). Due to the specification of sizeof in C99,
 * sizeof(char) is always 1, see section 6.5.3.4:
 *
 *	When applied to an operand that has type char, unsigned char, or
 *	signed char, (or a qualified version thereof) the result is 1.
 *
 * This means that the expression "== sizeof(char)" is not required, the
 * expression "== 1" is good as well.
 */

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexIsEmpty --
 *
 *	Return whether the given index is empty (still unset, or invalid).
 *
 * Results:
 *	True if empty, false otherwise.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexIsEmpty(
    const TkTextIndex *indexPtr)
{
    assert(indexPtr);
    return indexPtr->priv.byteIndex == -1 && !indexPtr->priv.segPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetLine --
 *
 *	Set the line pointer of this index.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

#ifndef NDEBUG
static bool
CheckLine(
    const TkTextIndex *indexPtr,
    const TkTextLine *linePtr)
{
    assert(linePtr);

    if (indexPtr->stateEpoch == TkBTreeEpoch(indexPtr->tree)) {
	if (indexPtr->priv.segPtr
		&& indexPtr->priv.segPtr->sectionPtr->linePtr != indexPtr->priv.linePtr) {
	    return false;
	}
	if (indexPtr->priv.lineNo != -1
		&& indexPtr->priv.lineNo !=
		(int) TkBTreeLinesTo(indexPtr->tree, NULL, indexPtr->priv.linePtr, NULL)) {
	    return false;
	}
	if (indexPtr->priv.lineNoRel != -1
		&& indexPtr->priv.lineNoRel !=
		(int) TkBTreeLinesTo(indexPtr->tree, indexPtr->textPtr, indexPtr->priv.linePtr, NULL)) {
	    return false;
	}
    }

    if (!indexPtr->discardConsistencyCheck && indexPtr->textPtr) {
	const TkTextLine *startLine = TkBTreeGetStartLine(indexPtr->textPtr);
	const TkTextLine *endLine = TkBTreeGetLastLine(indexPtr->textPtr);
	int lineNo = TkBTreeLinesTo(indexPtr->tree, NULL, linePtr, NULL);

	if (lineNo < (int) TkBTreeLinesTo(indexPtr->tree, NULL, startLine, NULL)) {
	    return false;
	}
	if (lineNo > (int) TkBTreeLinesTo(indexPtr->tree, NULL, endLine, NULL)) {
	    return false;
	}
    }

    return true;
}
#endif /* NDEBUG */

static int
FindStartByteIndex(
    const TkTextIndex *indexPtr)
{
    const TkText *textPtr = indexPtr->textPtr;
    const TkTextSegment *segPtr;
    const TkTextSection *sectionPtr;
    int byteIndex;

    if (!textPtr) {
	return 0;
    }

    if (textPtr->startMarker == TkBTreeGetShared(indexPtr->tree)->startMarker) {
	return 0;
    }

    segPtr = textPtr->startMarker;
    sectionPtr = segPtr->sectionPtr;
    byteIndex = 0;

    if (sectionPtr->linePtr == indexPtr->priv.linePtr) {
	while (segPtr && sectionPtr == segPtr->sectionPtr) {
	    byteIndex += segPtr->size;
	    segPtr = segPtr->prevPtr;
	}
	while (sectionPtr->prevPtr) {
	    sectionPtr = sectionPtr->prevPtr;
	    byteIndex += sectionPtr->size;
	}
    }

    return byteIndex;
}

static bool
DontNeedSpecialStartLineTreatment(
    const TkTextIndex *indexPtr)
{
    const TkText *textPtr = indexPtr->textPtr;

    return !textPtr
	    || textPtr->startMarker == TkBTreeGetShared(indexPtr->tree)->startMarker
	    || indexPtr->priv.linePtr != textPtr->startMarker->sectionPtr->linePtr;
}

void
TkTextIndexSetLine(
    TkTextIndex *indexPtr,
    TkTextLine *linePtr)
{
    assert(linePtr);
    assert(indexPtr->tree);
    assert(CheckLine(indexPtr, linePtr));

    indexPtr->stateEpoch = TkBTreeEpoch(indexPtr->tree);
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;
    indexPtr->priv.segPtr = NULL;
    indexPtr->priv.byteIndex = -1;

    if ((indexPtr->priv.linePtr = linePtr)) {
	assert(linePtr->parentPtr); /* expired? */

	if (DontNeedSpecialStartLineTreatment(indexPtr)) {
	    indexPtr->priv.byteIndex = 0;
	} else {
	    indexPtr->priv.segPtr = indexPtr->textPtr->startMarker;
	    indexPtr->priv.isCharSegment = false;
	    indexPtr->priv.byteIndex = FindStartByteIndex(indexPtr);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetPosition --
 *
 *	Set the byte index and the segment, the user is responsible
 *	for proper values.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

#ifndef NDEBUG
static bool
CheckByteIndex(
    const TkTextIndex *indexPtr,
    const TkTextLine *linePtr,
    int byteIndex)
{
    const TkText *textPtr = indexPtr->textPtr;

    if (byteIndex == -1 && (byteIndex = indexPtr->priv.byteIndex) == -1) {
	assert(indexPtr->priv.segPtr);
	assert(!indexPtr->priv.isCharSegment || TkBTreeEpoch(indexPtr->tree) == indexPtr->stateEpoch);
	byteIndex = SegToIndex(indexPtr->priv.linePtr, indexPtr->priv.segPtr);
    }

    if (!indexPtr->discardConsistencyCheck && textPtr) {
	if (linePtr == textPtr->startMarker->sectionPtr->linePtr) {
	    if (byteIndex < FindStartByteIndex(indexPtr)) {
		return false;
	    }
	}
	if (linePtr == textPtr->endMarker->sectionPtr->linePtr) {
	    return byteIndex <= SegToIndex(linePtr, textPtr->endMarker);
	}
	if (linePtr == textPtr->endMarker->sectionPtr->linePtr->nextPtr) {
	    return byteIndex == 0;
	}
    }

    return byteIndex < linePtr->size;
}
#endif /* NDEBUG */

void
TkTextIndexSetPosition(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    int byteIndex,		/* New byte index. */
    TkTextSegment *segPtr)	/* The segment which belongs to the byte index. */
{
    assert(indexPtr->tree);
    assert(byteIndex >= 0);
    assert(segPtr);
    assert(segPtr->typePtr);    /* expired? */
    assert(segPtr->sectionPtr); /* linked? */
    assert(CheckLine(indexPtr, segPtr->sectionPtr->linePtr));
    assert(CheckByteIndex(indexPtr, segPtr->sectionPtr->linePtr, byteIndex));

    indexPtr->stateEpoch = TkBTreeEpoch(indexPtr->tree);
    indexPtr->priv.linePtr = segPtr->sectionPtr->linePtr;
    indexPtr->priv.byteIndex = byteIndex;
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;
    indexPtr->priv.segPtr = segPtr;
    indexPtr->priv.isCharSegment = segPtr->typePtr == &tkTextCharType;

#ifndef NDEBUG
    {
	int pos = SegToIndex(indexPtr->priv.linePtr, segPtr);

	if (segPtr->typePtr == &tkTextCharType) {
	    assert(byteIndex - pos < segPtr->size);
	} else {
	    assert(pos == byteIndex);
	}
    }
#endif /* NDEBUG */
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetByteIndex --
 *
 *	Set the byte index. We allow to set to the start of the next
 *	line (this means that argument byteIndex is equal to line size),
 *	required that the next line exists.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static bool
DontNeedSpecialEndLineTreatment(
    const TkTextIndex *indexPtr)
{
    const TkText *textPtr = indexPtr->textPtr;

    return !textPtr
	    || textPtr->endMarker == TkBTreeGetShared(indexPtr->tree)->endMarker
	    || indexPtr->priv.linePtr != textPtr->endMarker->sectionPtr->linePtr;
}

static int
FindEndByteIndex(
    const TkTextIndex *indexPtr)
{
    /*
     * We do not handle the special case with last line, because CheckLine is testing this.
     */

    if (indexPtr->textPtr && indexPtr->priv.linePtr == TkBTreeGetLastLine(indexPtr->textPtr)) {
	return 0;
    }
    if (DontNeedSpecialEndLineTreatment(indexPtr)) {
	return indexPtr->priv.linePtr->size - 1;
    }
    return SegToIndex(indexPtr->priv.linePtr, indexPtr->textPtr->endMarker);
}

void
TkTextIndexSetByteIndex(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    int byteIndex)		/* New byte index. */
{
    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(byteIndex >= 0);

    if (byteIndex == FindEndByteIndex(indexPtr) + 1) {
	assert(indexPtr->priv.linePtr->nextPtr);
	indexPtr->priv.linePtr = indexPtr->priv.linePtr->nextPtr;
	indexPtr->priv.byteIndex = 0;
	indexPtr->priv.segPtr = NULL;
	if (indexPtr->priv.lineNo >= 0) {
	    indexPtr->priv.lineNo += 1;
	}
	if (indexPtr->priv.lineNoRel >= 0) {
	    indexPtr->priv.lineNoRel += 1;
	}
    } else {
	indexPtr->priv.byteIndex = byteIndex;
	indexPtr->priv.segPtr = NULL;
    }

    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));
    assert(CheckByteIndex(indexPtr, indexPtr->priv.linePtr, byteIndex));
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetByteIndex2 --
 *
 *	Set the new line pointer and the byte index. We allow to set to
 *	the start of the next line (this means that argument byteIndex
 *	is equal to line size), required that the next line exists.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexSetByteIndex2(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    TkTextLine *linePtr,	/* Pointer to line. */
    int byteIndex)		/* New byte index. */
{
    assert(indexPtr->tree);
    assert(linePtr);
    assert(linePtr->parentPtr); /* expired? */
    assert(byteIndex >= 0);

    if (indexPtr->priv.linePtr != linePtr) {
	indexPtr->priv.linePtr = linePtr;
	indexPtr->priv.lineNo = -1;
	indexPtr->priv.lineNoRel = -1;
    }
    TkTextIndexSetByteIndex(indexPtr, byteIndex);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetSegment --
 *
 *	Set the segment pointer.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The byte index will be cleared.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexSetSegment(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    TkTextSegment *segPtr)	/* Pointer to segment. */
{
    assert(indexPtr->tree);
    assert(segPtr);
    assert(segPtr->typePtr);    /* expired? */
    assert(segPtr->sectionPtr); /* linked? */
    assert(CheckLine(indexPtr, segPtr->sectionPtr->linePtr));

    indexPtr->stateEpoch = TkBTreeEpoch(indexPtr->tree);
    indexPtr->priv.linePtr = segPtr->sectionPtr->linePtr;
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;
    indexPtr->priv.segPtr = segPtr;

    if (segPtr->typePtr == &tkTextCharType) {
	/* this segment is volatile, thus we need the byte index. */
	indexPtr->priv.byteIndex = SegToIndex(indexPtr->priv.linePtr, segPtr);
	indexPtr->priv.isCharSegment = true;
    } else {
	indexPtr->priv.byteIndex = -1;
	indexPtr->priv.isCharSegment = false;
    }

    assert(CheckByteIndex(indexPtr, segPtr->sectionPtr->linePtr, -1));
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetToStartOfLine --
 *
 *	Set this index to the start of the line.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexSetToStartOfLine(
    TkTextIndex *indexPtr)	/* Pointer to index. */
{
    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));

    indexPtr->priv.byteIndex = FindStartByteIndex(indexPtr);
    TkTextIndexSetEpoch(indexPtr, TkBTreeEpoch(indexPtr->tree));
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetToStartOfLine2 --
 *
 *	Set the new line pointer, and set this index to the start of the line.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexSetToStartOfLine2(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    TkTextLine *linePtr)	/* Pointer to line. */
{
    assert(indexPtr->tree);
    assert(linePtr);
    assert(linePtr->parentPtr); /* expired? */
    assert(CheckLine(indexPtr, linePtr));

    indexPtr->stateEpoch = TkBTreeEpoch(indexPtr->tree);
    indexPtr->priv.linePtr = linePtr;
    indexPtr->priv.segPtr = NULL;
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;
    indexPtr->priv.byteIndex = FindStartByteIndex(indexPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetToEndOfLine2 --
 *
 *	Set the new line pointer, and set this index to the end of the line.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexSetToEndOfLine2(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    TkTextLine *linePtr)	/* Pointer to line. */
{
    assert(indexPtr->tree);
    assert(linePtr);
    assert(linePtr->parentPtr); /* expired? */
    assert(linePtr->nextPtr);
    assert(CheckLine(indexPtr, linePtr->nextPtr));

    indexPtr->stateEpoch = TkBTreeEpoch(indexPtr->tree);
    indexPtr->priv.segPtr = NULL;
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;
    indexPtr->priv.linePtr = linePtr->nextPtr;
    indexPtr->priv.byteIndex = 0;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetToLastChar --
 *
 *	Set this index to one byte before the end of the line.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexSetToLastChar(
    TkTextIndex *indexPtr)	/* Pointer to index. */
{
    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */

    indexPtr->stateEpoch = TkBTreeEpoch(indexPtr->tree);
    indexPtr->priv.byteIndex = FindEndByteIndex(indexPtr);
    indexPtr->priv.segPtr = NULL;
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;

    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetupToStartOfText --
 *
 *	Setup this index to the start of the text.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexSetupToStartOfText(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    TkText *textPtr,		/* Text widget for this index, can be NULL. */
    TkTextBTree tree)		/* B-tree for this index. */
{
    assert(indexPtr);
    assert(tree);

    indexPtr->textPtr = textPtr;
    indexPtr->tree = tree;
    indexPtr->stateEpoch = TkBTreeEpoch(tree);
    indexPtr->priv.lineNo = textPtr ? -1 : 0;
    indexPtr->priv.lineNoRel = 0;
    indexPtr->priv.isCharSegment = false;
    DEBUG(indexPtr->discardConsistencyCheck = false);

    if (textPtr) {
	indexPtr->priv.segPtr = textPtr->startMarker;
	indexPtr->priv.linePtr = indexPtr->priv.segPtr->sectionPtr->linePtr;
	indexPtr->priv.byteIndex = FindStartByteIndex(indexPtr);
    } else {
	indexPtr->priv.segPtr = TkBTreeGetShared(tree)->startMarker;
	indexPtr->priv.linePtr = indexPtr->priv.segPtr->sectionPtr->linePtr;
	indexPtr->priv.byteIndex = 0;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexSetupToEndOfText --
 *
 *	Setup this index to the end of the text. If a peer is given,
 *	then this is the start of last line in this peer, otherwise
 *	it's the start of the very last line.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexSetupToEndOfText(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    TkText *textPtr,		/* Text widget for this index, can be NULL. */
    TkTextBTree tree)		/* B-tree for this index. */
{
    assert(indexPtr);
    assert(tree);

    indexPtr->textPtr = textPtr;
    indexPtr->tree = tree;
    indexPtr->stateEpoch = TkBTreeEpoch(tree);
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;
    DEBUG(indexPtr->discardConsistencyCheck = false);

    if (!textPtr) {
	indexPtr->priv.segPtr = TkBTreeGetShared(tree)->endMarker;
	indexPtr->priv.isCharSegment = false;
	indexPtr->priv.linePtr = indexPtr->priv.segPtr->sectionPtr->linePtr;
	indexPtr->priv.byteIndex = 0;
    } else {
	indexPtr->priv.linePtr = TkBTreeGetLastLine(textPtr);
	indexPtr->priv.segPtr = indexPtr->priv.linePtr->segPtr;
	indexPtr->priv.isCharSegment = indexPtr->priv.segPtr->typePtr == &tkTextCharType;
	indexPtr->priv.byteIndex = 0;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexGetByteIndex --
 *
 *	Get the byte index.
 *
 * Results:
 *	The byte index.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextIndexGetByteIndex(
    const TkTextIndex *indexPtr)	/* Pointer to index. */
{
    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */

    if (indexPtr->priv.byteIndex == -1) {
	assert(indexPtr->priv.segPtr);
	assert(!indexPtr->priv.isCharSegment || TkBTreeEpoch(indexPtr->tree) == indexPtr->stateEpoch);
	assert(indexPtr->priv.segPtr->typePtr);    /* expired? */
	assert(indexPtr->priv.segPtr->sectionPtr); /* linked? */
	assert(indexPtr->priv.segPtr->sectionPtr->linePtr == indexPtr->priv.linePtr);
	/* is mutable due to concept */
	((TkTextIndex *)indexPtr)->priv.byteIndex =
		SegToIndex(indexPtr->priv.linePtr, indexPtr->priv.segPtr);
    }
    return indexPtr->priv.byteIndex;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexToByteIndex --
 *
 *	Force the conversion from segment pointer to byte index. This
 *	will unset the segment pointer.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The segment pointer will be unset.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexToByteIndex(
    TkTextIndex *indexPtr)	/* Pointer to index. */
{
    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));

    if (indexPtr->priv.byteIndex == -1) {
	(void) TkTextIndexGetByteIndex(indexPtr);
    }
    indexPtr->priv.segPtr = NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexClear --
 *
 *	Clear all attributes, and set up the corresponding text pointer.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The given index will be in an invalid state, the TkIndexGet*
 *	functions cannot be used.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexClear(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    TkText *textPtr)		/* Overall information for text widget. */
{
    assert(textPtr);

    indexPtr->textPtr = textPtr;
    indexPtr->tree = textPtr->sharedTextPtr->tree;
    indexPtr->stateEpoch = 0;
    indexPtr->priv.linePtr = NULL;
    indexPtr->priv.segPtr = NULL;
    indexPtr->priv.byteIndex = -1;
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;
    indexPtr->priv.isCharSegment = false;
    DEBUG(indexPtr->discardConsistencyCheck = false);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexClear2 --
 *
 *	Clear all attributes, and set up the corresponding tree.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The given index will be in an invalid state, the TkIndexGet*
 *	functions cannot be used.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexClear2(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    TkText *textPtr,		/* Overall information for text widget, can be NULL */
    TkTextBTree tree)		/* B-tree for this index. */
{
    assert(textPtr || tree);
    assert(!textPtr || !tree || textPtr->sharedTextPtr->tree == tree);

    indexPtr->textPtr = textPtr;
    indexPtr->tree = tree ? tree : textPtr->sharedTextPtr->tree;
    indexPtr->stateEpoch = 0;
    indexPtr->priv.linePtr = NULL;
    indexPtr->priv.segPtr = NULL;
    indexPtr->priv.byteIndex = -1;
    indexPtr->priv.lineNo = -1;
    indexPtr->priv.lineNoRel = -1;
    indexPtr->priv.isCharSegment = false;
    DEBUG(indexPtr->discardConsistencyCheck = false);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexGetLineNumber --
 *
 *	Get the line number.
 *
 * Results:
 *	The line number.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

unsigned
TkTextIndexGetLineNumber(
    const TkTextIndex *indexPtr,
    const TkText *textPtr)	/* we want the line number belonging to this peer, can be NULL */
{
    unsigned epoch;
    int32_t *lineNo;

    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(!textPtr || indexPtr->textPtr == textPtr);

    lineNo = (int32_t *) (textPtr ? &indexPtr->priv.lineNoRel : &indexPtr->priv.lineNo);
    epoch = TkBTreeEpoch(indexPtr->tree);

    if (*lineNo == -1 || indexPtr->stateEpoch != epoch) {
	TkTextIndex *iPtr = (TkTextIndex *) indexPtr;

	if (iPtr->priv.byteIndex == -1) {
	    assert(iPtr->priv.segPtr);
	    assert(!iPtr->priv.isCharSegment || indexPtr->stateEpoch == epoch);
	    iPtr->priv.byteIndex = SegToIndex(iPtr->priv.linePtr, iPtr->priv.segPtr);
	    assert(CheckByteIndex(iPtr, iPtr->priv.linePtr, iPtr->priv.byteIndex));
	}
	TkTextIndexSetEpoch(iPtr, epoch);
	*lineNo = TkBTreeLinesTo(iPtr->tree, textPtr, iPtr->priv.linePtr, NULL);
    } else {
	assert(*lineNo == (int) TkBTreeLinesTo(indexPtr->tree, textPtr, indexPtr->priv.linePtr, NULL));
    }

    return *lineNo;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexRebuild --
 *
 *	Rebuild the index after possible modifications, it is required
 *	that TkTextIndexSave has been called before.
 *
 * Results:
 *	Returns whether the original line/byte position could be restored.
 *	This does not meean that we have the same content at this position,
 *	this only means that the we have the same position as before.
 *
 * Side effects:
 *	Adjust the line and the byte offset, if required.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexRebuild(
    TkTextIndex *indexPtr)
{
    TkTextLine *linePtr;
    int byteIndex;
    int lineNo;
    bool rc;

    assert(indexPtr->tree);
    assert(indexPtr->priv.lineNo >= 0 || indexPtr->priv.lineNoRel >= 0);
    assert(indexPtr->priv.byteIndex >= 0);

    if (indexPtr->stateEpoch == TkBTreeEpoch(indexPtr->tree)) {
	return true; /* still up-to-date */
    }

    if (indexPtr->priv.lineNo >= 0) {
	lineNo = MIN(TkBTreeNumLines(indexPtr->tree, NULL), indexPtr->priv.lineNo);
	linePtr = TkBTreeFindLine(indexPtr->tree, NULL, lineNo);
	indexPtr->priv.lineNo = lineNo;
    } else {
	lineNo = MIN(TkBTreeNumLines(indexPtr->tree, indexPtr->textPtr), indexPtr->priv.lineNoRel);
	linePtr = TkBTreeFindLine(indexPtr->tree, indexPtr->textPtr, lineNo);
	indexPtr->priv.lineNoRel = lineNo;
    }

    if (!(rc = (linePtr == indexPtr->priv.linePtr))) {
	indexPtr->priv.linePtr = linePtr;
    }
    byteIndex = MIN(indexPtr->priv.byteIndex, FindEndByteIndex(indexPtr));
    if (byteIndex != indexPtr->priv.byteIndex) {
	rc = false;
    }
    indexPtr->priv.byteIndex = byteIndex;
    indexPtr->priv.segPtr = NULL;

    return rc;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexRestrictToStartRange --
 *
 *	If given index is beyond the range of the widget (at left side),
 *	then this index will be set to start range.
 *
 * Results:
 *	Returns -1 if the index is earlier than start of range, 0 if index
 *	is at start of range, and +1 if index is after start of range.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextIndexRestrictToStartRange(
    TkTextIndex *indexPtr)
{
    TkText *textPtr = indexPtr->textPtr;
    TkTextIndex start;
    int cmp;

    assert(indexPtr->tree);

    if (!textPtr || textPtr->startMarker == textPtr->sharedTextPtr->startMarker) {
	return TkTextIndexIsStartOfText(indexPtr) ? 0 : 1;
    }

    start = *indexPtr;
    TkTextIndexSetSegment(&start, textPtr->startMarker);

    if ((cmp = TkTextIndexCompare(indexPtr, &start)) < 0) {
	*indexPtr = start;
	cmp = -1;
    }

    return cmp;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexRestrictToEndRange --
 *
 *	If given index is beyond the range of the widget (at right side),
 *	then this index will be set to end range.
 *
 * Results:
 *	Returns +1 if the index has exceeded the range, 0 if index was at
 *	end of range, and -1 if index is earlier than end of range.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextIndexRestrictToEndRange(
    TkTextIndex *indexPtr)
{
    TkText *textPtr = indexPtr->textPtr;
    TkTextIndex last;
    int cmp;

    assert(indexPtr->tree);

    if (!textPtr || textPtr->endMarker == textPtr->sharedTextPtr->endMarker) {
	return TkTextIndexIsEndOfText(indexPtr) ? 0 : -1;
    }

    last = *indexPtr;
    TkTextIndexSetByteIndex2(&last, TkBTreeGetLastLine(textPtr), 0);

    if ((cmp = TkTextIndexCompare(indexPtr, &last)) > 0) {
	*indexPtr = last;
	cmp = 1;
    } else if (cmp < 0) {
	TkTextIndex end = *indexPtr;
	TkTextIndexSetSegment(&end, textPtr->endMarker);
	if (TkTextIndexCompare(indexPtr, &end) > 0) {
	    *indexPtr = last;
	    cmp = 0;
	} else {
	    cmp = -1;
	}
    }

    return cmp;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexEnsureBeforeLastChar --
 *
 *	If given index is on last line, then this index will be set to
 *	the position of the last character in second last line.
 *
 * Results:
 *	Returns 'true' if the index is now before last character position.
 *	This is not possible if the peer is empty, and in this case this
 *	function returns 'false'.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexEnsureBeforeLastChar(
    TkTextIndex *indexPtr)
{
    TkText *textPtr = indexPtr->textPtr;
    const TkTextLine *lastLinePtr;

    assert(indexPtr->tree);
    assert(indexPtr->textPtr);

    if (TkTextIsDeadPeer(indexPtr->textPtr)) {
        return false;
    }

    lastLinePtr = TkBTreeGetLastLine(textPtr);

    if (lastLinePtr == indexPtr->priv.linePtr
	    && (!textPtr || lastLinePtr != textPtr->startMarker->sectionPtr->linePtr)) {
	TkTextIndexSetToLastChar2(indexPtr, lastLinePtr->prevPtr);
    }

    return true;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexGetContentSegment --
 *
 *	Get the pointer to the segment at this byte position which
 *	contains any content (chars, image, or window).
 *
 *	This is the equivalent to the older (and eliminated) function
 *	TkTextIndexToSeg.
 *
 * Results:
 *	Pointer to a segment with size > 0.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

TkTextSegment *
TkTextIndexGetContentSegment(
    const TkTextIndex *indexPtr,/* Pointer to index. */
    int *offset)		/* Get offset in segment, can be NULL. */
{
    TkTextSegment *segPtr;

    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */

    if ((segPtr = indexPtr->priv.segPtr)
	    && (!indexPtr->priv.isCharSegment || TkBTreeEpoch(indexPtr->tree) == indexPtr->stateEpoch)) {
	while (segPtr->size == 0) {
	    segPtr = segPtr->nextPtr;
	}

	if (offset) {
	    if (indexPtr->priv.byteIndex == -1) {
		*offset = 0;
	    } else {
		int byteIndex = SegToIndex(indexPtr->priv.linePtr, segPtr);
		assert(byteIndex <= indexPtr->priv.byteIndex);
		assert(indexPtr->priv.byteIndex < byteIndex + segPtr->size);
		*offset = indexPtr->priv.byteIndex - byteIndex;
	    }
	    assert(*offset >= 0);
	    assert(*offset < segPtr->size);
	}
    } else {
	int myOffset;

	assert(indexPtr->priv.byteIndex >= 0);
	segPtr = IndexToSeg(indexPtr, &myOffset);
	if (myOffset == 0) {
	    TkTextIndex *iPtr = (TkTextIndex *) indexPtr; /* mutable due to concept */
	    iPtr->priv.segPtr = segPtr;
	    iPtr->priv.isCharSegment = segPtr->typePtr == &tkTextCharType;
	}
	if (offset) {
	    *offset = myOffset;
	}
    }

    return segPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexGetFirstSegment --
 *
 *	Get the pointer to first segment at this byte position.
 *
 * Results:
 *	Pointer to a segment.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

TkTextSegment *
TkTextIndexGetFirstSegment(
    const TkTextIndex *indexPtr,/* Pointer to index. */
    int *offset)		/* Get offset in segment, can be NULL. */
{
    TkTextSegment *segPtr;
    TkTextSegment *prevPtr;
    int myOffset;

    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */

    if ((segPtr = indexPtr->priv.segPtr)
	    && (!indexPtr->priv.isCharSegment || TkBTreeEpoch(indexPtr->tree) == indexPtr->stateEpoch)) {
	if (indexPtr->priv.byteIndex >= 0) {
	    myOffset = indexPtr->priv.byteIndex - SegToIndex(indexPtr->priv.linePtr, segPtr);
	    assert(myOffset >= 0);
	    assert(segPtr->size == 0 || myOffset < segPtr->size);
	} else {
	    myOffset = 0;
	}
    } else {
	assert(indexPtr->priv.byteIndex >= 0);
	segPtr = IndexToSeg(indexPtr, &myOffset);
    }

    assert(segPtr->typePtr);    /* expired? */
    assert(segPtr->sectionPtr); /* linked? */
    assert(segPtr->sectionPtr->linePtr == indexPtr->priv.linePtr);

    if (myOffset == 0) {
	TkTextIndex *iPtr = (TkTextIndex *) indexPtr; /* mutable due to concept */

	while ((prevPtr = segPtr->prevPtr) && prevPtr->size == 0) {
	    segPtr = prevPtr;
	}

	iPtr->priv.segPtr = segPtr;
	iPtr->priv.isCharSegment = segPtr->typePtr == &tkTextCharType;
    }
    if (offset) {
	*offset = myOffset;
    }

    return segPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexIsStartOfLine --
 *
 *	Test whether this index refers to the start of a line.
 *
 * Results:
 *	Returns true if the start of a line is referred, zero otherwise.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexIsStartOfLine(
    const TkTextIndex *indexPtr)
{
    const TkTextSegment *segPtr;
    const TkTextSegment *startPtr;

    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));

    if (indexPtr->priv.byteIndex >= 0) {
	return FindStartByteIndex(indexPtr) == indexPtr->priv.byteIndex;
    }

    assert(indexPtr->priv.segPtr);
    assert(!indexPtr->priv.isCharSegment || TkBTreeEpoch(indexPtr->tree) == indexPtr->stateEpoch);
    assert(CheckByteIndex(indexPtr, indexPtr->priv.linePtr, -1));

    startPtr = indexPtr->textPtr ? indexPtr->textPtr->startMarker : NULL;
    segPtr = indexPtr->priv.segPtr;
    if (segPtr->size > 0) {
	segPtr = segPtr->prevPtr;
    }
    while (segPtr && segPtr->size == 0) {
	if (segPtr == startPtr) {
	    return true;
	}
	segPtr = segPtr->prevPtr;
    }

    return !segPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexIsEndOfLine --
 *
 *	Test whether this index refers to the end of the line.
 *
 * Results:
 *	Returns true if the end of the line is referred, false otherwise.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexIsEndOfLine(
    const TkTextIndex *indexPtr)
{
    const TkTextSegment *segPtr;
    const TkTextSegment *endPtr;

    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));
    assert(CheckByteIndex(indexPtr, indexPtr->priv.linePtr, -1));

    if (indexPtr->priv.byteIndex >= 0) {
	return indexPtr->priv.byteIndex == FindEndByteIndex(indexPtr);
    }

    assert(indexPtr->priv.segPtr);
    assert(!indexPtr->priv.isCharSegment || TkBTreeEpoch(indexPtr->tree) == indexPtr->stateEpoch);

    if (indexPtr->priv.linePtr == TkBTreeGetLastLine(indexPtr->textPtr)) {
	return true;
    }

    segPtr = indexPtr->priv.segPtr;

    if (DontNeedSpecialEndLineTreatment(indexPtr)) {
	while (segPtr->size == 0) {
	    segPtr = segPtr->nextPtr;
	}
	return segPtr->size == 1 && segPtr == indexPtr->priv.linePtr->lastPtr;
    }

    assert(indexPtr->textPtr);
    assert(indexPtr->textPtr->endMarker != indexPtr->textPtr->sharedTextPtr->endMarker);

    endPtr = indexPtr->textPtr->endMarker;
    while (segPtr->size == 0) {
	if (segPtr == endPtr) {
	    return true;
	}
	segPtr = segPtr->nextPtr;
    }

    return false;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexIsStartOfText --
 *
 *	Test whether this index refers to the start of the text.
 *
 * Results:
 *	Returns true if the start of the text is referred, false otherwise.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexIsStartOfText(
    const TkTextIndex *indexPtr)
{
    const TkText *textPtr = indexPtr->textPtr;
    const TkTextSegment *segPtr;

    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));
    assert(CheckByteIndex(indexPtr, indexPtr->priv.linePtr, -1));

    segPtr = textPtr ? textPtr->startMarker : TkBTreeGetShared(indexPtr->tree)->startMarker;
    return indexPtr->priv.linePtr == segPtr->sectionPtr->linePtr && TkTextIndexIsStartOfLine(indexPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexIsEndOfText --
 *
 *	Test whether this index refers to the end of the text.
 *
 * Results:
 *	Returns true if the end of the text is referred, false otherwise.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexIsEndOfText(
    const TkTextIndex *indexPtr)
{
    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));
    assert(CheckByteIndex(indexPtr, indexPtr->priv.linePtr, -1));

    if (indexPtr->textPtr) {
	return indexPtr->priv.linePtr == TkBTreeGetLastLine(indexPtr->textPtr);
    }
    return !indexPtr->priv.linePtr->nextPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexIsEqual --
 *
 *	Test whether both given indicies are referring the same byte
 *	index. Such a test makes sense only if both indices are
 *	belonging to the same line.
 *
 * Results:
 *	Return true if both indices are equal, otherwise false will be returned.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexIsEqual(
    const TkTextIndex *indexPtr1,	/* Pointer to index. */
    const TkTextIndex *indexPtr2)	/* Pointer to index. */
{
    const TkTextSegment *segPtr1;
    const TkTextSegment *segPtr2;

    assert(indexPtr1->priv.linePtr);
    assert(indexPtr2->priv.linePtr);
    assert(indexPtr1->priv.linePtr->parentPtr); /* expired? */
    assert(indexPtr2->priv.linePtr->parentPtr); /* expired? */

    if (indexPtr1->priv.linePtr != indexPtr2->priv.linePtr) {
	return false;
    }

    if ((segPtr1 = TkTextIndexGetSegment(indexPtr1))) {
	if ((segPtr2 = TkTextIndexGetSegment(indexPtr2))) {
	    while (segPtr1->prevPtr && segPtr1->prevPtr->size == 0) {
		segPtr1 = segPtr1->prevPtr;
	    }
	    while (segPtr2->prevPtr && segPtr2->prevPtr->size == 0) {
		segPtr2 = segPtr2->prevPtr;
	    }
	    return segPtr1 == segPtr2;
	}
    }

    return TkTextIndexGetByteIndex(indexPtr1) == TkTextIndexGetByteIndex(indexPtr2);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexCompare --
 *
 *	Compare two indicies.
 *
 * Results:
 *	It returns an integer less than, equal to, or greater than zero if
 *	indexPtr1 is found, respectively, to be less than, to match, or be
 *	greater than indexPtr2.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextIndexCompare(
    const TkTextIndex *indexPtr1,	/* Pointer to index. */
    const TkTextIndex *indexPtr2)	/* Pointer to index. */
{
    const TkTextSection *sectionPtr1;
    const TkTextSection *sectionPtr2;
    const TkTextSegment *segPtr1;
    const TkTextSegment *segPtr2;

    assert(indexPtr1->priv.linePtr);
    assert(indexPtr2->priv.linePtr);
    assert(indexPtr1->priv.linePtr->parentPtr); /* expired? */
    assert(indexPtr2->priv.linePtr->parentPtr); /* expired? */

    if (indexPtr1->priv.linePtr != indexPtr2->priv.linePtr) {
	int lineNo1 = TkTextIndexGetLineNumber(indexPtr1, NULL);
	int lineNo2 = TkTextIndexGetLineNumber(indexPtr2, NULL);

	return lineNo1 - lineNo2;
    }
    if (indexPtr1->priv.byteIndex >= 0 && indexPtr2->priv.byteIndex >= 0) {
	return indexPtr1->priv.byteIndex - indexPtr2->priv.byteIndex;
    }

    if (!(segPtr1 = TkTextIndexGetSegment(indexPtr1)) || !(segPtr2 = TkTextIndexGetSegment(indexPtr2))) {
	return TkTextIndexGetByteIndex(indexPtr1) - TkTextIndexGetByteIndex(indexPtr2);
    }

    assert(!indexPtr1->priv.isCharSegment || TkBTreeEpoch(indexPtr1->tree) == indexPtr1->stateEpoch);
    assert(!indexPtr2->priv.isCharSegment || TkBTreeEpoch(indexPtr2->tree) == indexPtr2->stateEpoch);

    segPtr1 = indexPtr1->priv.segPtr;
    segPtr2 = indexPtr2->priv.segPtr;
    while (segPtr1->size == 0) {
	segPtr1 = segPtr1->nextPtr;
    }
    while (segPtr2->size == 0) {
	segPtr2 = segPtr2->nextPtr;
    }
    if (segPtr1 == segPtr2) {
	return 0;
    }
    sectionPtr1 = indexPtr1->priv.segPtr->sectionPtr;
    sectionPtr2 = indexPtr2->priv.segPtr->sectionPtr;
    if (sectionPtr1 != sectionPtr2) {
	while (sectionPtr1 && sectionPtr1 != sectionPtr2) {
	    sectionPtr1 = sectionPtr1->nextPtr;
	}
	return sectionPtr1 ? -1 : +1;
    }
    segPtr1 = indexPtr1->priv.segPtr;
    segPtr2 = indexPtr2->priv.segPtr;
    while (segPtr1 != segPtr2) {
	if (!(segPtr1 = segPtr1->nextPtr) || segPtr1->sectionPtr != sectionPtr1) {
	    return +1;
	}
    }
    return -1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexAddToByteIndex --
 *
 *	Add given byte offset to byte index.
 *
 *	Note that this function allows that the byte index will reach the
 *	size of the line, in this case the line will be advanced, and the
 *	byte index will be set to zero.
 *
 * Results:
 *	Returns whether we're on same line.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

bool
TkTextIndexAddToByteIndex(
    TkTextIndex *indexPtr,	/* Pointer to index. */
    int byteOffset)		/* Add this offset. */
{
    bool rc = true;

    assert(indexPtr->tree);
    assert(indexPtr->priv.linePtr);
    assert(indexPtr->priv.linePtr->parentPtr); /* expired? */
    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));
    assert(CheckByteIndex(indexPtr, indexPtr->priv.linePtr, -1));

    if (byteOffset == 0) {
	return true;
    }

    if (indexPtr->priv.byteIndex == -1) {
	(void) TkTextIndexGetByteIndex(indexPtr);
    }

    if (byteOffset > 0) {
	if ((indexPtr->priv.byteIndex += byteOffset) > FindEndByteIndex(indexPtr)) {
	    assert(indexPtr->priv.linePtr->nextPtr);
	    assert(indexPtr->priv.byteIndex <= indexPtr->priv.linePtr->size);
	    indexPtr->priv.linePtr = indexPtr->priv.linePtr->nextPtr;
	    if (indexPtr->priv.lineNo >= 0) {
		indexPtr->priv.lineNo += 1;
	    }
	    if (indexPtr->priv.lineNoRel >= 0) {
		indexPtr->priv.lineNoRel += 1;
	    }
	    indexPtr->priv.byteIndex = 0;
	    rc = false;
	}
    } else {
	assert(-byteOffset <= indexPtr->priv.byteIndex);
	indexPtr->priv.byteIndex += byteOffset;
    }

    indexPtr->priv.segPtr = NULL;

    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));
    assert(CheckByteIndex(indexPtr, indexPtr->priv.linePtr, -1));

    return rc;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkpTextIndexDump --
 *
 *	This function is for debugging only, printing the given index
 *	on stdout.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */
#ifndef NDEBUG

void
TkpTextIndexDump(
    TkText *textPtr,		/* May be NULL. */
    const TkTextIndex *indexPtr)/* Pointer to index. */
{
    char buf[TK_POS_CHARS];
    TkTextIndexPrint(TkTextIndexGetShared(indexPtr), textPtr, indexPtr, buf);
    fprintf(stdout, "%s\n", buf);
}

#endif /* NDEBUG */

/*
 *---------------------------------------------------------------------------
 *
 * TkTextNewIndexObj --
 *
 *	This function generates a Tcl_Obj description of an index, suitable
 *	for reading in again later. The index generated is effectively stable
 *	to all except insertion/deletion operations on the widget.
 *
 * Results:
 *	A new Tcl_String with refCount zero.
 *
 * Side effects:
 *	A small amount of memory is allocated.
 *
 *---------------------------------------------------------------------------
 */

Tcl_Obj *
TkTextNewIndexObj(
    const TkTextIndex *indexPtr)/* Pointer to index. */
{
    char buffer[TK_POS_CHARS];
    int len;

    assert(indexPtr->textPtr);

    len = TkTextPrintIndex(indexPtr->textPtr, indexPtr, buffer);
    return Tcl_NewStringObj(buffer, len);
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextMakeByteIndex --
 *
 *	Given a line index and a byte index, look things up in the B-tree and
 *	fill in a TkTextIndex structure.
 *
 * Results:
 *	The structure at *indexPtr is filled in with information about the
 *	character at lineIndex and byteIndex (or the closest existing
 *	character, if the specified one doesn't exist), and indexPtr is
 *	returned as result.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

TkTextIndex *
TkTextMakeByteIndex(
    TkTextBTree tree,		/* Tree that lineIndex and byteIndex refer TkTextBTree tree, to. */
    const TkText *textPtr,	/* Client that lineIndex and byteIndex refer to, can be NULL. */
    int lineIndex,		/* Index of desired line (0 means first line of text). */
    int byteIndex,		/* Byte index of desired character. */
    TkTextIndex *indexPtr)	/* Structure to fill in. */
{
    TkTextSegment *segPtr;
    TkTextSection *sectionPtr;
    TkTextLine *linePtr;
    int index, nextIndex;

    TkTextIndexClear2(indexPtr, (TkText *) textPtr, tree);

    if (lineIndex < 0) {
	TkTextIndexSetupToStartOfText(indexPtr, (TkText *) textPtr, tree);
	return indexPtr;
    }

    if (!(linePtr = TkBTreeFindLine(tree, textPtr, lineIndex))) {
	TkTextIndexSetupToEndOfText(indexPtr, (TkText *) textPtr, tree);
	return indexPtr;
    }

    if (byteIndex < 0) {
	byteIndex = 0;
    }

    if (textPtr) {
	if (textPtr->startMarker != textPtr->sharedTextPtr->startMarker
		&& textPtr->startMarker->sectionPtr->linePtr == linePtr) {
	    int startByteIndex;

	    TkTextIndexSetSegment(indexPtr, textPtr->startMarker);
	    startByteIndex = FindStartByteIndex(indexPtr);
	    if (byteIndex <= startByteIndex) {
		return indexPtr;
	    }
	}
	if (textPtr->endMarker != textPtr->sharedTextPtr->endMarker
		&& textPtr->endMarker->sectionPtr->linePtr == linePtr) {
	    int endByteIndex;

	    TkTextIndexSetSegment(indexPtr, textPtr->endMarker);
	    endByteIndex = FindEndByteIndex(indexPtr);
	    if (endByteIndex <= byteIndex) {
		return indexPtr;
	    }
	}
    }

    indexPtr->priv.linePtr = linePtr;

    if (byteIndex == 0) {
	/* this is catching a frequent case */
	TkTextIndexSetByteIndex(indexPtr, 0);
	return indexPtr;
    }

    if (byteIndex >= linePtr->size) {
	/*
	 * Use the index of the last character in the line. Since the last
	 * character on the line is guaranteed to be a '\n', we can back
	 * up one byte.
	 *
	 * Note that it is already guaranteed that we do not exceed the position
	 * of the end marker.
	 */
	TkTextIndexSetByteIndex(indexPtr, linePtr->size - 1);
	return indexPtr;
    }

    indexPtr->priv.byteIndex = byteIndex;
    index = 0;

    sectionPtr = linePtr->segPtr->sectionPtr;
    while ((nextIndex = index + sectionPtr->size) <= byteIndex) {
	index = nextIndex;
	sectionPtr = sectionPtr->nextPtr;
	assert(sectionPtr);
    }

    segPtr = sectionPtr->segPtr;
    while ((nextIndex = index + segPtr->size) < byteIndex) {
	index = nextIndex;
	segPtr = segPtr->nextPtr;
	assert(segPtr);
    }

    /*
     * Verify that the index points to a valid character boundary.
     */

    if (segPtr->typePtr == &tkTextCharType && byteIndex > index && index + segPtr->size > byteIndex) {
	const char *p = segPtr->body.chars + (byteIndex - index);

	/*
	 * Prevent UTF-8 character from being split up by ensuring that byteIndex
	 * falls on a character boundary. If index falls in the middle of a UTF-8
	 * character, it will be adjusted to the end of that UTF-8 character.
	 */

	while ((*p & 0xc0) == 0x80) {
	    ++p;
	    indexPtr->priv.byteIndex += 1;
	}
    }

    return indexPtr;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextMakeCharIndex --
 *
 *	Given a line index and a character index, look things up in the B-tree
 *	and fill in a TkTextIndex structure.
 *
 * Results:
 *	The structure at *indexPtr is filled in with information about the
 *	character at lineIndex and charIndex (or the closest existing
 *	character, if the specified one doesn't exist), and indexPtr is
 *	returned as result.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static unsigned
CountCharsInSeg(
    const TkTextSegment *segPtr)
{
    assert(segPtr->typePtr == &tkTextCharType);
    return Tcl_NumUtfChars(segPtr->body.chars, segPtr->size);
}

TkTextIndex *
TkTextMakeCharIndex(
    TkTextBTree tree,		/* Tree that lineIndex and charIndex refer to. */
    TkText *textPtr,		/* Client that lineIndex and charIndex refer to, can be NULL. */
    int lineIndex,		/* Index of desired line (0 means first line of text). */
    int charIndex,		/* Index of desired character. */
    TkTextIndex *indexPtr)	/* Structure to fill in. */
{
    TkTextSegment *segPtr, *lastPtr;
    TkTextLine *linePtr;
    char *p, *start, *end;
    int index, offset;

    TkTextIndexClear2(indexPtr, textPtr, tree);

    if (lineIndex < 0) {
	TkTextIndexSetupToStartOfText(indexPtr, textPtr, tree);
	return indexPtr;
    }

    if (!(linePtr = TkBTreeFindLine(tree, textPtr, lineIndex))) {
	TkTextIndexSetupToEndOfText(indexPtr, textPtr, tree);
	return indexPtr;
    }

    indexPtr->priv.linePtr = linePtr;

    if (charIndex >= linePtr->size - 1) {
	/* this is catching a frequent case */
	TkTextIndexSetToLastChar(indexPtr);
	return indexPtr;
    }

    if (charIndex <= 0) {
	/* this is catching a frequent case */
	TkTextIndexSetToStartOfLine(indexPtr);
	return indexPtr;
    }

    if (textPtr && textPtr->endMarker->sectionPtr->linePtr == linePtr) {
	lastPtr = textPtr->endMarker;
    } else {
	lastPtr = NULL;
    }

    if (!textPtr
	    || textPtr->startMarker == TkBTreeGetShared(indexPtr->tree)->startMarker
	    || linePtr != textPtr->startMarker->sectionPtr->linePtr) {
	segPtr = linePtr->segPtr;
	index = 0;
    } else {
	TkTextSegment *startPtr;

	/*
	 * We have to skip some segments not belonging to this peer.
	 */

	TkTextIndexSetSegment(indexPtr, textPtr->startMarker);
	startPtr = TkTextIndexGetFirstSegment(indexPtr, NULL);

	for (segPtr = linePtr->segPtr; segPtr != startPtr; segPtr = segPtr->nextPtr) {
	    if (segPtr->typePtr == &tkTextCharType) {
		charIndex -= CountCharsInSeg(segPtr);
	    } else {
		assert(segPtr->size <= 1);
		charIndex -= segPtr->size;
	    }
	    if (charIndex <= 0) {
		return indexPtr;
	    }
	}

	index = TkTextIndexGetByteIndex(indexPtr);
	indexPtr->priv.segPtr = NULL;
    }

    /*
     * Verify that the index is within the range of the line. If not, just use
     * the index of the last character in the line.
     */

    while (segPtr != lastPtr) {
	if (segPtr->tagInfoPtr) {
	    if (segPtr->typePtr == &tkTextCharType) {
		/*
		 * Turn character offset into a byte offset.
		 */

		start = segPtr->body.chars;
		end = start + segPtr->size;

		for (p = start; p < end; p += offset) {
		    if (charIndex == 0) {
			indexPtr->priv.byteIndex = index;
			return indexPtr;
		    }
		    charIndex -= 1;
		    { /* local scope */
#if TCL_UTF_MAX > 4
			/*
			 * HACK: Support of pseudo UTF-8 strings. Needed because of this
			 * bad hack with TCL_UTF_MAX > 4, the whole thing is amateurish.
			 * (See function GetLineBreakFunc() about the very severe problems
			 * with TCL_UTF_MAX > 4).
			 */

			int ch;
			offset = TkUtfToUniChar(p, &ch);
#else
			/*
			 * Proper implementation for UTF-8 strings:
			 */

			Tcl_UniChar ch;
			offset = Tcl_UtfToUniChar(p, &ch);
#endif
		    }
		    index += offset;
		}
	    } else if (charIndex < segPtr->size) {
		indexPtr->priv.byteIndex = index;
		return indexPtr;
	    } else {
		assert(segPtr->size == 1);
		charIndex -= 1;
		index += 1;
	    }
	}
	if (!(segPtr = segPtr->nextPtr)) {
	    /*
	     * Use the index of the last character in the line.
	     */
	    TkTextIndexSetToLastChar(indexPtr);
	    return indexPtr;
	}
    }

    indexPtr->priv.byteIndex = index;
    return indexPtr;
}

/*
 *---------------------------------------------------------------------------
 *
 * IndexToSeg --
 *
 *	Given an index, this function returns the segment and offset within
 *	segment for the index.
 *
 * Results:
 *	The return value is a pointer to the segment referred to by indexPtr;
 *	this will always be a segment with non-zero size. The variable at
 *	*offsetPtr is set to hold the integer offset within the segment of the
 *	character given by indexPtr.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static TkTextSegment *
IndexToSeg(
    const TkTextIndex *indexPtr,/* Text index. */
    int *offsetPtr)		/* Where to store offset within segment, or NULL if offset isn't
    				 * wanted. */
{
    TkTextSection *sectionPtr;
    TkTextSegment *segPtr;
    TkTextLine *linePtr;
    int index;

    assert(indexPtr->priv.byteIndex >= 0);
    assert(indexPtr->priv.byteIndex < indexPtr->priv.linePtr->size);

    index = indexPtr->priv.byteIndex;
    linePtr = indexPtr->priv.linePtr;

    /*
     * Speed up a frequent use case.
     */

    if (index == 0) {
	segPtr = linePtr->segPtr;
	while (segPtr->size == 0) {
	    segPtr = segPtr->nextPtr;
	    assert(segPtr);
	}
	if (offsetPtr) {
	    *offsetPtr = 0;
	}
	return segPtr;
    }

    /*
     * Speed up a frequent use case.
     */

    if (index == linePtr->size - 1) {
	assert(linePtr->lastPtr->typePtr == &tkTextCharType);
	if (offsetPtr) {
	    *offsetPtr = linePtr->lastPtr->size - 1;
	}
	return linePtr->lastPtr;
    }

    /*
     * Now we iterate through the section an segment structure until we reach the
     * wanted byte index.
     */

    sectionPtr = linePtr->segPtr->sectionPtr;
    for ( ; index >= sectionPtr->size; sectionPtr = sectionPtr->nextPtr) {
	index -= sectionPtr->size;
	assert(sectionPtr->nextPtr);
    }
    for (segPtr = sectionPtr->segPtr; index >= segPtr->size; segPtr = segPtr->nextPtr) {
	index -= segPtr->size;
	assert(segPtr->nextPtr);
    }
    assert(segPtr->size > 0);

    if (offsetPtr) {
	*offsetPtr = index;
    }
    return segPtr;
}

/*
 *---------------------------------------------------------------------------
 *
 * SegToIndex --
 *
 *	Given a segment pointer, this function returns the offset of the
 *	segment within its line.
 *
 *	This function assumes that we want the index to the current line,
 *	and not the index from the start of the logical line.
 *
 * Results:
 *	The return value is the offset (within its line) of the first
 *	character in segPtr.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static int
SegToIndex(
    const TkTextLine *linePtr,
    const TkTextSegment *segPtr)/* Segment whose offset is desired. */
{
    const TkTextSection *sectionPtr;
    const TkTextSegment *segPtr2;
    int offset;

    assert(segPtr->sectionPtr); /* otherwise not linked */
    assert(segPtr->sectionPtr->linePtr == linePtr);

    sectionPtr = linePtr->segPtr->sectionPtr; /* first segment in line */

    /*
     * Speed up frequent use cases.
     */

    if (segPtr == sectionPtr->segPtr) {
	return 0;
    }

    if (segPtr == linePtr->lastPtr) {
	return linePtr->size - segPtr->size;
    }

    /*
     * Now we iterate through the section an segment structure until we reach the
     * given segment.
     */

    offset = 0;

    for ( ; sectionPtr != segPtr->sectionPtr; sectionPtr = sectionPtr->nextPtr) {
	offset += sectionPtr->size;
	assert(sectionPtr->nextPtr);
    }
    for (segPtr2 = segPtr->sectionPtr->segPtr; segPtr2 != segPtr; segPtr2 = segPtr2->nextPtr) {
	offset += segPtr2->size;
	assert(segPtr2->nextPtr);
    }

    return offset;
}
/*
 *---------------------------------------------------------------------------
 *
 * TkTextSegToIndex --
 *
 *	Given a segment pointer, this function returns the offset of the
 *	segment within its line.
 *
 *	This function assumes that we want the index to the current line,
 *	and not the index from the start of the logical line.
 *
 * Results:
 *	The return value is the offset (within its line) of the first
 *	character in segPtr.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

int
TkTextSegToIndex(
    const TkTextSegment *segPtr)/* Segment whose offset is desired. */
{
    return SegToIndex(segPtr->sectionPtr->linePtr, segPtr);
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextGetIndex --
 *
 *	Given a string, return the index that is described.
 *
 * Results:
 *	The return value is a standard Tcl return result. If TCL_OK is
 *	returned, then everything went well and the index at *indexPtr is
 *	filled in; otherwise TCL_ERROR is returned and an error message is
 *	left in the interp's result.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

int
TkTextGetIndex(
    Tcl_Interp *interp,		/* Use this for error reporting. */
    TkText *textPtr,		/* Information about text widget. */
    const char *string,		/* Textual description of position. */
    TkTextIndex *indexPtr)	/* Index structure to fill in. */
{
    assert(textPtr);
    assert(string);

    return TkpTextGetIndex(interp, textPtr->sharedTextPtr, textPtr, string, strlen(string), indexPtr) ?
	    TCL_OK : TCL_ERROR;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkpTextGetIndex --
 *
 *	Given a string, return the index that is described.
 *
 * Results:
 *	If 'true' is returned, then everything went well and the index at
 *	*indexPtr is filled in; otherwise 'false' is returned and an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static unsigned
SkipSegments(
    TkTextSegment *startMarkPtr)
{
    TkTextSegment *segPtr = startMarkPtr->sectionPtr->linePtr->segPtr;
    unsigned charIndex = 0;

    /* Skip chars not belonging to this text widget. */

    for ( ; segPtr != startMarkPtr; segPtr = segPtr->nextPtr) {
	if (segPtr->tagInfoPtr) {
	    charIndex += (segPtr->typePtr == &tkTextCharType) ? CountCharsInSeg(segPtr) : 1;
	}
    }

    return charIndex;
}

bool
TkpTextGetIndex(
    Tcl_Interp *interp,		/* Use this for error reporting. */
    TkSharedText *sharedTextPtr,/* Pointer to shared resource. */
    TkText *textPtr,		/* Information about text widget. */
    const char *string,		/* Textual description of position. */
    unsigned lenOfString,	/* Length of textual description. */
    TkTextIndex *indexPtr)	/* Index structure to fill in. */
{
    char *p, *end, *endOfBase;
    TkTextIndex first, last;
    char c;
    const char *cp;
    char *myString;
    Tcl_DString copy;
    Tcl_HashEntry *hPtr;
    TkTextTag *tagPtr;
    bool skipMark;
    bool wantLast;
    bool wantCurrent;
    bool result;
    int charCount = -1;

    assert(textPtr);
    assert(sharedTextPtr);

    /*
     * The documentation about indices says:
     *
     *	The base for an index must have one of the following forms:
     *
     *		<line>.<char>
     *		@<x>,<y>
     *		begin
     *		end
     *		<mark>
     *		<tag>.first
     *		<tag>.last
     *		<tag>.current.first
     *		<tag>.current.last
     *		<pathName>
     *		<imageName>
     *
     * Furthermore the documentation says:
     *
     *	If the base could match more than one of the above forms, such as a mark and imageName
     *	both having the same value, then the form earlier in the above list takes precedence.
     */

#if BEGIN_DOES_NOT_BELONG_TO_BASE
    /*
     *------------------------------------------------
     * Stage 0: for portability reasons keyword "begin" has the lowest
     * precedence (but this should be corrected in a future version).
     *------------------------------------------------
     */

    if (string[0] == 'b' && strncmp(string, "begin", 5)) {
	if (TkTextMarkNameToIndex(textPtr, string, indexPtr)
		|| TkTextWindowIndex(textPtr, string, indexPtr)
		|| TkTextImageIndex(textPtr, string, indexPtr)) {
	    return true;
	}
    }
#endif /* BEGIN_DOES_NOT_BELONG_TO_BASE */

    /*
     *------------------------------------------------
     * Stage 1: start by parsing the base index.
     *------------------------------------------------
     */

    TkTextIndexClear(indexPtr, textPtr);

    /*
     * First look for the form "tag.first", "tag.last", and then for "tag.current.first"
     * or "tag.current.last", where "tag" is the name of a valid tag. Try to use up as
     * much as possible of the string in this check. Doing the check now, and in this way,
     * allows tag names to include funny characters like "@" or "+1c".
     */

    Tcl_DStringInit(&copy);
    myString = Tcl_DStringAppend(&copy, string, -1);
    skipMark = false;

    p = myString + lenOfString;
    do {
	if (p-- == myString) {
	    goto tryxy;
	}
    } while (*p != '.');

    if (p[1] == 'f' && strncmp(p + 2, "irst", 4) == 0) {
	wantLast = false;
	endOfBase = p + 6;
	lenOfString = p - myString;
    } else if (p[1] == 'l' && strncmp(p + 2, "ast", 3) == 0) {
	wantLast = true;
	endOfBase = p + 5;
	lenOfString = p - myString;
    } else {
	goto tryxy;
    }

    /*
     * Marks have a higher precedence than tag.first or tag.last, so we will
     * search for marks before proceeding with tags.
     */

    if (TkTextMarkNameToIndex(textPtr, string, indexPtr)) {
	Tcl_DStringFree(&copy);
	return true;
    }

    skipMark = true;
    wantCurrent = false;

    do {
	if (lenOfString == 3 && strncmp(myString, "sel", 3) == 0) {
	    /*
	     * Special case for sel tag which is not stored in the hash table.
	     */
	    tagPtr = textPtr->selTagPtr;
	    hPtr = NULL;
	} else {
	    myString[lenOfString] = '\0';
	    hPtr = Tcl_FindHashEntry(&sharedTextPtr->tagTable, myString);
	    myString[lenOfString] = '.';
	    if (hPtr) {
		tagPtr = Tcl_GetHashValue(hPtr);
	    } else if (!wantCurrent
		    && lenOfString >= 8
		    && p[-8] == '.'
		    && strncmp(p - 7, "current", 7) == 0) {
		tagPtr = NULL;
		wantCurrent = true;
		lenOfString -= 8;
	    } else {
		goto tryxy;
	    }
	}
    } while (!tagPtr);

    if (wantCurrent) {
	bool tagFound = false;

	if (tagPtr->rootPtr) {
	    TkTextIndex currIndex;
	    TkTextSegment *segPtr;

	    assert(!textPtr->haveToSetCurrentMark);

	    segPtr = textPtr->currentMarkPtr;
	    do {
		segPtr = segPtr->nextPtr;
	    } while (!segPtr->tagInfoPtr);

	    if (TkTextTagSetTest(segPtr->tagInfoPtr, tagPtr->index)) {
		TkTextIndexClear(&currIndex, textPtr);
		TkTextIndexSetSegment(&currIndex, segPtr);
		TkTextIndexForwChars(textPtr, &currIndex, 1, &currIndex, COUNT_INDICES);
		tagFound = true;
	    } else {
		segPtr = textPtr->currentMarkPtr;
		do {
		    segPtr = segPtr->prevPtr;
		} while (segPtr && !segPtr->tagInfoPtr);

		if (!segPtr) {
		    TkTextLine *linePtr = textPtr->currentMarkPtr->sectionPtr->linePtr->prevPtr;
		    segPtr = linePtr ? linePtr->lastPtr : NULL;
		}
		if (segPtr && TkTextTagSetTest(segPtr->tagInfoPtr, tagPtr->index)) {
		    if (wantLast) {
			/* in this case we've already found the end of the range */
			TkTextIndexClear(indexPtr, textPtr);
			TkTextIndexSetSegment(indexPtr, textPtr->currentMarkPtr);
			goto gotBase;
		    }

		    TkTextIndexClear(&currIndex, textPtr);
		    TkTextIndexSetSegment(&currIndex, textPtr->currentMarkPtr);
		    tagFound = true;
		}
	    }

	    if (tagFound) {
		if (wantLast) {
		    TkTextTagFindEndOfRange(textPtr, tagPtr, &currIndex, indexPtr);
		} else {
		    TkTextTagFindStartOfRange(textPtr, tagPtr, &currIndex, indexPtr);
		}
	    }
	}
	if (!tagFound) {
	    const char *tagName = hPtr ? Tcl_GetHashKey(&sharedTextPtr->tagTable, hPtr) : "sel";

	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "character near current position isn't tagged with \"%s\"", tagName));
	    Tcl_SetErrorCode(interp, "TK", "LOOKUP", "TEXT_INDEX", tagName, NULL);
	    Tcl_DStringFree(&copy);
	    return false;
	}
    } else {
	TkTextSearch search;
	bool tagFound;

	TkTextIndexSetupToStartOfText(&first, textPtr, sharedTextPtr->tree);
	TkTextIndexSetupToEndOfText(&last, textPtr, sharedTextPtr->tree);
	if (wantLast) {
	    TkBTreeStartSearchBack(&last, &first, tagPtr, &search, SEARCH_EITHER_TAGON_TAGOFF);
	    tagFound = TkBTreePrevTag(&search);
	} else {
	    TkBTreeStartSearch(&first, &last, tagPtr, &search, SEARCH_NEXT_TAGON);
	    tagFound = TkBTreeNextTag(&search);
	}
	if (!tagFound) {
	    const char *tagName = hPtr ? Tcl_GetHashKey(&sharedTextPtr->tagTable, hPtr) : "sel";

	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "text doesn't contain any characters tagged with \"%s\"", tagName));
	    Tcl_SetErrorCode(interp, "TK", "LOOKUP", "TEXT_INDEX", tagName, NULL);
	    Tcl_DStringFree(&copy);
	    return false;
	}
	*indexPtr = search.curIndex;
    }

    goto gotBase;

  tryxy:
    if (string[0] == '@') {
	/*
	 * Find character at a given x,y location in the window.
	 */

	int x, y;

	cp = string + 1;
	if (*cp == 'f' && strncmp(cp, "first,", 6) == 0) {
	    x = TkTextGetFirstXPixel(textPtr);
	    end = (char *) cp + 5;
	} else if (*cp == 'l' && strncmp(cp, "last,", 5) == 0) {
	    x = TkTextGetLastXPixel(textPtr);
	    end = (char *) cp + 4;
	} else {
	    x = strtol(cp, &end, 0);
	    if (end == cp || *end != ',') {
		goto noBaseFound;
	    }
	}
	cp = end + 1;
	if (*cp == 'f' && strcmp(cp, "first") == 0) {
	    y = TkTextGetFirstYPixel(textPtr);
	    end += 6;
	} else if (*cp == 'l' && strcmp(cp, "last") == 0) {
	    y = TkTextGetLastYPixel(textPtr);
	    end += 5;
	} else {
	    y = strtol(cp, &end, 0);
	    if (end == cp) {
		goto noBaseFound;
	    }
	}
	TkTextPixelIndex(textPtr, x, y, indexPtr, NULL);
	endOfBase = end;
	goto gotBase;
    }

    if (isdigit(string[0]) || string[0] == '-') {
	int lineIndex, charIndex;

	/*
	 * Base is identified with line and character indices.
	 */

	lineIndex = strtol(string, &end, 0) - 1;
	if (end == string || *end != '.') {
	    goto noBaseFound;
	}
	p = end + 1;
	if (*p == 'e' && strncmp(p, "end", 3) == 0) {
	    charIndex = INT_MAX;
	    endOfBase = p + 3;
	} else if (*p == 'b' && strncmp(p, "begin", 5) == 0) {
	    charCount = charIndex = 0;
	    endOfBase = p + 5;
	} else {
	    charCount = charIndex = strtol(p, &end, 0);
	    if (end == p) {
		goto noBaseFound;
	    }
	    endOfBase = end;
	}
	if (lineIndex == 0 && textPtr->startMarker != sharedTextPtr->startMarker) {
	    charIndex += SkipSegments(textPtr->startMarker);
	}
	TkTextMakeCharIndex(sharedTextPtr->tree, textPtr, lineIndex, charIndex, indexPtr);
	goto gotBase;
    }

    for (p = myString; *p; ++p) {
	if (isspace(*p) || *p == '+' || *p == '-') {
	    break;
	}
    }
    endOfBase = p;
    if (string[0] == '.') {
	/*
	 * See if the base position is the name of an embedded window.
	 */

	c = *endOfBase;
	*endOfBase = '\0';
	result = TkTextWindowIndex(textPtr, myString, indexPtr);
	*endOfBase = c;
	if (result) {
	    goto gotBase;
	}
    }
    if (string[0] == 'b' && endOfBase - myString == 5 && strncmp(string, "begin", 5) == 0) {
	/*
	 * Base position is start of text.
	 */

	TkTextIndexSetupToStartOfText(indexPtr, textPtr, sharedTextPtr->tree);
	goto gotBase;
    }
    if (string[0] == 'e' && endOfBase - myString == 3 && strncmp(string, "end", 3) == 0) {
	/*
	 * Base position is end of text.
	 */

	TkTextIndexSetupToEndOfText(indexPtr, textPtr, sharedTextPtr->tree);
	goto gotBase;
    }

    /*
     * See if the base position is the name of a mark.
     */

    c = *endOfBase;
    *endOfBase = '\0';
    result = TkTextMarkNameToIndex(textPtr, myString, indexPtr);
    if (result) {
	*endOfBase = c;
	goto gotBase;
    }

    /*
     * See if the base position is the name of an embedded image.
     */

    result = TkTextImageIndex(textPtr, myString, indexPtr);
    *endOfBase = c;
    if (result) {
	goto gotBase;
    }

  noBaseFound:
    if ((!skipMark && TkTextMarkNameToIndex(textPtr, string, indexPtr))
	    || TkTextWindowIndex(textPtr, string, indexPtr)
	    || TkTextImageIndex(textPtr, string, indexPtr)) {
	Tcl_DStringFree(&copy);
	return true;
    }

    Tcl_DStringFree(&copy);
    Tcl_ResetResult(interp);
    Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad text index \"%s\"", string));
    Tcl_SetErrorCode(interp, "TK", "TEXT", "BAD_INDEX", NULL);
    return false;

    /*
     *-------------------------------------------------------------------
     * Stage 2: process zero or more modifiers. Each modifier is either a
     * keyword like "wordend" or "linestart", or it has the form "op count
     * units" where op is + or -, count is a number, and units is "chars" or
     * "lines".
     *-------------------------------------------------------------------
     */

  gotBase:
    cp = endOfBase;

    while (true) {
	while (isspace(*cp)) {
	    cp++;
	}
	if (*cp == '\0') {
	    break;
	}
	if (*cp == '+' || *cp == '-') {
	    cp = ForwBack(textPtr, cp, indexPtr, charCount);
	} else {
	    cp = StartEnd(textPtr, cp, indexPtr);
	}
	if (!cp) {
	    goto noBaseFound;
	}
    }

    Tcl_DStringFree(&copy);
    return true;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextIndexPrint --
 *
 *	This function generates a string description of an index, suitable for
 *	reading in again later.
 *
 * Results:
 *	The characters pointed to by string are modified. Returns the number
 *	of characters in the string.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

int
TkTextIndexPrint(
    const TkSharedText *sharedTextPtr,
    				/* Pointer to shared resource. */
    const TkText *textPtr,	/* Information about text widget, can be NULL. */
    const TkTextIndex *indexPtr,/* Pointer to index. */
    char *string)		/* Place to store the position. Must have at least TK_POS_CHARS
    				 * characters. */
{
    const TkTextSegment *segPtr;
    const TkTextLine *linePtr;
    const TkTextSegment *startMarker;
    int charIndex;

    assert(sharedTextPtr);
    assert(indexPtr);
    assert(string);
    assert(CheckLine(indexPtr, indexPtr->priv.linePtr));
    assert(CheckByteIndex(indexPtr, indexPtr->priv.linePtr, -1));

    charIndex = 0;
    linePtr = indexPtr->priv.linePtr;
    startMarker = textPtr ? textPtr->startMarker : sharedTextPtr->startMarker;
    segPtr = (linePtr == startMarker->sectionPtr->linePtr) ? startMarker : linePtr->segPtr;

    /*
     * Too bad that we cannot use the section structure here.
     *
     * The user of the Tk text widget is encouraged to work with marks,
     * in this way the expensive mappings between char indices and byte
     * indices can be avoided in many cases.
     */

    if (indexPtr->priv.segPtr && !indexPtr->priv.isCharSegment) {
	TkTextSegment *lastPtr = indexPtr->priv.segPtr;

	assert(indexPtr->priv.segPtr->typePtr);

	while (lastPtr->size == 0) {
	    lastPtr = lastPtr->nextPtr;
	}

	for ( ; segPtr != lastPtr; segPtr = segPtr->nextPtr) {
	    if (segPtr->typePtr == &tkTextCharType) {
		charIndex += CountCharsInSeg(segPtr);
	    } else {
		assert(segPtr->size <= 1);
		charIndex += segPtr->size;
	    }
	    assert(segPtr->nextPtr);
	}
    } else {
	int numBytes = TkTextIndexGetByteIndex(indexPtr);

	if (segPtr == startMarker && startMarker != sharedTextPtr->startMarker) {
	    numBytes -= TkTextSegToIndex(startMarker);
	}

	assert(numBytes >= 0);
	assert(numBytes < linePtr->size);

	for ( ; numBytes > segPtr->size; segPtr = segPtr->nextPtr) {
	    if (segPtr->typePtr == &tkTextCharType) {
		charIndex += CountCharsInSeg(segPtr);
	    } else {
		assert(segPtr->size <= 1);
		charIndex += segPtr->size;
	    }
	    numBytes -= segPtr->size;
	    assert(segPtr->nextPtr);
	}

	if (numBytes) {
	    if (segPtr->typePtr == &tkTextCharType) {
		charIndex += Tcl_NumUtfChars(segPtr->body.chars, numBytes);
	    } else {
		assert(segPtr->size <= 1);
		charIndex += numBytes;
	    }
	}
    }

    return snprintf(string, TK_POS_CHARS, "%d.%d",
	    TkBTreeLinesTo(indexPtr->tree, textPtr, linePtr, NULL) + 1, charIndex);
}

/*
 *---------------------------------------------------------------------------
 *
 * ForwBack --
 *
 *	This function handles +/- modifiers for indices to adjust the index
 *	forwards or backwards.
 *
 * Results:
 *	If the modifier in string is successfully parsed then the return value
 *	is the address of the first character after the modifier, and
 *	*indexPtr is updated to reflect the modifier. If there is a syntax
 *	error in the modifier then NULL is returned.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static const char *
ForwBack(
    TkText *textPtr,		/* Information about text widget. */
    const char *string,		/* String to parse for additional info about
				 * modifier (count and units). Points to "+"
				 * or "-" that starts modifier. */
    TkTextIndex *indexPtr,	/* Index to update as specified in string. */
    int charCount)		/* The character position in this line, -1 if not yet determined. */
{
    const char *p, *units;
    char *end;
    int count, lineIndex, modifier;
    size_t length;

    assert(textPtr);

    /*
     * Get the count (how many units forward or backward).
     */

    p = string + 1;
    while (isspace(*p)) {
	p++;
    }
    count = strtol(p, &end, 0);
    if (end == p) {
	return NULL;
    }
    p = end;
    while (isspace(*p)) {
	p++;
    }

    /*
     * Find the end of this modifier (next space or + or - character), then
     * check if there is a textual 'display' or 'any' modifier. These
     * modifiers can be their own word (in which case they can be abbreviated)
     * or they can follow on to the actual unit in a single word (in which
     * case no abbreviation is allowed). So, 'display lines', 'd lines',
     * 'displaylin' are all ok, but 'dline' is not.
     */

    units = p;
    while (*p != '\0' && !isspace(*p) && *p != '+' && *p != '-') {
	p++;
    }
    length = p - units;
    if (*units == 'd' && strncmp(units, "display", MIN(length, 7u)) == 0) {
	modifier = TKINDEX_DISPLAY;
	if (length > 7) {
	    p -= (length - 7);
	}
    } else if (*units == 'a' && strncmp(units, "any", MIN(length, 3u)) == 0) {
	modifier = TKINDEX_CHAR;
	if (length > 3) {
	    p -= (length - 3);
	}
    } else {
	modifier = TKINDEX_NONE;
    }

    /*
     * If we had a modifier, which we interpreted ok, so now forward to the
     * actual units.
     */

    if (modifier != TKINDEX_NONE) {
	while (isspace(*p)) {
	    p++;
	}
	units = p;
	while (*p != '\0' && !isspace(*p) && *p != '+' && *p != '-') {
	    p++;
	}
	length = p - units;
    }

    /*
     * Finally parse the units.
     */

    if (*units == 'c' && strncmp(units, "chars", length) == 0) {
	TkTextCountType type;

	if (modifier == TKINDEX_DISPLAY) {
	    type = COUNT_DISPLAY_CHARS;
	} else { /* if (modifier == TKINDEX_NONE) */
	    assert(modifier == TKINDEX_NONE || modifier == TKINDEX_CHAR);

	    /*
	     * The following is incompatible to 8.4 (and prior versions), but I think that
	     * now it's the time to eliminate this known issue:
	     *
	     *    Before Tk 8.5, the widget used the string “chars” to refer to index positions
	     *    (which included characters, embedded windows and embedded images). As of Tk 8.5
	     *    the text widget deals separately and correctly with “chars” and “indices”. For
	     *    backwards compatibility, however, the index modifiers “+N chars” and “-N chars”
	     *    continue to refer to indices. One must use any of the full forms “+N any chars”
	     *    or “-N any chars” etc. to refer to actual character indices. This confusion may
	     *    be fixed in a future release by making the widget correctly interpret “+N chars”
	     *    as a synonym for “+N any chars”.
	     *
	     * This confusion is fixed now, we will interpret "+N chars" as a synonym for
	     * “+N any chars”.
	     */

	    type = COUNT_CHARS;
	}

	if (*string == '+') {
	    TkTextIndexForwChars(textPtr, indexPtr, count, indexPtr, type);
	} else {
	    TkTextIndexBackChars(textPtr, indexPtr, count, indexPtr, type);
	}
    } else if (*units == 'i' && strncmp(units, "indices", length) == 0) {
	TkTextCountType type;

	if (modifier == TKINDEX_DISPLAY) {
	    type = COUNT_DISPLAY_INDICES;
	} else {
	    type = COUNT_INDICES;
	}

	if (*string == '+') {
	    TkTextIndexForwChars(textPtr, indexPtr, count, indexPtr, type);
	} else {
	    TkTextIndexBackChars(textPtr, indexPtr, count, indexPtr, type);
	}
    } else if (*units == 'l' && strncmp(units, "lines", length) == 0) {
	if (modifier == TKINDEX_DISPLAY) {
	    /*
	     * Find the appropriate pixel offset of the current position
	     * within its display line. This also has the side-effect of
	     * moving indexPtr, but that doesn't matter since we will do it
	     * again below.
	     *
	     * Then find the right display line, and finally calculated the
	     * index we want in that display line, based on the original pixel
	     * offset.
	     */

	    int xOffset;
	    bool forward;

	    /*
	     * Go forward to the first non-elided index.
	     */

	    if (TkTextIsElided(indexPtr)) {
		TkTextSkipElidedRegion(indexPtr);
	    }

	    if (count == 0) {
		return p;
	    }

	    /*
	     * Unlike the Forw/BackChars code, the display line code is
	     * sensitive to whether we are genuinely going forwards or
	     * backwards. So, we need to determine that. This is important in
	     * the case where we have "+ -3 displaylines", for example.
	     */

	    forward = (count < 0) == (*string == '-');
	    count = abs(count);
	    if (!forward) {
		count = -count;
	    }

	    TkTextFindDisplayIndex(textPtr, indexPtr, count, &xOffset);

	    /*
	     * This call assumes indexPtr is the beginning of a display line
	     * and moves it to the 'xOffset' position of that line, which is
	     * just what we want.
	     */

	    TkTextIndexOfX(textPtr, xOffset, indexPtr);

	    /*
	     * We must skip any elided range.
	     */

	    if (TkTextIsElided(indexPtr)) {
		TkTextSkipElidedRegion(indexPtr);
	    }
	} else {
	    int newLineIndex;

	    lineIndex = TkBTreeLinesTo(indexPtr->tree, textPtr, indexPtr->priv.linePtr, NULL);
	    if (*string == '+') {
		newLineIndex = MIN(TkBTreeNumLines(indexPtr->tree, textPtr), lineIndex + count);
	    } else {
		newLineIndex = MAX(0, lineIndex - count);
	    }
	    if (newLineIndex != lineIndex) {
		TkTextLine *linePtr = TkBTreeFindLine(indexPtr->tree, textPtr, newLineIndex);

		if (charCount == -1) {
		    TkTextIndex lineStart = *indexPtr;
		    TkTextIndexSetToStartOfLine(&lineStart);
		    charCount = TkTextIndexCount(textPtr, &lineStart, indexPtr, COUNT_CHARS);
		}
		TkTextIndexSetToStartOfLine2(indexPtr, linePtr);
		TkTextIndexForwChars(textPtr, indexPtr, charCount, indexPtr, COUNT_CHARS);
		if (linePtr != TkTextIndexGetLine(indexPtr)) {
		    TkTextIndexSetToEndOfLine2(indexPtr, linePtr);
		}
	    }
	}
    } else {
	return NULL;
    }
    return p;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextIndexForwBytes --
 *
 *	Given an index for a text widget, this function creates a new index
 *	that points "byteCount" bytes ahead of the source index.
 *
 * Results:
 *	*dstPtr is modified to refer to the character "count" bytes after
 *	srcPtr, or to the last character in the TkText if there aren't "byteCount"
 *	bytes left.
 *
 *	In this latter case, the function returns '1' to indicate that not all
 *	of 'byteCount' could be used.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

int
TkTextIndexForwBytes(
    const TkText *textPtr,	/* Overall information about text widget, can be NULL. */
    const TkTextIndex *srcPtr,	/* Source index. */
    int byteCount,		/* How many bytes forward to move. May be negative. */
    TkTextIndex *dstPtr)	/* Destination index: gets modified. */
{
    TkTextLine *linePtr;
    int byteIndex;

    if (byteCount == 0) {
	if (dstPtr != srcPtr) {
	    *dstPtr = *srcPtr;
	}
	return 0;
    }

    if (byteCount < 0) {
	TkTextIndexBackBytes(textPtr, srcPtr, -byteCount, dstPtr);
	return 0;
    }

    if (dstPtr != srcPtr) {
	*dstPtr = *srcPtr;
    }

    TkTextIndexToByteIndex(dstPtr);
    linePtr = TkTextIndexGetLine(dstPtr);

    if (textPtr) {
	if (linePtr == TkBTreeGetLastLine(textPtr)) {
	    return 1;
	}
	if (textPtr->endMarker->sectionPtr->linePtr == linePtr) {
	    /*
	     * Special case: line contains end marker.
	     */

	    int lineLength = SegToIndex(linePtr, textPtr->endMarker);

	    if ((byteIndex = (dstPtr->priv.byteIndex += byteCount)) > lineLength) {
		assert(linePtr->nextPtr);
		TkTextIndexSetByteIndex2(dstPtr, linePtr->nextPtr, 0);
	    }
	    return byteIndex <= lineLength ? 0 : 1;
	}
    } else if (!linePtr->nextPtr) {
	return 1;
    }

    if ((byteIndex = dstPtr->priv.byteIndex + byteCount) > linePtr->size) {
	bool rc;
	DEBUG(TkTextIndex index = *srcPtr);
	rc = TkBTreeMoveForward(dstPtr, byteCount);
	assert(!rc || (int) TkTextIndexCountBytes(&index, dstPtr) == byteCount);
	return rc ? 0 : 1;
    }

    if (byteIndex == linePtr->size) {
	assert(linePtr->nextPtr);
	TkTextIndexSetByteIndex2(dstPtr, linePtr->nextPtr, 0);
    } else {
	TkTextIndexSetByteIndex(dstPtr, byteIndex);
    }

    return 0;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextIndexForwChars --
 *
 *	Given an index for a text widget, this function creates a new index
 *	that points "count" items of type given by "type" ahead of the source
 *	index. "count" can be zero, which is useful in the case where one
 *	wishes to move forward by display (non-elided) chars or indices or one
 *	wishes to move forward by chars, skipping any intervening indices. In
 *	this case dstPtr will point to the first acceptable index which is
 *	encountered.
 *
 * Results:
 *	*dstPtr is modified to refer to the character "count" items after
 *	srcPtr, or to the last character in the TkText if there aren't
 *	sufficient items left in the widget.
 *
 *	This function returns whether the resulting index is different from
 *	source index.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

bool
TkTextIndexForwChars(
    const TkText *textPtr,	/* Overall information about text widget, can be NULL. */
    const TkTextIndex *srcPtr,	/* Source index. */
    int charCount,		/* How many characters forward to move. May be negative. */
    TkTextIndex *dstPtr,	/* Destination index: gets modified. */
    TkTextCountType type)	/* The type of item to count */
{
    TkTextLine *linePtr;
    TkTextSegment *segPtr;
    TkTextSegment *endPtr;
    TkSharedText *sharedTextPtr;
    int byteOffset;
    bool checkElided;
    bool trimmed;
    bool skipSpaces;

    if (charCount < 0) {
	return TkTextIndexBackChars(textPtr, srcPtr, -charCount, dstPtr, type);
    }

    if (dstPtr != srcPtr) {
	*dstPtr = *srcPtr;
    }

    if (TkTextIndexIsEndOfText(dstPtr)) {
	return false;
    }

    sharedTextPtr = TkTextIndexGetShared(srcPtr);
    checkElided = !!(type & COUNT_DISPLAY) && TkBTreeHaveElidedSegments(sharedTextPtr);

    if (checkElided && TkTextIsElided(dstPtr) && !TkTextSkipElidedRegion(dstPtr)) {
	return false;
    }

    if (charCount == 0) {
	return false;
    }

    assert(dstPtr->priv.byteIndex <= FindEndByteIndex(dstPtr));

    /*
     * Find seg that contains src byteIndex. Move forward specified number of chars.
     */

    segPtr = TkTextIndexGetFirstSegment(dstPtr, &byteOffset);
    endPtr = textPtr ? textPtr->endMarker : sharedTextPtr->endMarker;
    trimmed = textPtr && textPtr->spaceMode == TEXT_SPACEMODE_TRIM && !!(type & COUNT_DISPLAY);
    skipSpaces = false;

    TkTextIndexToByteIndex(dstPtr);
    dstPtr->priv.segPtr = NULL;

    while (true) {
	/*
	 * Go through each segment in line looking for specified character index.
	 */

	for ( ; segPtr; segPtr = segPtr->nextPtr) {
	    if (segPtr->tagInfoPtr) {
		if (segPtr->typePtr == &tkTextCharType) {
		    const char *start = segPtr->body.chars + byteOffset;
		    const char *end = segPtr->body.chars + segPtr->size;
		    const char *p = start;
		    int n;

		    for (p = start; p < end; p += n) {
			Tcl_UniChar ch;

			if (charCount <= 0) {
			    if (skipSpaces) {
				while (*p == ' ') {
				    ++p;
				}
				if (*p == '\n') {
				    ++p;
				}
				if (p == end) {
				    break;
				}
			    }
			    dstPtr->priv.byteIndex += (p - start);
			    goto forwardCharDone;
			}
			{ /* local scope */
#if TCL_UTF_MAX > 4
			    /*
			     * HACK: Support of pseudo UTF-8 strings. Needed because of this
			     * bad hack with TCL_UTF_MAX > 4, the whole thing is amateurish.
			     * (See function GetLineBreakFunc() about the very severe problems
			     * with TCL_UTF_MAX > 4).
			     */

			    int c;
			    n = TkUtfToUniChar(p, &c);
			    ch = c;
#else
			    /*
			     * Proper implementation for UTF-8 strings:
			     */

			    n = Tcl_UtfToUniChar(p, &ch);
#endif
			}
			if (ch == ' ') {
			    if (!skipSpaces) {
				skipSpaces = trimmed;
				charCount -= 1;
			    }
			} else {
			    skipSpaces = false;
			    charCount -= (type & COUNT_INDICES) ? n : 1;
			}
		    }
		} else if (type & COUNT_INDICES) {
		    assert(byteOffset == 0);
		    assert(segPtr->size <= 1);
		    if (charCount < segPtr->size) {
			dstPtr->priv.byteIndex += charCount;
			dstPtr->priv.segPtr = segPtr;
			dstPtr->priv.isCharSegment = false;
			goto forwardCharDone;
		    }
		    charCount -= segPtr->size;
		}
		dstPtr->priv.byteIndex += segPtr->size - byteOffset;
		byteOffset = 0;
	    } else if (checkElided && segPtr->typePtr == &tkTextBranchType) {
		TkTextIndexSetSegment(dstPtr, segPtr = segPtr->body.branch.nextPtr);
		if (TkTextIndexRestrictToEndRange(dstPtr) >= 0) {
		    return true;
		}
		TkTextIndexToByteIndex(dstPtr);
	    } else if (segPtr == endPtr) {
		if (charCount <= 0) {
		    goto forwardCharDone;
		}
		TkTextIndexSetupToEndOfText(dstPtr, (TkText *) textPtr, srcPtr->tree);
		return true;
	    }
	}

	/*
	 * Go to the next line. If we are at the end of the text item, back up
	 * one byte (for the terminal '\n' character) and return that index.
	 */

	if (!(linePtr = TkBTreeNextLine(textPtr, dstPtr->priv.linePtr))) {
	    TkTextIndexSetToLastChar(dstPtr);
	    return true;
	}
	dstPtr->priv.linePtr = linePtr;
	dstPtr->priv.byteIndex = 0;
	dstPtr->priv.lineNo = -1;
	dstPtr->priv.lineNoRel = -1;
	segPtr = linePtr->segPtr;
    }

forwardCharDone:
    dstPtr->stateEpoch = TkBTreeEpoch(dstPtr->tree);
    return true;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextSkipElidedRegion --
 *
 *	Given an index for a text widget, this function returns an index with
 *	the position of first un-elided character, or end of text, if the first
 *	un-elided character is beyond of this text widget. This functions assumes
 *	that the text position specified with incoming index is elided.
 *
 * Results:
 *	*indexPtr is modified to refer to the first un-elided character. This
 *	functions returns 'false' iff we reach the end of the text (belonging to
 *	this widget).
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

bool
TkTextSkipElidedRegion(
    TkTextIndex *indexPtr)
{
    TkTextSegment *segPtr;

    assert(indexPtr->textPtr);
    assert(TkTextIsElided(indexPtr));

    segPtr = TkBTreeFindEndOfElidedRange(indexPtr->textPtr->sharedTextPtr,
	    indexPtr->textPtr, TkTextIndexGetContentSegment(indexPtr, NULL));
    TkTextIndexSetSegment(indexPtr, segPtr);
    return !TkTextIndexIsEndOfText(indexPtr);
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextIndexCountBytes --
 *
 *	Given a pair of indices in a text widget, this function counts how
 *	many bytes are between the two indices. The two indices must be
 *	ordered.
 *
 * Results:
 *	The number of bytes in the given range.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

unsigned
TkTextIndexCountBytes(
    const TkTextIndex *indexPtr1,	/* Index describing location of character from which to count. */
    const TkTextIndex *indexPtr2)	/* Index describing location of last character at which to
    					 * stop the count. */
{
    int byteCount;
    TkTextLine *linePtr;

    assert(TkTextIndexCompare(indexPtr1, indexPtr2) <= 0);

    if (indexPtr1->priv.linePtr == indexPtr2->priv.linePtr) {
        return TkTextIndexGetByteIndex(indexPtr2) - TkTextIndexGetByteIndex(indexPtr1);
    }

    /*
     * indexPtr2 is on a line strictly after the line containing indexPtr1.
     * Add up:
     *   bytes between indexPtr1 and end of its line
     *   bytes in lines strictly between indexPtr1 and indexPtr2
     *   bytes between start of the indexPtr2 line and indexPtr2
     */

    linePtr = indexPtr1->priv.linePtr;
    byteCount = linePtr->size - TkTextIndexGetByteIndex(indexPtr1);
    byteCount += TkTextIndexGetByteIndex(indexPtr2);
    byteCount += TkBTreeCountSize(indexPtr1->tree, NULL, linePtr->nextPtr, indexPtr2->priv.linePtr);
    return byteCount;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextIndexGetChar --
 *
 *	Return the character at given index.
 *
 * Results:
 *	The character at given index.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

Tcl_UniChar
TkTextIndexGetChar(
    const TkTextIndex *indexPtr)/* Index describing location of character. */
{
    TkTextSegment *segPtr;
    int byteOffset;
    const char *s;

    segPtr = TkTextIndexGetContentSegment(indexPtr, &byteOffset);
    s = segPtr->body.chars + byteOffset;

    { /* local scope */
#if TCL_UTF_MAX > 4
	/*
	 * HACK: Support of pseudo UTF-8 strings. Needed because of this
	 * bad hack with TCL_UTF_MAX > 4, the whole thing is amateurish.
	 * (See function GetLineBreakFunc() about the very severe problems
	 * with TCL_UTF_MAX > 4).
	 */

	int ch;
	TkUtfToUniChar(s, &ch);
	return ch;
#else
	/*
	 * Proper implementation for UTF-8 strings:
	 */

	Tcl_UniChar ch;
	Tcl_UtfToUniChar(s, &ch);
	return ch;
#endif
    }

    return 0; /* never reached */
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextIndexCount --
 *
 *	Given an ordered pair of indices in a text widget, this function
 *	counts how many characters (not bytes) are between the two indices.
 *
 *	It is illegal to call this function with unordered indices.
 *
 *	Note that 'textPtr' is only used if we need to check for elided
 *	attributes, i.e. if type is COUNT_DISPLAY_INDICES or
 *	COUNT_DISPLAY_CHARS.
 *
 *	NOTE: here COUNT_INDICES is also counting chars in text segments.
 *
 * Results:
 *	The number of characters in the given range, which meet the
 *	appropriate 'type' attributes.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

unsigned
TkTextIndexCount(
    const TkText *textPtr,	/* Overall information about text widget. */
    const TkTextIndex *indexPtr1,
				/* Index describing location of character from which to count. */
    const TkTextIndex *indexPtr2,
				/* Index describing location of last character at which to stop
				 * the count. */
    TkTextCountType type)	/* The kind of indices to count. */
{
    TkTextLine *linePtr;
    TkTextIndex index;
    TkTextSegment *segPtr, *lastPtr;
    int byteOffset, maxBytes;
    unsigned count;
    bool checkElided;

    assert(textPtr);
    assert(TkTextIndexCompare(indexPtr1, indexPtr2) <= 0);

    checkElided = !!(type & COUNT_DISPLAY) && TkBTreeHaveElidedSegments(textPtr->sharedTextPtr);
    index = *indexPtr1;

    if (checkElided
	    && TkTextIsElided(&index)
	    && (!TkTextSkipElidedRegion(&index) || TkTextIndexCompare(&index, indexPtr2) >= 0)) {
	return 0;
    }

    /*
     * Find seg that contains src index, and remember how many bytes not to count in the given segment.
     */

    segPtr = TkTextIndexGetContentSegment(&index, &byteOffset);
    lastPtr = TkTextIndexGetContentSegment(indexPtr2, &maxBytes);
    linePtr = index.priv.linePtr;
    count = 0;

    if (byteOffset > 0) {
	if (segPtr->tagInfoPtr) {
	    if (segPtr->typePtr == &tkTextCharType) {
		if (type & (COUNT_INDICES|COUNT_TEXT)) {
		    count += Tcl_NumUtfChars(segPtr->body.chars + byteOffset,
			    (segPtr == lastPtr ? maxBytes : segPtr->size) - byteOffset);
		}
	    } else if (segPtr->typePtr == &tkTextHyphenType) {
		if (type & (COUNT_HYPHENS|COUNT_INDICES)) {
		    assert(segPtr->size == 1);
		    count += 1;
		}
	    } else if (type & COUNT_INDICES) {
		assert(segPtr->size == 1);
		count += 1;
	    }
	}
	if (segPtr == lastPtr) {
	    return count;
	}
	segPtr = segPtr->nextPtr;
    }

    if (maxBytes > 0 && (!checkElided || !TkTextSegmentIsElided(textPtr, lastPtr))) {
	if (lastPtr->typePtr == &tkTextCharType) {
	    if (type & (COUNT_TEXT|COUNT_INDICES)) {
		count += Tcl_NumUtfChars(lastPtr->body.chars, maxBytes);
	    }
	} else if (lastPtr->typePtr == &tkTextHyphenType) {
	    if (type & (COUNT_HYPHENS|COUNT_INDICES)) {
		assert(lastPtr->size == 1);
		count += 1;
	    }
	} else if (type & COUNT_INDICES) {
	    assert(lastPtr->size == 1);
	    count += 1;
	}
    }

    while (true) {
	/*
	 * Go through each segment in line adding up the number of characters.
	 */

	for ( ; segPtr; segPtr = segPtr->nextPtr) {
	    if (segPtr == lastPtr) {
		return count;
	    }
	    if (segPtr->tagInfoPtr) {
		if (segPtr->typePtr == &tkTextCharType) {
		    if (type & (COUNT_TEXT|COUNT_INDICES)) {
			count += CountCharsInSeg(segPtr);
		    }
		} else if (segPtr->typePtr == &tkTextHyphenType) {
		    if (type & (COUNT_HYPHENS|COUNT_INDICES)) {
			count += CountCharsInSeg(segPtr);
		    }
		} else if (type & COUNT_INDICES) {
		    assert(segPtr->size == 1);
		    count += 1;
		}
	    } else if (checkElided && segPtr->typePtr == &tkTextBranchType) {
		TkTextIndexSetSegment(&index, segPtr = segPtr->body.branch.nextPtr);
		if (TkTextIndexCompare(&index, indexPtr2) >= 0) {
		    return count;
		}
		linePtr = TkTextIndexGetLine(&index);
	    }
	}

	/*
	 * Go to the next line.
	 */

	linePtr = TkBTreeNextLine(textPtr, linePtr);
	assert(linePtr);
	segPtr = linePtr->segPtr;
    }

    return 0; /* never reached */
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextIndexBackBytes --
 *
 *	Given an index for a text widget, this function creates a new index
 *	that points "count" bytes earlier than the source index.
 *
 * Results:
 *	*dstPtr is modified to refer to the character "count" bytes before
 *	srcPtr, or to the first character in the TkText if there aren't
 *	"count" bytes earlier than srcPtr.
 *
 *	Returns 1 if we couldn't use all of 'byteCount' because we have run
 *	into the beginning or end of the text, and zero otherwise.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

/*
 * NOTE: This function has external linkage, so we cannot change the return
 * type to 'bool'.
 */

int
TkTextIndexBackBytes(
    const TkText *textPtr,	/* Overall information about text widget, can be NULL. */
    const TkTextIndex *srcPtr,	/* Source index. */
    int byteCount,		/* How many bytes backward to move. May be negative. */
    TkTextIndex *dstPtr)	/* Destination index: gets modified. */
{
    TkTextLine *linePtr;
    int byteIndex;

    if (byteCount == 0) {
	if (dstPtr != srcPtr) {
	    *dstPtr = *srcPtr;
	}
	return 0;
    }

    if (byteCount < 0) {
	return TkTextIndexForwBytes(textPtr, srcPtr, -byteCount, dstPtr);
    }

    if (dstPtr != srcPtr) {
	*dstPtr = *srcPtr;
    }
    byteIndex = TkTextIndexGetByteIndex(dstPtr);
    linePtr = TkTextIndexGetLine(dstPtr);

    if (textPtr
	    && linePtr == textPtr->startMarker->sectionPtr->linePtr
	    && textPtr->startMarker != textPtr->sharedTextPtr->startMarker) {
	/*
	 * Special case: this is the first line, and we have to consider the start marker.
	 */

	if ((byteIndex -= byteCount) < SegToIndex(linePtr, textPtr->startMarker)) {
	    TkTextIndexSetupToStartOfText(dstPtr, (TkText *) textPtr, textPtr->sharedTextPtr->tree);
	    return 1;
	}

	TkTextIndexSetByteIndex(dstPtr, byteIndex);
	return 0;
    }

    if (byteCount > byteIndex + 1) {
	bool rc;
	DEBUG(TkTextIndex index = *srcPtr);
	rc = TkBTreeMoveBackward(dstPtr, byteCount);
	assert(!rc || (int) TkTextIndexCountBytes(dstPtr, &index) == byteCount);
	return rc ? 0 : 1;
    }

    if ((byteIndex -= byteCount) >= 0) {
	TkTextIndexSetByteIndex(dstPtr, byteIndex);
	return 0;
    }

    /*
     * Move back one line in the text. If we run off the beginning
     * then just return the first character in the text widget.
     */

    if (!(linePtr = TkBTreePrevLine(textPtr, linePtr))) {
	TkTextIndexSetToStartOfLine(dstPtr);
	return 1;
    }

    TkTextIndexSetToLastChar2(dstPtr, linePtr);
    return 0;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextIndexBackChars --
 *
 *	Given an index for a text widget, this function creates a new index
 *	that points "count" items of type given by "type" earlier than the
 *	source index. "count" can be zero, which is useful in the case where
 *	one wishes to move backward by display (non-elided) chars or indices
 *	or one wishes to move backward by chars, skipping any intervening
 *	indices. In this case the returned index *dstPtr will point just
 *	_after_ the first acceptable index which is encountered.
 *
 * Results:
 *	*dstPtr is modified to refer to the character "count" items before
 *	srcPtr, or to the first index in the window if there aren't sufficient
 *	items earlier than srcPtr.
 *
 *	This function returns whether the resulting index is different from
 *	source index.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

bool
TkTextIndexBackChars(
    const TkText *textPtr,	/* Overall information about text widget, can be NULL. */
    const TkTextIndex *srcPtr,	/* Source index. */
    int charCount,		/* How many characters backward to move. May be negative. */
    TkTextIndex *dstPtr,	/* Destination index: gets modified. */
    TkTextCountType type)	/* The type of item to count */
{
    TkSharedText *sharedTextPtr;
    TkTextSegment *segPtr;
    TkTextSegment *startPtr;
    TkTextLine *linePtr;
    int segSize;
    bool checkElided;
    bool trimmed;
    bool skipSpaces;
    int byteIndex;

    assert(textPtr || !(type & COUNT_DISPLAY));

    if (charCount < 0) {
	return TkTextIndexForwChars(textPtr, srcPtr, -charCount, dstPtr, type);
    }

    if (dstPtr != srcPtr) {
	*dstPtr = *srcPtr;
    }

    if (charCount == 0) {
	return false;
    }

    sharedTextPtr = TkTextIndexGetShared(srcPtr);
    checkElided = !!(type & COUNT_DISPLAY) && TkBTreeHaveElidedSegments(textPtr->sharedTextPtr);

    if (checkElided && TkTextIsElided(dstPtr) && !TkTextSkipElidedRegion(dstPtr)) {
	return false;
    }

    if (TkTextIndexIsStartOfLine(dstPtr) && !TkBTreePrevLine(textPtr, dstPtr->priv.linePtr)) {
	return false;
    }

    if (textPtr && textPtr->endMarker != sharedTextPtr->endMarker) {
	linePtr = TkBTreeGetLastLine(textPtr);

	if (dstPtr->priv.linePtr == linePtr && linePtr != textPtr->endMarker->sectionPtr->linePtr) {
	    /*
	     * Special case: we are at start of last line, but this is not the end line.
	     */

	    if (--charCount == 0) {
		byteIndex = TkTextSegToIndex(textPtr->endMarker);
		dstPtr->priv.linePtr = textPtr->endMarker->sectionPtr->linePtr;
		dstPtr->priv.segPtr = NULL;
		dstPtr->priv.lineNo = dstPtr->priv.lineNoRel = -1;
		goto backwardCharDone;
	    }
	    TkTextIndexSetSegment(dstPtr, textPtr->endMarker);
	}
    }

    /*
     * Move backward specified number of chars.
     */

    segPtr = TkTextIndexGetFirstSegment(dstPtr, &segSize);
    startPtr = textPtr ? textPtr->startMarker : sharedTextPtr->startMarker;
    byteIndex = TkTextIndexGetByteIndex(dstPtr);
    dstPtr->priv.segPtr = NULL;

    /*
     * Now segPtr points to the segment containing the starting index.
     */

    trimmed = textPtr && textPtr->spaceMode == TEXT_SPACEMODE_TRIM && !!(type & COUNT_DISPLAY);
    skipSpaces = false;

    while (true) {
	/*
	 * If we do need to pay attention to the visibility of
	 * characters/indices, check that first. If the current segment isn't
	 * visible, then we simply continue the loop.
	 */

	if (segPtr->tagInfoPtr) {
	    if (segPtr->typePtr == &tkTextCharType) {
		const char *start = segPtr->body.chars;
		const char *end = segPtr->body.chars + segSize;
		const char *p = end;

		while (true) {
		    const char *q;

		    if (charCount <= 0) {
			if (skipSpaces) {
			    while (p > start && p[-1] == ' ') {
				--p;
			    }
			    if (p == start) {
				break;
			    }
			}
			byteIndex -= (end - p);
			goto backwardCharDone;
		    }
		    if (p == start) {
			break;
		    }
		    p = Tcl_UtfPrev(q = p, start);
		    if (*p == ' ') {
			if (!skipSpaces) {
			    skipSpaces = trimmed;
			    charCount -= 1;
			}
		    } else {
			skipSpaces = trimmed && *p == '\n';
			charCount -= (type & COUNT_INDICES) ? q - p : 1;
		    }
		}
	    } else if (type & COUNT_INDICES) {
		assert(segPtr->size <= 1);
		if (charCount <= segSize) {
		    byteIndex -= charCount;
		    dstPtr->priv.segPtr = segPtr;
		    dstPtr->priv.isCharSegment = false;
		    goto backwardCharDone;
		}
		charCount -= segSize;
	    }
	} else if (checkElided && segPtr->typePtr == &tkTextLinkType) {
	    TkTextIndexSetSegment(dstPtr, segPtr = segPtr->body.link.prevPtr);
	    if (TkTextIndexRestrictToStartRange(dstPtr) <= 0) {
		return true;
	    }
	    TkTextIndexToByteIndex(dstPtr);
	    byteIndex = TkTextIndexGetByteIndex(dstPtr);
	} else if (segPtr == startPtr) {
	    TkTextIndexSetSegment(dstPtr, segPtr = startPtr);
	    return true;
	}

	/*
	 * Move back into previous segment.
	 */

	if (!(segPtr = segPtr->prevPtr)) {
	    /*
	     * Move back to previous line
	     */

	    linePtr = TkBTreePrevLine(textPtr, dstPtr->priv.linePtr);
	    assert(linePtr);

	    dstPtr->priv.linePtr = linePtr;
	    dstPtr->priv.lineNo = dstPtr->priv.lineNoRel = -1;
	    byteIndex = linePtr->size;
	    segPtr = linePtr->lastPtr;
	} else {
	    byteIndex -= segSize;
	}

	segSize = segPtr->size;
    }

  backwardCharDone:
    dstPtr->priv.byteIndex = byteIndex;
    dstPtr->stateEpoch = TkBTreeEpoch(dstPtr->tree);
    return true;
}

/*
 *----------------------------------------------------------------------
 *
 * StartEnd --
 *
 *	This function handles modifiers like "wordstart" and "lineend" to
 *	adjust indices forwards or backwards.
 *
 * Results:
 *	If the modifier is successfully parsed then the return value is the
 *	address of the first character after the modifier, and *indexPtr is
 *	updated to reflect the modifier. If there is a syntax error in the
 *	modifier then NULL is returned.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static const char *
StartEnd(
    TkText *textPtr,		/* Information about text widget. */
    const char *string,		/* String to parse for additional info about modifier (count and units).
    				 * Points to first character of modifier word. */
    TkTextIndex *indexPtr)	/* Index to modify based on string. */
{
    const char *p;
    size_t length;
    TkTextSegment *segPtr;
    int modifier = TKINDEX_NONE;
    int mode = COUNT_INDICES;

    assert(textPtr);

    /*
     * Find the end of the modifier word.
     */

    for (p = string; isalnum(*p); ++p) {
	/* Empty loop body. */
    }
    length = p - string;

    switch (string[0]) {
	case 'd':
	    if (strncmp(string, "display", MIN(length, 7u)) == 0) {
		modifier = TKINDEX_DISPLAY;
		mode = COUNT_DISPLAY_INDICES;
		if (length > 7) {
		    p -= (length - 7);
		}
	    }
	    break;
	case 'a':
	    if (strncmp(string, "any", MIN(length, 3u)) == 0) {
		modifier = TKINDEX_CHAR;
		mode = COUNT_CHARS;
		if (length > 3) {
		    p -= (length - 3);
		}
	    }
	    break;
    }

    /*
     * If we had a modifier, which we interpreted ok, so now forward to the actual units.
     */

    if (modifier != TKINDEX_NONE) {
	while (isspace(*p)) {
	    ++p;
	}
	string = p;
	while (*p && !isspace(*p) && *p != '+' && *p != '-') {
	    ++p;
	}
	length = p - string;
    }

    if (length >= 5) {
	switch (string[0]) {
	case 'l':
	    switch (string[4]) {
	    case 'e':
		if (strncmp(string, "lineend", length) == 0) {
		    if (modifier == TKINDEX_DISPLAY) {
			TkTextFindDisplayLineStartEnd(textPtr, indexPtr, DISP_LINE_END);
		    } else {
			TkTextIndexSetToLastChar(indexPtr);
		    }
		    return p;
		}
		break;
	    case 's':
		if (strncmp(string, "linestart", length) == 0) {
		    if (modifier == TKINDEX_DISPLAY) {
			TkTextFindDisplayLineStartEnd(textPtr, indexPtr, DISP_LINE_START);
		    } else {
			TkTextIndexSetToStartOfLine(indexPtr);
		    }
		    return p;
		}
		break;
	    }
	    break;
	case 'w':
	    switch (string[4]) {
	    case 'e':
		if (strncmp(string, "wordend", length) == 0) {
		    bool firstChar = true;
		    int offset;

		    /*
		     * If the current character isn't part of a word then just move
		     * forward one character. Otherwise move forward until finding a
		     * character that isn't part of a word and stop there.
		     */

		    if (modifier == TKINDEX_DISPLAY) {
			TkTextIndexForwChars(textPtr, indexPtr, 0, indexPtr, COUNT_DISPLAY_INDICES);
		    }
		    segPtr = TkTextIndexGetContentSegment(indexPtr, &offset);

		    while (true) {
			int chSize = 1;

			if (segPtr->typePtr == &tkTextCharType) {
			    const char *s = segPtr->body.chars + offset;

#if TCL_UTF_MAX > 4
			    /*
			     * HACK: Support of pseudo UTF-8 strings. Needed because of this
			     * bad hack with TCL_UTF_MAX > 4, the whole thing is amateurish.
			     * (See function GetLineBreakFunc() about the very severe problems
			     * with TCL_UTF_MAX > 4).
			     */

			    int ch;
			    chSize = TkUtfToUniChar(s, &ch);
#else
			    /*
			     * Proper implementation for UTF-8 strings:
			     */

			    Tcl_UniChar ch;
			    chSize = Tcl_UtfToUniChar(s, &ch);
#endif

			    if (!Tcl_UniCharIsWordChar(ch)) {
				break;
			    }
			    firstChar = false;
			}
			offset += chSize;
			indexPtr->priv.byteIndex += chSize;
			if (offset >= segPtr->size) {
			    do {
				segPtr = segPtr->nextPtr;
			    } while (segPtr->size == 0);
			    offset = 0;
			}
		    }
		    indexPtr->priv.segPtr = segPtr;
		    indexPtr->priv.isCharSegment = segPtr->typePtr == &tkTextCharType;
		    if (firstChar) {
			TkTextIndexForwChars(textPtr, indexPtr, 1, indexPtr, mode);
		    }
		    return p;
		}
		break;
	    case 's':
		if (strncmp(string, "wordstart", length) == 0) {
		    bool firstChar = true;
		    int offset;

		    if (modifier == TKINDEX_DISPLAY) {
			/*
			 * Skip elided region.
			 */
			TkTextIndexForwChars(textPtr, indexPtr, 0, indexPtr, COUNT_DISPLAY_INDICES);
		    }

		    /*
		     * Starting with the current character, look for one that's not part
		     * of a word and keep moving backward until you find one. Then if the
		     * character found wasn't the first one, move forward again one
		     * position.
		     */

		    segPtr = TkTextIndexGetContentSegment(indexPtr, &offset);

		    while (true) {
			int chSize = 1;

			if (segPtr->typePtr == &tkTextCharType) {
			    Tcl_UniChar ch;
			    const char *p = segPtr->body.chars + offset;

#if TCL_UTF_MAX > 4
			    /*
			     * HACK: Support of pseudo UTF-8 strings. Needed because of this
			     * bad hack with TCL_UTF_MAX > 4, the whole thing is amateurish.
			     * (See function GetLineBreakFunc() about the very severe problems
			     * with TCL_UTF_MAX > 4).
			     */

			    int c;
			    TkUtfToUniChar(p, &c);
			    ch = c;
#else
			    /*
			     * Proper implementation for UTF-8 strings:
			     */

			    Tcl_UtfToUniChar(p, &ch);
#endif

#if TCL_UTF_MAX > 4
/*
 * At this place I like to state that the replacement of Tcl_UtfToUniChar
 * with TkUtfToUniChar has introduced an unreliable system, it's not a
 * new problem with revised version.
 *
 * Also note that the implementation of tkFont.c is also affected, here
 * the following code will be used:
 *    src += TkUtfToUniChar(src, &ch);
 *    ...
 *    ch = Tcl_UniCharToUpper(ch);
 *
 * But in general Tcl_UniCharToUpper will deliver wrong results here,
 * because of the truncation of 32 bit to 16 bit.
 */
# error "With TCL_UTF_MAX > 4 function TkUtfToUniChar() may return wrong values, the text widget cannot be provided when TCL_UTF_MAX > 4. The author of this TCL_UTF_MAX > 4 stuff has to develop his private text widget version, which can handle pseudo UTF-8 strings without the use of The Tcl_Uni* functions. The author of the text widget is not willing to re-implement the Tcl_Uni* for these psuedo UTF-8 strings. See also function GetLineBreakFunc() about the severe problems with this TCL_UTF_MAX > 4 hack."
#endif

			    if (!Tcl_UniCharIsWordChar(ch)) {
				break;
			    }
			    if (offset > 0) {
				const char *prevPtr;
				prevPtr = Tcl_UtfPrev(segPtr->body.chars + offset, segPtr->body.chars);
				chSize = segPtr->body.chars + offset - prevPtr;
			    }
			    firstChar = false;
			}
			if (offset == 0) {
			    TkTextIndexBackChars(textPtr, indexPtr, 1, indexPtr, mode);
			    segPtr = TkTextIndexGetContentSegment(indexPtr, &offset);
			    if (offset < chSize && indexPtr->priv.byteIndex == 0) {
				return p;
			    }
			} else if ((indexPtr->priv.byteIndex -= chSize) == 0) {
			    indexPtr->priv.segPtr = segPtr;
			    indexPtr->priv.isCharSegment = segPtr->typePtr == &tkTextCharType;
			    return p;
			} else if ((offset -= chSize) < 0) {
			    do {
				segPtr = segPtr->prevPtr;
				assert(segPtr);
			    } while (segPtr->size == 0);
			    offset = 0;
			}
		    }

		    indexPtr->priv.segPtr = segPtr;
		    indexPtr->priv.isCharSegment = segPtr->typePtr == &tkTextCharType;
		    if (!firstChar) {
			TkTextIndexForwChars(textPtr, indexPtr, 1, indexPtr, mode);
		    }
		    return p;
		}
		break;
	    }
	    break;
	}
    }

    return NULL;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 * vi:set ts=8 sw=4:
 */