Tk Source Code

Artifact [3a0f5445]
Login

Artifact 3a0f54457fe241434cdceae3b700e9f25d7e9bdd7c79e71bc0ba40f71edc0cc6:


     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
   100
   101
   102
   103
   104
   105
   106
   107
   108
   109
   110
   111
   112
   113
   114
   115
   116
   117
   118
   119
   120
   121
   122
   123
   124
   125
   126
   127
   128
   129
   130
   131
   132
   133
   134
   135
   136
   137
   138
   139
   140
   141
   142
   143
   144
   145
   146
   147
   148
   149
   150
   151
   152
   153
   154
   155
   156
   157
   158
   159
   160
   161
   162
   163
   164
   165
   166
   167
   168
   169
   170
   171
   172
   173
   174
   175
   176
   177
   178
   179
   180
   181
   182
   183
   184
   185
   186
   187
   188
   189
   190
   191
   192
   193
   194
   195
   196
   197
   198
   199
   200
   201
   202
   203
   204
   205
   206
   207
   208
   209
   210
   211
   212
   213
   214
   215
   216
   217
   218
   219
   220
   221
   222
   223
   224
   225
   226
   227
   228
   229
   230
   231
   232
   233
   234
   235
   236
   237
   238
   239
   240
   241
   242
   243
   244
   245
   246
   247
   248
   249
   250
   251
   252
   253
   254
   255
   256
   257
   258
   259
   260
   261
   262
   263
   264
   265
   266
   267
   268
   269
   270
   271
   272
   273
   274
   275
   276
   277
   278
   279
   280
   281
   282
   283
   284
   285
   286
   287
   288
   289
   290
   291
   292
   293
   294
   295
   296
   297
   298
   299
   300
   301
   302
   303
   304
   305
   306
   307
   308
   309
   310
   311
   312
   313
   314
   315
   316
   317
   318
   319
   320
   321
   322
   323
   324
   325
   326
   327
   328
   329
   330
   331
   332
   333
   334
   335
   336
   337
   338
   339
   340
   341
   342
   343
   344
   345
   346
   347
   348
   349
   350
   351
   352
   353
   354
   355
   356
   357
   358
   359
   360
   361
   362
   363
   364
   365
   366
   367
   368
   369
   370
   371
   372
   373
   374
   375
   376
   377
   378
   379
   380
   381
   382
   383
   384
   385
   386
   387
   388
   389
   390
   391
   392
   393
   394
   395
   396
   397
   398
   399
   400
   401
   402
   403
   404
   405
   406
   407
   408
   409
   410
   411
   412
   413
   414
   415
   416
   417
   418
   419
   420
   421
   422
   423
   424
   425
   426
   427
   428
   429
   430
   431
   432
   433
   434
   435
   436
   437
   438
   439
   440
   441
   442
   443
   444
   445
   446
   447
   448
   449
   450
   451
   452
   453
   454
   455
   456
   457
   458
   459
   460
   461
   462
   463
   464
   465
   466
   467
   468
   469
   470
   471
   472
   473
   474
   475
   476
   477
   478
   479
   480
   481
   482
   483
   484
   485
   486
   487
   488
   489
   490
   491
   492
   493
   494
   495
   496
   497
   498
   499
   500
   501
   502
   503
   504
   505
   506
   507
   508
   509
   510
   511
   512
   513
   514
   515
   516
   517
   518
   519
   520
   521
   522
   523
   524
   525
   526
   527
   528
   529
   530
   531
   532
   533
   534
   535
   536
   537
   538
   539
   540
   541
   542
   543
   544
   545
   546
   547
   548
   549
   550
   551
   552
   553
   554
   555
   556
   557
   558
   559
   560
   561
   562
   563
   564
   565
   566
   567
   568
   569
   570
   571
   572
   573
   574
   575
   576
   577
   578
   579
   580
   581
   582
   583
   584
   585
   586
   587
   588
   589
   590
   591
   592
   593
   594
   595
   596
   597
   598
   599
   600
   601
   602
   603
   604
   605
   606
   607
   608
   609
   610
   611
   612
   613
   614
   615
   616
   617
   618
   619
   620
   621
   622
   623
   624
   625
   626
   627
   628
   629
   630
   631
   632
   633
   634
   635
   636
   637
   638
   639
   640
   641
   642
   643
   644
   645
   646
   647
   648
   649
   650
   651
   652
   653
   654
   655
   656
   657
   658
   659
   660
   661
   662
   663
   664
   665
   666
   667
   668
   669
   670
   671
   672
   673
   674
   675
   676
   677
   678
   679
   680
   681
   682
   683
   684
   685
   686
   687
   688
   689
   690
   691
   692
   693
   694
   695
   696
   697
   698
   699
   700
   701
   702
   703
   704
   705
   706
   707
   708
   709
   710
   711
   712
   713
   714
   715
   716
   717
   718
   719
   720
   721
   722
   723
   724
   725
   726
   727
   728
   729
   730
   731
   732
   733
   734
   735
   736
   737
   738
   739
   740
   741
   742
   743
   744
   745
   746
   747
   748
   749
   750
   751
   752
   753
   754
   755
   756
   757
   758
   759
   760
   761
   762
   763
   764
   765
   766
   767
   768
   769
   770
   771
   772
   773
   774
   775
   776
   777
   778
   779
   780
   781
   782
   783
   784
   785
   786
   787
   788
   789
   790
   791
   792
   793
   794
   795
   796
   797
   798
   799
   800
   801
   802
   803
   804
   805
   806
   807
   808
   809
   810
   811
   812
   813
   814
   815
   816
   817
   818
   819
   820
   821
   822
   823
   824
   825
   826
   827
   828
   829
   830
   831
   832
   833
   834
   835
   836
   837
   838
   839
   840
   841
   842
   843
   844
   845
   846
   847
   848
   849
   850
   851
   852
   853
   854
   855
   856
   857
   858
   859
   860
   861
   862
   863
   864
   865
   866
   867
   868
   869
   870
   871
   872
   873
   874
   875
   876
   877
   878
   879
   880
   881
   882
   883
   884
   885
   886
   887
   888
   889
   890
   891
   892
   893
   894
   895
   896
   897
   898
   899
   900
   901
   902
   903
   904
   905
   906
   907
   908
   909
   910
   911
   912
   913
   914
   915
   916
   917
   918
   919
   920
   921
   922
   923
   924
   925
   926
   927
   928
   929
   930
   931
   932
   933
   934
   935
   936
   937
   938
   939
   940
   941
   942
   943
   944
   945
   946
   947
   948
   949
   950
   951
   952
   953
   954
   955
   956
   957
   958
   959
   960
   961
   962
   963
   964
   965
   966
   967
   968
   969
   970
   971
   972
   973
   974
   975
   976
   977
   978
   979
   980
   981
   982
   983
   984
   985
   986
   987
   988
   989
   990
   991
   992
   993
   994
   995
   996
   997
   998
   999
  1000
  1001
  1002
  1003
  1004
  1005
  1006
  1007
  1008
  1009
  1010
  1011
  1012
  1013
  1014
  1015
  1016
  1017
  1018
  1019
  1020
  1021
  1022
  1023
  1024
  1025
  1026
  1027
  1028
  1029
  1030
  1031
  1032
  1033
  1034
  1035
  1036
  1037
  1038
  1039
  1040
  1041
  1042
  1043
  1044
  1045
  1046
  1047
  1048
  1049
  1050
  1051
  1052
  1053
  1054
  1055
  1056
  1057
  1058
  1059
  1060
  1061
  1062
  1063
  1064
  1065
  1066
  1067
  1068
  1069
  1070
  1071
  1072
  1073
  1074
  1075
  1076
  1077
  1078
  1079
  1080
  1081
  1082
  1083
  1084
  1085
  1086
  1087
  1088
  1089
  1090
  1091
  1092
  1093
  1094
  1095
  1096
  1097
  1098
  1099
  1100
  1101
  1102
  1103
  1104
  1105
  1106
  1107
  1108
  1109
  1110
  1111
  1112
  1113
  1114
  1115
  1116
  1117
  1118
  1119
  1120
  1121
  1122
  1123
  1124
  1125
  1126
  1127
  1128
  1129
  1130
  1131
  1132
  1133
  1134
  1135
  1136
  1137
  1138
  1139
  1140
  1141
  1142
  1143
  1144
  1145
  1146
  1147
  1148
  1149
  1150
  1151
  1152
  1153
  1154
  1155
  1156
  1157
  1158
  1159
  1160
  1161
  1162
  1163
  1164
  1165
  1166
  1167
  1168
  1169
  1170
  1171
  1172
  1173
  1174
  1175
  1176
  1177
  1178
  1179
  1180
  1181
  1182
  1183
  1184
  1185
  1186
  1187
  1188
  1189
  1190
  1191
  1192
  1193
  1194
  1195
  1196
  1197
  1198
  1199
  1200
  1201
  1202
  1203
  1204
  1205
  1206
  1207
  1208
  1209
  1210
  1211
  1212
  1213
  1214
  1215
  1216
  1217
  1218
  1219
  1220
  1221
  1222
  1223
  1224
  1225
  1226
  1227
  1228
  1229
  1230
  1231
  1232
  1233
  1234
  1235
  1236
  1237
  1238
  1239
  1240
  1241
  1242
  1243
  1244
  1245
  1246
  1247
  1248
  1249
  1250
  1251
  1252
  1253
  1254
  1255
  1256
  1257
  1258
  1259
  1260
  1261
  1262
  1263
  1264
  1265
  1266
  1267
  1268
  1269
  1270
  1271
  1272
  1273
  1274
  1275
  1276
  1277
  1278
  1279
  1280
  1281
  1282
  1283
  1284
  1285
  1286
  1287
  1288
  1289
  1290
  1291
  1292
  1293
  1294
  1295
  1296
  1297
  1298
  1299
  1300
  1301
  1302
  1303
  1304
  1305
  1306
  1307
  1308
  1309
  1310
  1311
  1312
  1313
  1314
  1315
  1316
  1317
  1318
  1319
  1320
  1321
  1322
  1323
  1324
  1325
  1326
  1327
  1328
  1329
  1330
  1331
  1332
  1333
  1334
  1335
  1336
  1337
  1338
  1339
  1340
  1341
  1342
  1343
  1344
  1345
  1346
  1347
  1348
  1349
  1350
  1351
  1352
  1353
  1354
  1355
  1356
  1357
  1358
  1359
  1360
  1361
  1362
  1363
  1364
  1365
  1366
  1367
  1368
  1369
  1370
  1371
  1372
  1373
  1374
  1375
  1376
  1377
  1378
  1379
  1380
  1381
  1382
  1383
  1384
  1385
  1386
  1387
  1388
  1389
  1390
  1391
  1392
  1393
  1394
  1395
  1396
  1397
  1398
  1399
  1400
  1401
  1402
  1403
  1404
  1405
  1406
  1407
  1408
  1409
  1410
  1411
  1412
  1413
  1414
  1415
  1416
  1417
  1418
  1419
  1420
  1421
  1422
  1423
  1424
  1425
  1426
  1427
  1428
  1429
  1430
  1431
  1432
  1433
  1434
  1435
  1436
  1437
  1438
  1439
  1440
  1441
  1442
  1443
  1444
  1445
  1446
  1447
  1448
  1449
  1450
  1451
  1452
  1453
  1454
  1455
  1456
  1457
  1458
  1459
  1460
  1461
  1462
  1463
  1464
  1465
  1466
  1467
  1468
  1469
  1470
  1471
  1472
  1473
  1474
  1475
  1476
  1477
  1478
  1479
  1480
  1481
  1482
  1483
  1484
  1485
  1486
  1487
  1488
  1489
  1490
  1491
  1492
  1493
  1494
  1495
  1496
  1497
  1498
  1499
  1500
  1501
  1502
  1503
  1504
  1505
  1506
  1507
  1508
  1509
  1510
  1511
  1512
  1513
  1514
  1515
  1516
  1517
  1518
  1519
  1520
  1521
  1522
  1523
  1524
  1525
  1526
  1527
  1528
  1529
  1530
  1531
  1532
  1533
  1534
  1535
  1536
  1537
  1538
  1539
  1540
  1541
  1542
  1543
  1544
  1545
  1546
  1547
  1548
  1549
  1550
  1551
  1552
  1553
  1554
  1555
  1556
  1557
  1558
  1559
  1560
  1561
  1562
  1563
  1564
  1565
  1566
  1567
  1568
  1569
  1570
  1571
  1572
  1573
  1574
  1575
  1576
  1577
  1578
  1579
  1580
  1581
  1582
  1583
  1584
  1585
  1586
  1587
  1588
  1589
  1590
  1591
  1592
  1593
  1594
  1595
  1596
  1597
  1598
  1599
  1600
  1601
  1602
  1603
  1604
  1605
  1606
  1607
  1608
  1609
  1610
  1611
  1612
  1613
  1614
  1615
  1616
  1617
  1618
  1619
  1620
  1621
  1622
  1623
  1624
  1625
  1626
  1627
  1628
  1629
  1630
  1631
  1632
  1633
  1634
  1635
  1636
  1637
  1638
  1639
  1640
  1641
  1642
  1643
  1644
  1645
  1646
  1647
  1648
  1649
  1650
  1651
  1652
  1653
  1654
  1655
  1656
  1657
  1658
  1659
  1660
  1661
  1662
  1663
  1664
  1665
  1666
  1667
  1668
  1669
  1670
  1671
  1672
  1673
  1674
  1675
  1676
  1677
  1678
  1679
  1680
  1681
  1682
  1683
  1684
  1685
  1686
  1687
  1688
  1689
  1690
  1691
  1692
  1693
  1694
  1695
  1696
  1697
  1698
  1699
  1700
  1701
  1702
  1703
  1704
  1705
  1706
  1707
  1708
  1709
  1710
  1711
  1712
  1713
  1714
  1715
  1716
  1717
  1718
  1719
  1720
  1721
  1722
  1723
  1724
  1725
  1726
  1727
  1728
  1729
  1730
  1731
  1732
  1733
  1734
  1735
  1736
  1737
  1738
  1739
  1740
  1741
  1742
  1743
  1744
  1745
  1746
  1747
  1748
  1749
  1750
  1751
  1752
  1753
  1754
  1755
  1756
  1757
  1758
  1759
  1760
  1761
  1762
  1763
  1764
  1765
  1766
  1767
  1768
  1769
  1770
  1771
  1772
  1773
  1774
  1775
  1776
  1777
  1778
  1779
  1780
  1781
  1782
  1783
  1784
  1785
  1786
  1787
  1788
  1789
  1790
  1791
  1792
  1793
  1794
  1795
  1796
  1797
  1798
  1799
  1800
  1801
  1802
  1803
  1804
  1805
  1806
  1807
  1808
  1809
  1810
  1811
  1812
  1813
  1814
  1815
  1816
  1817
  1818
  1819
  1820
  1821
  1822
  1823
  1824
  1825
  1826
  1827
  1828
  1829
  1830
  1831
  1832
  1833
  1834
  1835
  1836
  1837
  1838
  1839
  1840
  1841
  1842
  1843
  1844
  1845
  1846
  1847
  1848
  1849
  1850
  1851
  1852
  1853
  1854
  1855
  1856
  1857
  1858
  1859
  1860
  1861
  1862
  1863
  1864
  1865
  1866
  1867
  1868
  1869
  1870
  1871
  1872
  1873
  1874
  1875
  1876
  1877
  1878
  1879
  1880
  1881
  1882
  1883
  1884
  1885
  1886
  1887
  1888
  1889
  1890
  1891
  1892
  1893
  1894
  1895
  1896
  1897
  1898
  1899
  1900
  1901
  1902
  1903
  1904
  1905
  1906
  1907
  1908
  1909
  1910
  1911
  1912
  1913
  1914
  1915
  1916
  1917
  1918
  1919
  1920
  1921
  1922
  1923
  1924
  1925
  1926
  1927
  1928
  1929
  1930
  1931
  1932
  1933
  1934
  1935
  1936
  1937
  1938
  1939
  1940
  1941
  1942
  1943
  1944
  1945
  1946
  1947
  1948
  1949
  1950
  1951
  1952
  1953
  1954
  1955
  1956
  1957
  1958
  1959
  1960
  1961
  1962
  1963
  1964
  1965
  1966
  1967
  1968
  1969
  1970
  1971
  1972
  1973
  1974
  1975
  1976
  1977
  1978
  1979
  1980
  1981
  1982
  1983
  1984
  1985
  1986
  1987
  1988
  1989
  1990
  1991
  1992
  1993
  1994
  1995
  1996
  1997
  1998
  1999
  2000
  2001
  2002
  2003
  2004
  2005
  2006
  2007
  2008
  2009
  2010
  2011
  2012
  2013
  2014
  2015
  2016
  2017
  2018
  2019
  2020
  2021
  2022
  2023
  2024
  2025
  2026
  2027
  2028
  2029
  2030
  2031
  2032
  2033
  2034
  2035
  2036
  2037
  2038
  2039
  2040
  2041
  2042
  2043
  2044
  2045
  2046
  2047
  2048
  2049
  2050
  2051
  2052
  2053
  2054
  2055
  2056
  2057
  2058
  2059
  2060
  2061
  2062
  2063
  2064
  2065
  2066
  2067
  2068
  2069
  2070
  2071
  2072
  2073
  2074
  2075
  2076
  2077
  2078
  2079
  2080
  2081
  2082
  2083
  2084
  2085
  2086
  2087
  2088
  2089
  2090
  2091
  2092
  2093
  2094
  2095
  2096
  2097
  2098
  2099
  2100
  2101
  2102
  2103
  2104
  2105
  2106
  2107
  2108
  2109
  2110
  2111
  2112
  2113
  2114
  2115
  2116
  2117
  2118
  2119
  2120
  2121
  2122
  2123
  2124
  2125
  2126
  2127
  2128
  2129
  2130
  2131
  2132
  2133
  2134
  2135
  2136
  2137
  2138
  2139
  2140
  2141
  2142
  2143
  2144
  2145
  2146
  2147
  2148
  2149
  2150
  2151
  2152
  2153
  2154
  2155
  2156
  2157
  2158
  2159
  2160
  2161
  2162
  2163
  2164
  2165
  2166
  2167
  2168
  2169
  2170
  2171
  2172
  2173
  2174
  2175
  2176
  2177
  2178
  2179
  2180
  2181
  2182
  2183
  2184
  2185
  2186
  2187
  2188
  2189
  2190
  2191
  2192
  2193
  2194
  2195
  2196
  2197
  2198
  2199
  2200
  2201
  2202
  2203
  2204
  2205
  2206
  2207
  2208
  2209
  2210
  2211
  2212
  2213
  2214
  2215
  2216
  2217
  2218
  2219
  2220
  2221
  2222
  2223
  2224
  2225
  2226
  2227
  2228
  2229
  2230
  2231
  2232
  2233
  2234
  2235
  2236
  2237
  2238
  2239
  2240
  2241
  2242
  2243
  2244
  2245
  2246
  2247
  2248
  2249
  2250
  2251
  2252
  2253
  2254
  2255
  2256
  2257
  2258
  2259
  2260
  2261
  2262
  2263
  2264
  2265
  2266
  2267
  2268
  2269
  2270
  2271
  2272
  2273
  2274
  2275
  2276
  2277
  2278
  2279
  2280
  2281
  2282
  2283
  2284
  2285
  2286
  2287
  2288
  2289
  2290
  2291
  2292
  2293
  2294
  2295
  2296
  2297
  2298
  2299
  2300
  2301
  2302
  2303
  2304
  2305
  2306
  2307
  2308
  2309
  2310
  2311
  2312
  2313
  2314
  2315
  2316
  2317
  2318
  2319
  2320
  2321
  2322
  2323
  2324
  2325
  2326
  2327
  2328
  2329
  2330
  2331
  2332
  2333
  2334
  2335
  2336
  2337
  2338
  2339
  2340
  2341
  2342
  2343
  2344
  2345
  2346
  2347
  2348
  2349
  2350
  2351
  2352
  2353
  2354
  2355
  2356
  2357
  2358
  2359
  2360
  2361
  2362
  2363
  2364
  2365
  2366
  2367
  2368
  2369
  2370
  2371
  2372
  2373
  2374
  2375
  2376
  2377
  2378
  2379
  2380
  2381
  2382
  2383
  2384
  2385
  2386
  2387
  2388
  2389
  2390
  2391
  2392
  2393
  2394
  2395
  2396
  2397
  2398
  2399
  2400
  2401
  2402
  2403
  2404
  2405
  2406
  2407
  2408
  2409
  2410
  2411
  2412
  2413
  2414
  2415
  2416
  2417
  2418
  2419
  2420
  2421
  2422
  2423
  2424
  2425
  2426
  2427
  2428
  2429
  2430
  2431
  2432
  2433
  2434
  2435
  2436
  2437
  2438
  2439
  2440
  2441
  2442
  2443
  2444
  2445
  2446
  2447
  2448
  2449
  2450
  2451
  2452
  2453
  2454
  2455
  2456
  2457
  2458
  2459
  2460
  2461
  2462
  2463
  2464
  2465
  2466
  2467
  2468
  2469
  2470
  2471
  2472
  2473
  2474
  2475
  2476
  2477
  2478
  2479
  2480
  2481
  2482
  2483
  2484
  2485
  2486
  2487
  2488
  2489
  2490
  2491
  2492
  2493
  2494
  2495
  2496
  2497
  2498
  2499
  2500
  2501
  2502
  2503
  2504
  2505
  2506
  2507
  2508
  2509
  2510
  2511
  2512
  2513
  2514
  2515
  2516
  2517
  2518
  2519
  2520
  2521
  2522
  2523
  2524
  2525
  2526
  2527
  2528
  2529
  2530
  2531
  2532
  2533
  2534
  2535
  2536
  2537
  2538
  2539
  2540
  2541
  2542
  2543
  2544
  2545
  2546
  2547
  2548
  2549
  2550
  2551
  2552
  2553
  2554
  2555
  2556
  2557
  2558
  2559
  2560
  2561
  2562
  2563
  2564
  2565
  2566
  2567
  2568
  2569
  2570
  2571
  2572
  2573
  2574
  2575
  2576
  2577
  2578
  2579
  2580
  2581
  2582
  2583
  2584
  2585
  2586
  2587
  2588
  2589
  2590
  2591
  2592
  2593
  2594
  2595
  2596
  2597
  2598
  2599
  2600
  2601
  2602
  2603
  2604
  2605
  2606
  2607
  2608
  2609
  2610
  2611
  2612
  2613
  2614
  2615
  2616
  2617
  2618
  2619
  2620
  2621
  2622
  2623
  2624
  2625
  2626
  2627
  2628
  2629
  2630
  2631
  2632
  2633
  2634
  2635
  2636
  2637
  2638
  2639
  2640
  2641
  2642
  2643
  2644
  2645
  2646
  2647
  2648
  2649
  2650
  2651
  2652
  2653
  2654
  2655
  2656
  2657
  2658
  2659
  2660
  2661
  2662
  2663
  2664
  2665
  2666
  2667
  2668
  2669
  2670
  2671
  2672
  2673
  2674
  2675
  2676
  2677
  2678
  2679
  2680
  2681
  2682
  2683
  2684
  2685
  2686
  2687
  2688
  2689
  2690
  2691
  2692
  2693
  2694
  2695
  2696
  2697
  2698
  2699
  2700
  2701
  2702
  2703
  2704
  2705
  2706
  2707
  2708
  2709
  2710
  2711
  2712
  2713
  2714
  2715
  2716
  2717
  2718
  2719
  2720
  2721
  2722
  2723
  2724
  2725
  2726
  2727
  2728
  2729
  2730
  2731
  2732
  2733
  2734
  2735
  2736
  2737
  2738
  2739
  2740
  2741
  2742
  2743
  2744
  2745
  2746
  2747
  2748
  2749
  2750
  2751
  2752
  2753
  2754
  2755
  2756
  2757
  2758
  2759
  2760
  2761
  2762
  2763
  2764
  2765
  2766
  2767
  2768
  2769
  2770
  2771
  2772
  2773
  2774
  2775
  2776
  2777
  2778
  2779
  2780
  2781
  2782
  2783
  2784
  2785
  2786
  2787
  2788
  2789
  2790
  2791
  2792
  2793
  2794
  2795
  2796
  2797
  2798
  2799
  2800
  2801
  2802
  2803
  2804
  2805
  2806
  2807
  2808
  2809
  2810
  2811
  2812
  2813
  2814
  2815
  2816
  2817
  2818
  2819
  2820
  2821
  2822
  2823
  2824
  2825
  2826
  2827
  2828
  2829
  2830
  2831
  2832
  2833
  2834
  2835
  2836
  2837
  2838
  2839
  2840
  2841
  2842
  2843
  2844
  2845
  2846
  2847
  2848
  2849
  2850
  2851
  2852
  2853
  2854
  2855
  2856
  2857
  2858
  2859
  2860
  2861
  2862
  2863
  2864
  2865
  2866
  2867
  2868
  2869
  2870
  2871
  2872
  2873
  2874
  2875
  2876
  2877
  2878
  2879
  2880
  2881
  2882
  2883
  2884
  2885
  2886
  2887
  2888
  2889
  2890
  2891
  2892
  2893
  2894
  2895
  2896
  2897
  2898
  2899
  2900
  2901
  2902
  2903
  2904
  2905
  2906
  2907
  2908
  2909
  2910
  2911
  2912
  2913
  2914
  2915
  2916
  2917
  2918
  2919
  2920
  2921
  2922
  2923
  2924
  2925
  2926
  2927
  2928
  2929
  2930
  2931
  2932
  2933
  2934
  2935
  2936
  2937
  2938
  2939
  2940
  2941
  2942
  2943
  2944
  2945
  2946
  2947
  2948
  2949
  2950
  2951
  2952
  2953
  2954
  2955
  2956
  2957
  2958
  2959
  2960
  2961
  2962
  2963
  2964
  2965
  2966
  2967
  2968
  2969
  2970
  2971
  2972
  2973
  2974
  2975
  2976
  2977
  2978
  2979
  2980
  2981
  2982
  2983
  2984
  2985
  2986
  2987
  2988
  2989
  2990
  2991
  2992
  2993
  2994
  2995
  2996
  2997
  2998
  2999
  3000
  3001
  3002
  3003
  3004
  3005
  3006
  3007
  3008
  3009
  3010
  3011
  3012
  3013
  3014
  3015
  3016
  3017
  3018
  3019
  3020
  3021
  3022
  3023
  3024
  3025
  3026
  3027
  3028
  3029
  3030
  3031
  3032
  3033
  3034
  3035
  3036
  3037
  3038
  3039
  3040
  3041
  3042
  3043
  3044
  3045
  3046
  3047
  3048
  3049
  3050
  3051
  3052
  3053
  3054
  3055
  3056
  3057
  3058
  3059
  3060
  3061
  3062
  3063
  3064
  3065
  3066
  3067
  3068
  3069
  3070
  3071
  3072
  3073
  3074
  3075
  3076
  3077
  3078
  3079
  3080
  3081
  3082
  3083
  3084
  3085
  3086
  3087
  3088
  3089
  3090
  3091
  3092
  3093
  3094
  3095
  3096
  3097
  3098
  3099
  3100
  3101
  3102
  3103
  3104
  3105
  3106
  3107
  3108
  3109
  3110
  3111
  3112
  3113
  3114
  3115
  3116
  3117
  3118
  3119
  3120
  3121
  3122
  3123
  3124
  3125
  3126
  3127
  3128
  3129
  3130
  3131
  3132
  3133
  3134
  3135
  3136
  3137
  3138
  3139
  3140
  3141
  3142
  3143
  3144
  3145
  3146
  3147
  3148
  3149
  3150
  3151
  3152
  3153
  3154
  3155
  3156
  3157
  3158
  3159
  3160
  3161
  3162
  3163
  3164
  3165
  3166
  3167
  3168
  3169
  3170
  3171
  3172
  3173
  3174
  3175
  3176
  3177
  3178
  3179
  3180
  3181
  3182
  3183
  3184
  3185
  3186
  3187
  3188
  3189
  3190
  3191
  3192
  3193
  3194
  3195
  3196
  3197
  3198
  3199
  3200
  3201
  3202
  3203
  3204
  3205
  3206
  3207
  3208
  3209
  3210
  3211
  3212
  3213
  3214
  3215
  3216
  3217
  3218
  3219
  3220
  3221
  3222
  3223
  3224
  3225
  3226
  3227
  3228
  3229
  3230
  3231
  3232
  3233
  3234
  3235
  3236
  3237
  3238
  3239
  3240
  3241
  3242
  3243
  3244
  3245
  3246
  3247
  3248
  3249
  3250
  3251
  3252
  3253
  3254
  3255
  3256
  3257
  3258
  3259
  3260
  3261
  3262
  3263
  3264
  3265
  3266
  3267
  3268
  3269
  3270
  3271
  3272
  3273
  3274
  3275
  3276
  3277
  3278
  3279
  3280
  3281
  3282
  3283
  3284
  3285
  3286
  3287
  3288
  3289
  3290
  3291
  3292
  3293
  3294
  3295
  3296
  3297
  3298
  3299
  3300
  3301
  3302
  3303
  3304
  3305
  3306
  3307
  3308
  3309
  3310
  3311
  3312
  3313
  3314
  3315
  3316
  3317
  3318
  3319
  3320
  3321
  3322
  3323
  3324
  3325
  3326
  3327
  3328
  3329
  3330
  3331
  3332
  3333
  3334
  3335
  3336
  3337
  3338
  3339
  3340
  3341
  3342
  3343
  3344
  3345
  3346
  3347
  3348
  3349
  3350
  3351
  3352
  3353
  3354
  3355
  3356
  3357
  3358
  3359
  3360
  3361
  3362
  3363
  3364
  3365
  3366
  3367
  3368
  3369
  3370
  3371
  3372
  3373
  3374
  3375
  3376
  3377
  3378
  3379
  3380
  3381
  3382
  3383
  3384
  3385
  3386
  3387
  3388
  3389
  3390
  3391
  3392
  3393
  3394
  3395
  3396
  3397
  3398
  3399
  3400
  3401
  3402
  3403
  3404
  3405
  3406
  3407
  3408
  3409
  3410
  3411
  3412
  3413
  3414
  3415
  3416
  3417
  3418
  3419
  3420
  3421
  3422
  3423
  3424
  3425
  3426
  3427
  3428
  3429
  3430
  3431
  3432
  3433
  3434
  3435
  3436
  3437
  3438
  3439
  3440
  3441
  3442
  3443
  3444
  3445
  3446
  3447
  3448
  3449
  3450
  3451
  3452
  3453
  3454
  3455
  3456
  3457
  3458
  3459
  3460
  3461
  3462
  3463
  3464
  3465
  3466
  3467
  3468
  3469
  3470
  3471
  3472
  3473
  3474
  3475
  3476
  3477
  3478
  3479
  3480
  3481
  3482
  3483
  3484
  3485
  3486
  3487
  3488
  3489
  3490
  3491
  3492
  3493
  3494
  3495
  3496
  3497
  3498
  3499
  3500
  3501
  3502
  3503
  3504
  3505
  3506
  3507
  3508
  3509
  3510
  3511
  3512
  3513
  3514
  3515
  3516
  3517
  3518
  3519
  3520
  3521
  3522
  3523
  3524
  3525
  3526
  3527
  3528
  3529
  3530
  3531
  3532
  3533
  3534
  3535
  3536
  3537
  3538
  3539
  3540
  3541
  3542
  3543
  3544
  3545
  3546
  3547
  3548
  3549
  3550
  3551
  3552
  3553
  3554
  3555
  3556
  3557
  3558
  3559
  3560
  3561
  3562
  3563
  3564
  3565
  3566
  3567
  3568
  3569
  3570
  3571
  3572
  3573
  3574
  3575
  3576
  3577
  3578
  3579
  3580
  3581
  3582
  3583
  3584
  3585
  3586
  3587
  3588
  3589
  3590
  3591
  3592
  3593
  3594
  3595
  3596
  3597
  3598
  3599
  3600
  3601
  3602
  3603
  3604
  3605
  3606
  3607
  3608
  3609
  3610
  3611
  3612
  3613
  3614
  3615
  3616
  3617
  3618
  3619
  3620
  3621
  3622
  3623
  3624
  3625
  3626
  3627
  3628
  3629
  3630
  3631
  3632
  3633
  3634
  3635
  3636
  3637
  3638
  3639
  3640
  3641
  3642
  3643
  3644
  3645
  3646
  3647
  3648
  3649
  3650
  3651
  3652
  3653
  3654
  3655
  3656
  3657
  3658
  3659
  3660
  3661
  3662
  3663
  3664
  3665
  3666
  3667
  3668
  3669
  3670
  3671
  3672
  3673
  3674
  3675
  3676
  3677
  3678
  3679
  3680
  3681
  3682
  3683
  3684
  3685
  3686
  3687
  3688
  3689
  3690
  3691
  3692
  3693
  3694
  3695
  3696
  3697
  3698
  3699
  3700
  3701
  3702
  3703
  3704
  3705
  3706
  3707
  3708
  3709
  3710
  3711
  3712
  3713
  3714
  3715
  3716
  3717
  3718
  3719
  3720
  3721
  3722
  3723
  3724
  3725
  3726
  3727
  3728
  3729
  3730
  3731
  3732
  3733
  3734
  3735
  3736
  3737
  3738
  3739
  3740
  3741
  3742
  3743
  3744
  3745
  3746
  3747
  3748
  3749
  3750
  3751
  3752
  3753
  3754
  3755
  3756
  3757
  3758
  3759
  3760
  3761
  3762
  3763
  3764
  3765
  3766
  3767
  3768
  3769
  3770
  3771
  3772
  3773
  3774
  3775
  3776
  3777
  3778
  3779
  3780
  3781
  3782
  3783
  3784
  3785
  3786
  3787
  3788
  3789
  3790
  3791
  3792
  3793
  3794
  3795
  3796
  3797
  3798
  3799
  3800
  3801
  3802
  3803
  3804
  3805
  3806
  3807
  3808
  3809
  3810
  3811
  3812
  3813
  3814
  3815
  3816
  3817
  3818
  3819
  3820
  3821
  3822
  3823
  3824
  3825
  3826
  3827
  3828
  3829
  3830
  3831
  3832
  3833
  3834
  3835
  3836
  3837
  3838
  3839
  3840
  3841
  3842
  3843
  3844
  3845
  3846
  3847
  3848
  3849
  3850
  3851
  3852
  3853
  3854
  3855
  3856
  3857
  3858
  3859
  3860
  3861
  3862
  3863
  3864
  3865
  3866
  3867
  3868
  3869
  3870
  3871
  3872
  3873
  3874
  3875
  3876
  3877
  3878
  3879
  3880
  3881
  3882
  3883
  3884
  3885
  3886
  3887
  3888
  3889
  3890
  3891
  3892
  3893
  3894
  3895
  3896
  3897
  3898
  3899
  3900
  3901
  3902
  3903
  3904
  3905
  3906
  3907
  3908
  3909
  3910
  3911
  3912
  3913
  3914
  3915
  3916
  3917
  3918
  3919
  3920
  3921
  3922
  3923
  3924
  3925
  3926
  3927
  3928
  3929
  3930
  3931
  3932
  3933
  3934
  3935
  3936
  3937
  3938
  3939
  3940
  3941
  3942
  3943
  3944
  3945
  3946
  3947
  3948
  3949
  3950
  3951
  3952
  3953
  3954
  3955
  3956
  3957
  3958
  3959
  3960
  3961
  3962
  3963
  3964
  3965
  3966
  3967
  3968
  3969
  3970
  3971
  3972
  3973
  3974
  3975
  3976
  3977
  3978
  3979
  3980
  3981
  3982
  3983
  3984
  3985
  3986
  3987
  3988
  3989
  3990
  3991
  3992
  3993
  3994
  3995
  3996
  3997
  3998
  3999
  4000
  4001
  4002
  4003
  4004
  4005
  4006
  4007
  4008
  4009
  4010
  4011
  4012
  4013
  4014
  4015
  4016
  4017
  4018
  4019
  4020
  4021
  4022
  4023
  4024
  4025
  4026
  4027
  4028
  4029
  4030
  4031
  4032
  4033
  4034
  4035
  4036
  4037
  4038
  4039
  4040
  4041
  4042
  4043
  4044
  4045
  4046
  4047
  4048
  4049
  4050
  4051
  4052
  4053
  4054
  4055
  4056
  4057
  4058
  4059
  4060
  4061
  4062
  4063
  4064
  4065
  4066
  4067
  4068
  4069
  4070
  4071
  4072
  4073
  4074
  4075
  4076
  4077
  4078
  4079
  4080
  4081
  4082
  4083
  4084
  4085
  4086
  4087
  4088
  4089
  4090
  4091
  4092
  4093
  4094
  4095
  4096
  4097
  4098
  4099
  4100
  4101
  4102
  4103
  4104
  4105
  4106
  4107
  4108
  4109
  4110
  4111
  4112
  4113
  4114
  4115
  4116
  4117
  4118
  4119
  4120
  4121
  4122
  4123
  4124
  4125
  4126
  4127
  4128
  4129
  4130
  4131
  4132
  4133
  4134
  4135
  4136
  4137
  4138
  4139
  4140
  4141
  4142
  4143
  4144
  4145
  4146
  4147
  4148
  4149
  4150
  4151
  4152
  4153
  4154
  4155
  4156
  4157
  4158
  4159
  4160
  4161
  4162
  4163
  4164
  4165
  4166
  4167
  4168
  4169
  4170
  4171
  4172
  4173
  4174
  4175
  4176
  4177
  4178
  4179
  4180
  4181
  4182
  4183
  4184
  4185
  4186
  4187
  4188
  4189
  4190
  4191
  4192
  4193
  4194
  4195
  4196
  4197
  4198
  4199
  4200
  4201
  4202
  4203
  4204
  4205
  4206
  4207
  4208
  4209
  4210
  4211
  4212
  4213
  4214
  4215
  4216
  4217
  4218
  4219
  4220
  4221
  4222
  4223
  4224
  4225
  4226
  4227
  4228
  4229
  4230
  4231
  4232
  4233
  4234
  4235
  4236
  4237
  4238
  4239
  4240
  4241
  4242
  4243
  4244
  4245
  4246
  4247
  4248
  4249
  4250
  4251
  4252
  4253
  4254
  4255
  4256
  4257
  4258
  4259
  4260
  4261
  4262
  4263
  4264
  4265
  4266
  4267
  4268
  4269
  4270
  4271
  4272
  4273
  4274
  4275
  4276
  4277
  4278
  4279
  4280
  4281
  4282
  4283
  4284
  4285
  4286
  4287
  4288
  4289
  4290
  4291
  4292
  4293
  4294
  4295
  4296
  4297
  4298
  4299
  4300
  4301
  4302
  4303
  4304
  4305
  4306
  4307
  4308
  4309
  4310
  4311
  4312
  4313
  4314
  4315
  4316
  4317
  4318
  4319
  4320
  4321
  4322
  4323
  4324
  4325
  4326
  4327
  4328
  4329
  4330
  4331
  4332
  4333
  4334
  4335
  4336
  4337
  4338
  4339
  4340
  4341
  4342
  4343
  4344
  4345
  4346
  4347
  4348
  4349
  4350
  4351
  4352
  4353
  4354
  4355
  4356
  4357
  4358
  4359
  4360
  4361
  4362
  4363
  4364
  4365
  4366
  4367
  4368
  4369
  4370
  4371
  4372
  4373
  4374
  4375
  4376
  4377
  4378
  4379
  4380
  4381
  4382
  4383
  4384
  4385
  4386
  4387
  4388
  4389
  4390
  4391
  4392
  4393
  4394
  4395
  4396
  4397
  4398
  4399
  4400
  4401
  4402
  4403
  4404
  4405
  4406
  4407
  4408
  4409
  4410
  4411
  4412
  4413
  4414
  4415
  4416
  4417
  4418
  4419
  4420
  4421
  4422
  4423
  4424
  4425
  4426
  4427
  4428
  4429
  4430
  4431
  4432
  4433
  4434
  4435
  4436
  4437
  4438
  4439
  4440
  4441
  4442
  4443
  4444
  4445
  4446
  4447
  4448
  4449
  4450
  4451
  4452
  4453
  4454
  4455
  4456
  4457
  4458
  4459
  4460
  4461
  4462
  4463
  4464
  4465
  4466
  4467
  4468
  4469
  4470
  4471
  4472
  4473
  4474
  4475
  4476
  4477
  4478
  4479
  4480
  4481
  4482
  4483
  4484
  4485
  4486
  4487
  4488
  4489
  4490
  4491
  4492
  4493
  4494
  4495
  4496
  4497
  4498
  4499
  4500
  4501
  4502
  4503
  4504
  4505
  4506
  4507
  4508
  4509
  4510
  4511
  4512
  4513
  4514
  4515
  4516
  4517
  4518
  4519
  4520
  4521
  4522
  4523
  4524
  4525
  4526
  4527
  4528
  4529
  4530
  4531
  4532
  4533
  4534
  4535
  4536
  4537
  4538
  4539
  4540
  4541
  4542
  4543
  4544
  4545
  4546
  4547
  4548
  4549
  4550
  4551
  4552
  4553
  4554
  4555
  4556
  4557
  4558
  4559
  4560
  4561
  4562
  4563
  4564
  4565
  4566
  4567
  4568
  4569
  4570
  4571
  4572
  4573
  4574
  4575
  4576
  4577
  4578
  4579
  4580
  4581
  4582
  4583
  4584
  4585
  4586
  4587
  4588
  4589
  4590
  4591
  4592
  4593
  4594
  4595
  4596
  4597
  4598
  4599
  4600
  4601
  4602
  4603
  4604
  4605
  4606
  4607
  4608
  4609
  4610
  4611
  4612
  4613
  4614
  4615
  4616
  4617
  4618
  4619
  4620
  4621
  4622
  4623
  4624
  4625
  4626
  4627
  4628
  4629
  4630
  4631
  4632
  4633
  4634
  4635
  4636
  4637
  4638
  4639
  4640
  4641
  4642
  4643
  4644
  4645
  4646
  4647
  4648
  4649
  4650
  4651
  4652
  4653
  4654
  4655
  4656
  4657
  4658
  4659
  4660
  4661
  4662
  4663
  4664
  4665
  4666
  4667
  4668
  4669
  4670
  4671
  4672
  4673
  4674
  4675
  4676
  4677
  4678
  4679
  4680
  4681
  4682
  4683
  4684
  4685
  4686
  4687
  4688
  4689
  4690
  4691
  4692
  4693
  4694
  4695
  4696
  4697
  4698
  4699
  4700
  4701
  4702
  4703
  4704
  4705
  4706
  4707
  4708
  4709
  4710
  4711
  4712
  4713
  4714
  4715
  4716
  4717
  4718
  4719
  4720
  4721
  4722
  4723
  4724
  4725
  4726
  4727
  4728
  4729
  4730
  4731
  4732
  4733
  4734
  4735
  4736
  4737
  4738
  4739
  4740
  4741
  4742
  4743
  4744
  4745
  4746
  4747
  4748
  4749
  4750
  4751
  4752
  4753
  4754
  4755
  4756
  4757
  4758
  4759
  4760
  4761
  4762
  4763
  4764
  4765
  4766
  4767
  4768
  4769
  4770
  4771
  4772
  4773
  4774
  4775
  4776
  4777
  4778
  4779
  4780
  4781
  4782
  4783
  4784
  4785
  4786
  4787
  4788
  4789
  4790
  4791
  4792
  4793
  4794
  4795
  4796
  4797
  4798
  4799
  4800
  4801
  4802
  4803
  4804
  4805
  4806
  4807
  4808
  4809
  4810
  4811
  4812
  4813
  4814
  4815
  4816
  4817
  4818
  4819
  4820
  4821
  4822
  4823
  4824
  4825
  4826
  4827
  4828
  4829
  4830
  4831
  4832
  4833
  4834
  4835
  4836
  4837
  4838
  4839
  4840
  4841
  4842
  4843
  4844
  4845
  4846
  4847
  4848
  4849
  4850
  4851
  4852
  4853
  4854
  4855
  4856
  4857
  4858
  4859
  4860
  4861
  4862
  4863
  4864
  4865
  4866
  4867
  4868
  4869
  4870
  4871
  4872
  4873
  4874
  4875
  4876
  4877
  4878
  4879
  4880
  4881
  4882
  4883
  4884
  4885
  4886
  4887
  4888
  4889
  4890
  4891
  4892
  4893
  4894
  4895
  4896
  4897
  4898
  4899
  4900
  4901
  4902
  4903
  4904
  4905
  4906
  4907
  4908
  4909
  4910
  4911
  4912
  4913
  4914
  4915
  4916
  4917
  4918
  4919
  4920
  4921
  4922
  4923
  4924
  4925
  4926
  4927
  4928
  4929
  4930
  4931
  4932
  4933
  4934
  4935
  4936
  4937
  4938
  4939
  4940
  4941
  4942
  4943
  4944
  4945
  4946
  4947
  4948
  4949
  4950
  4951
  4952
  4953
  4954
  4955
  4956
  4957
  4958
  4959
  4960
  4961
  4962
  4963
  4964
  4965
  4966
  4967
  4968
  4969
  4970
  4971
  4972
  4973
  4974
  4975
  4976
  4977
  4978
  4979
  4980
  4981
  4982
  4983
  4984
  4985
  4986
  4987
  4988
  4989
  4990
  4991
  4992
  4993
  4994
  4995
  4996
  4997
  4998
  4999
  5000
  5001
  5002
  5003
  5004
  5005
  5006
  5007
  5008
  5009
  5010
  5011
  5012
  5013
  5014
  5015
  5016
  5017
  5018
  5019
  5020
  5021
  5022
  5023
  5024
  5025
  5026
  5027
  5028
  5029
  5030
  5031
  5032
  5033
  5034
  5035
  5036
  5037
  5038
  5039
  5040
  5041
  5042
  5043
  5044
  5045
  5046
  5047
  5048
  5049
  5050
  5051
  5052
  5053
  5054
  5055
  5056
  5057
  5058
  5059
  5060
  5061
  5062
  5063
  5064
  5065
  5066
  5067
  5068
  5069
  5070
  5071
  5072
  5073
  5074
  5075
  5076
  5077
  5078
  5079
  5080
  5081
  5082
  5083
  5084
  5085
  5086
  5087
  5088
  5089
  5090
  5091
  5092
  5093
  5094
  5095
  5096
  5097
  5098
  5099
  5100
  5101
  5102
  5103
  5104
  5105
  5106
  5107
  5108
  5109
  5110
  5111
  5112
  5113
  5114
  5115
  5116
  5117
  5118
  5119
  5120
  5121
  5122
  5123
  5124
  5125
  5126
  5127
  5128
  5129
  5130
  5131
  5132
  5133
  5134
  5135
  5136
  5137
  5138
  5139
  5140
  5141
  5142
  5143
  5144
  5145
  5146
  5147
  5148
  5149
  5150
  5151
  5152
  5153
  5154
  5155
  5156
  5157
  5158
  5159
  5160
  5161
  5162
  5163
  5164
  5165
  5166
  5167
  5168
  5169
  5170
  5171
  5172
  5173
  5174
  5175
  5176
  5177
  5178
  5179
  5180
  5181
  5182
  5183
  5184
  5185
  5186
  5187
  5188
  5189
  5190
  5191
  5192
  5193
  5194
  5195
  5196
  5197
  5198
  5199
  5200
  5201
  5202
  5203
  5204
  5205
  5206
  5207
  5208
  5209
  5210
  5211
  5212
  5213
  5214
  5215
  5216
  5217
  5218
  5219
  5220
  5221
  5222
  5223
  5224
  5225
  5226
  5227
  5228
  5229
  5230
  5231
  5232
  5233
  5234
  5235
  5236
  5237
  5238
  5239
  5240
  5241
  5242
  5243
  5244
  5245
  5246
  5247
  5248
  5249
  5250
  5251
  5252
  5253
  5254
  5255
  5256
  5257
  5258
  5259
  5260
  5261
  5262
  5263
  5264
  5265
  5266
  5267
  5268
  5269
  5270
  5271
  5272
  5273
  5274
  5275
  5276
  5277
  5278
  5279
  5280
  5281
  5282
  5283
  5284
  5285
  5286
  5287
  5288
  5289
  5290
  5291
  5292
  5293
  5294
  5295
  5296
  5297
  5298
  5299
  5300
  5301
  5302
  5303
  5304
  5305
  5306
  5307
  5308
  5309
  5310
  5311
  5312
  5313
  5314
  5315
  5316
  5317
  5318
  5319
  5320
  5321
  5322
  5323
  5324
  5325
  5326
  5327
  5328
  5329
  5330
  5331
  5332
  5333
  5334
  5335
  5336
  5337
  5338
  5339
  5340
  5341
  5342
  5343
  5344
  5345
  5346
  5347
  5348
  5349
  5350
  5351
  5352
  5353
  5354
  5355
  5356
  5357
  5358
  5359
  5360
  5361
  5362
  5363
  5364
  5365
  5366
  5367
  5368
  5369
  5370
  5371
  5372
  5373
  5374
  5375
  5376
  5377
  5378
  5379
  5380
  5381
  5382
  5383
  5384
  5385
  5386
  5387
  5388
  5389
  5390
  5391
  5392
  5393
  5394
  5395
  5396
  5397
  5398
  5399
  5400
  5401
  5402
  5403
  5404
  5405
  5406
  5407
  5408
  5409
  5410
  5411
  5412
  5413
  5414
  5415
  5416
  5417
  5418
  5419
  5420
  5421
  5422
  5423
  5424
  5425
  5426
  5427
  5428
  5429
  5430
  5431
  5432
  5433
  5434
  5435
  5436
  5437
  5438
  5439
  5440
  5441
  5442
  5443
  5444
  5445
  5446
  5447
  5448
  5449
  5450
  5451
  5452
  5453
  5454
  5455
  5456
  5457
  5458
  5459
  5460
  5461
  5462
  5463
  5464
  5465
  5466
  5467
  5468
  5469
  5470
  5471
  5472
  5473
  5474
  5475
  5476
  5477
  5478
  5479
  5480
  5481
  5482
  5483
  5484
  5485
  5486
  5487
  5488
  5489
  5490
  5491
  5492
  5493
  5494
  5495
  5496
  5497
  5498
  5499
  5500
  5501
  5502
  5503
  5504
  5505
  5506
  5507
  5508
  5509
  5510
  5511
  5512
  5513
  5514
  5515
  5516
  5517
  5518
  5519
  5520
  5521
  5522
  5523
  5524
  5525
  5526
  5527
  5528
  5529
  5530
  5531
  5532
  5533
  5534
  5535
  5536
  5537
  5538
  5539
  5540
  5541
  5542
  5543
  5544
  5545
  5546
  5547
  5548
  5549
  5550
  5551
  5552
  5553
  5554
  5555
  5556
  5557
  5558
  5559
  5560
  5561
  5562
  5563
  5564
  5565
  5566
  5567
  5568
  5569
  5570
  5571
  5572
  5573
  5574
  5575
  5576
  5577
  5578
  5579
  5580
  5581
  5582
  5583
  5584
  5585
  5586
  5587
  5588
  5589
  5590
  5591
  5592
  5593
  5594
  5595
  5596
  5597
  5598
  5599
  5600
  5601
  5602
  5603
  5604
  5605
  5606
  5607
  5608
  5609
  5610
  5611
  5612
  5613
  5614
  5615
  5616
  5617
  5618
  5619
  5620
  5621
  5622
  5623
  5624
  5625
  5626
  5627
  5628
  5629
  5630
  5631
  5632
  5633
  5634
  5635
  5636
  5637
  5638
  5639
  5640
  5641
  5642
  5643
  5644
  5645
  5646
  5647
  5648
  5649
  5650
  5651
  5652
  5653
  5654
  5655
  5656
  5657
  5658
  5659
  5660
  5661
  5662
  5663
  5664
  5665
  5666
  5667
  5668
  5669
  5670
  5671
  5672
  5673
  5674
  5675
  5676
  5677
  5678
  5679
  5680
  5681
  5682
  5683
  5684
  5685
  5686
  5687
  5688
  5689
  5690
  5691
  5692
  5693
  5694
  5695
  5696
  5697
  5698
  5699
  5700
  5701
  5702
  5703
  5704
  5705
  5706
  5707
  5708
  5709
  5710
  5711
  5712
  5713
  5714
  5715
  5716
  5717
  5718
  5719
  5720
  5721
  5722
  5723
  5724
  5725
  5726
  5727
  5728
  5729
  5730
  5731
  5732
  5733
  5734
  5735
  5736
  5737
  5738
  5739
  5740
  5741
  5742
  5743
  5744
  5745
  5746
  5747
  5748
  5749
  5750
  5751
  5752
  5753
  5754
  5755
  5756
  5757
  5758
  5759
  5760
  5761
  5762
  5763
  5764
  5765
  5766
  5767
  5768
  5769
  5770
  5771
  5772
  5773
  5774
  5775
  5776
  5777
  5778
  5779
  5780
  5781
  5782
  5783
  5784
  5785
  5786
  5787
  5788
  5789
  5790
  5791
  5792
  5793
  5794
  5795
  5796
  5797
  5798
  5799
  5800
  5801
  5802
  5803
  5804
  5805
  5806
  5807
  5808
  5809
  5810
  5811
  5812
  5813
  5814
  5815
  5816
  5817
  5818
  5819
  5820
  5821
  5822
  5823
  5824
  5825
  5826
  5827
  5828
  5829
  5830
  5831
  5832
  5833
  5834
  5835
  5836
  5837
  5838
  5839
  5840
  5841
  5842
  5843
  5844
  5845
  5846
  5847
  5848
  5849
  5850
  5851
  5852
  5853
  5854
  5855
  5856
  5857
  5858
  5859
  5860
  5861
  5862
  5863
  5864
  5865
  5866
  5867
  5868
  5869
  5870
  5871
  5872
  5873
  5874
  5875
  5876
  5877
  5878
  5879
  5880
  5881
  5882
  5883
  5884
  5885
  5886
  5887
  5888
  5889
  5890
  5891
  5892
  5893
  5894
  5895
  5896
  5897
  5898
  5899
  5900
  5901
  5902
  5903
  5904
  5905
  5906
  5907
  5908
  5909
  5910
  5911
  5912
  5913
  5914
  5915
  5916
  5917
  5918
  5919
  5920
  5921
  5922
  5923
  5924
  5925
  5926
  5927
  5928
  5929
  5930
  5931
  5932
  5933
  5934
  5935
  5936
  5937
  5938
  5939
  5940
  5941
  5942
  5943
  5944
  5945
  5946
  5947
  5948
  5949
  5950
  5951
  5952
  5953
  5954
  5955
  5956
  5957
  5958
  5959
  5960
  5961
  5962
  5963
  5964
  5965
  5966
  5967
  5968
  5969
  5970
  5971
  5972
  5973
  5974
  5975
  5976
  5977
  5978
  5979
  5980
  5981
  5982
  5983
  5984
  5985
  5986
  5987
  5988
  5989
  5990
  5991
  5992
  5993
  5994
  5995
  5996
  5997
  5998
  5999
  6000
  6001
  6002
  6003
  6004
  6005
  6006
  6007
  6008
  6009
  6010
  6011
  6012
  6013
  6014
  6015
  6016
  6017
  6018
  6019
  6020
  6021
  6022
  6023
  6024
  6025
  6026
  6027
  6028
  6029
  6030
  6031
  6032
  6033
  6034
  6035
  6036
  6037
  6038
  6039
  6040
  6041
  6042
  6043
  6044
  6045
  6046
  6047
  6048
  6049
  6050
  6051
  6052
  6053
  6054
  6055
  6056
  6057
  6058
  6059
  6060
  6061
  6062
  6063
  6064
  6065
  6066
  6067
  6068
  6069
  6070
  6071
  6072
  6073
  6074
  6075
  6076
  6077
  6078
  6079
  6080
  6081
  6082
  6083
  6084
  6085
  6086
  6087
  6088
  6089
  6090
  6091
  6092
  6093
  6094
  6095
  6096
  6097
  6098
  6099
  6100
  6101
  6102
  6103
  6104
  6105
  6106
  6107
  6108
  6109
  6110
  6111
  6112
  6113
  6114
  6115
  6116
  6117
  6118
  6119
  6120
  6121
  6122
  6123
  6124
  6125
  6126
  6127
  6128
  6129
  6130
  6131
  6132
  6133
  6134
  6135
  6136
  6137
  6138
  6139
  6140
  6141
  6142
  6143
  6144
  6145
  6146
  6147
  6148
  6149
  6150
  6151
  6152
  6153
  6154
  6155
  6156
  6157
  6158
  6159
  6160
  6161
  6162
  6163
  6164
  6165
  6166
  6167
  6168
  6169
  6170
  6171
  6172
  6173
  6174
  6175
  6176
  6177
  6178
  6179
  6180
  6181
  6182
  6183
  6184
  6185
  6186
  6187
  6188
  6189
  6190
  6191
  6192
  6193
  6194
  6195
  6196
  6197
  6198
  6199
  6200
  6201
  6202
  6203
  6204
  6205
  6206
  6207
  6208
  6209
  6210
  6211
  6212
  6213
  6214
  6215
  6216
  6217
  6218
  6219
  6220
  6221
  6222
  6223
  6224
  6225
  6226
  6227
  6228
  6229
  6230
  6231
  6232
  6233
  6234
  6235
  6236
  6237
  6238
  6239
  6240
  6241
  6242
  6243
  6244
  6245
  6246
  6247
  6248
  6249
  6250
  6251
  6252
  6253
  6254
  6255
  6256
  6257
  6258
  6259
  6260
  6261
  6262
  6263
  6264
  6265
  6266
  6267
  6268
  6269
  6270
  6271
  6272
  6273
  6274
  6275
  6276
  6277
  6278
  6279
  6280
  6281
  6282
  6283
  6284
  6285
  6286
  6287
  6288
  6289
  6290
  6291
  6292
  6293
  6294
  6295
  6296
  6297
  6298
  6299
  6300
  6301
  6302
  6303
  6304
  6305
  6306
  6307
  6308
  6309
  6310
  6311
  6312
  6313
  6314
  6315
  6316
  6317
  6318
  6319
  6320
  6321
  6322
  6323
  6324
  6325
  6326
  6327
  6328
  6329
  6330
  6331
  6332
  6333
  6334
  6335
  6336
  6337
  6338
  6339
  6340
  6341
  6342
  6343
  6344
  6345
  6346
  6347
  6348
  6349
  6350
  6351
  6352
  6353
  6354
  6355
  6356
  6357
  6358
  6359
  6360
  6361
  6362
  6363
  6364
  6365
  6366
  6367
  6368
  6369
  6370
  6371
  6372
  6373
  6374
  6375
  6376
  6377
  6378
  6379
  6380
  6381
  6382
  6383
  6384
  6385
  6386
  6387
  6388
  6389
  6390
  6391
  6392
  6393
  6394
  6395
  6396
  6397
  6398
  6399
  6400
  6401
  6402
  6403
  6404
  6405
  6406
  6407
  6408
  6409
  6410
  6411
  6412
  6413
  6414
  6415
  6416
  6417
  6418
  6419
  6420
  6421
  6422
  6423
  6424
  6425
  6426
  6427
  6428
  6429
  6430
  6431
  6432
  6433
  6434
  6435
  6436
  6437
  6438
  6439
  6440
  6441
  6442
  6443
  6444
  6445
  6446
  6447
  6448
  6449
  6450
  6451
  6452
  6453
  6454
  6455
  6456
  6457
  6458
  6459
  6460
  6461
  6462
  6463
  6464
  6465
  6466
  6467
  6468
  6469
  6470
  6471
  6472
  6473
  6474
  6475
  6476
  6477
  6478
  6479
  6480
  6481
  6482
  6483
  6484
  6485
  6486
  6487
  6488
  6489
  6490
  6491
  6492
  6493
  6494
  6495
  6496
  6497
  6498
  6499
  6500
  6501
  6502
  6503
  6504
  6505
  6506
  6507
  6508
  6509
  6510
  6511
  6512
  6513
  6514
  6515
  6516
  6517
  6518
  6519
  6520
  6521
  6522
  6523
  6524
  6525
  6526
  6527
  6528
  6529
  6530
  6531
  6532
  6533
  6534
  6535
  6536
  6537
  6538
  6539
  6540
  6541
  6542
  6543
  6544
  6545
  6546
  6547
  6548
  6549
  6550
  6551
  6552
  6553
  6554
  6555
  6556
  6557
  6558
  6559
  6560
  6561
  6562
  6563
  6564
  6565
  6566
  6567
  6568
  6569
  6570
  6571
  6572
  6573
  6574
  6575
  6576
  6577
  6578
  6579
  6580
  6581
  6582
  6583
  6584
  6585
  6586
  6587
  6588
  6589
  6590
  6591
  6592
  6593
  6594
  6595
  6596
  6597
  6598
  6599
  6600
  6601
  6602
  6603
  6604
  6605
  6606
  6607
  6608
  6609
  6610
  6611
  6612
  6613
  6614
  6615
  6616
  6617
  6618
  6619
  6620
  6621
  6622
  6623
  6624
  6625
  6626
  6627
  6628
  6629
  6630
  6631
  6632
  6633
  6634
  6635
  6636
  6637
  6638
  6639
  6640
  6641
  6642
  6643
  6644
  6645
  6646
  6647
  6648
  6649
  6650
  6651
  6652
  6653
  6654
  6655
  6656
  6657
  6658
  6659
  6660
  6661
  6662
  6663
  6664
  6665
  6666
  6667
  6668
  6669
  6670
  6671
  6672
  6673
  6674
  6675
  6676
  6677
  6678
  6679
  6680
  6681
  6682
  6683
  6684
  6685
  6686
  6687
  6688
  6689
  6690
  6691
  6692
  6693
  6694
  6695
  6696
  6697
  6698
  6699
  6700
  6701
  6702
  6703
  6704
  6705
  6706
  6707
  6708
  6709
  6710
  6711
  6712
  6713
  6714
  6715
  6716
  6717
  6718
  6719
  6720
  6721
  6722
  6723
  6724
  6725
  6726
  6727
  6728
  6729
  6730
  6731
  6732
  6733
  6734
  6735
  6736
  6737
  6738
  6739
  6740
  6741
  6742
  6743
  6744
  6745
  6746
  6747
  6748
  6749
  6750
  6751
  6752
  6753
  6754
  6755
  6756
  6757
  6758
  6759
  6760
  6761
  6762
  6763
  6764
  6765
  6766
  6767
  6768
  6769
  6770
  6771
  6772
  6773
  6774
  6775
  6776
  6777
  6778
  6779
  6780
  6781
  6782
  6783
  6784
  6785
  6786
  6787
  6788
  6789
  6790
  6791
  6792
  6793
  6794
  6795
  6796
  6797
  6798
  6799
  6800
  6801
  6802
  6803
  6804
  6805
  6806
  6807
  6808
  6809
  6810
  6811
  6812
  6813
  6814
  6815
  6816
  6817
  6818
  6819
  6820
  6821
  6822
  6823
  6824
  6825
  6826
  6827
  6828
  6829
  6830
  6831
  6832
  6833
  6834
  6835
  6836
  6837
  6838
  6839
  6840
  6841
  6842
  6843
  6844
  6845
  6846
  6847
  6848
  6849
  6850
  6851
  6852
  6853
  6854
  6855
  6856
  6857
  6858
  6859
  6860
  6861
  6862
  6863
  6864
  6865
  6866
  6867
  6868
  6869
  6870
  6871
  6872
  6873
  6874
  6875
  6876
  6877
  6878
  6879
  6880
  6881
  6882
  6883
  6884
  6885
  6886
  6887
  6888
  6889
  6890
  6891
  6892
  6893
  6894
  6895
  6896
  6897
  6898
  6899
  6900
  6901
  6902
  6903
  6904
  6905
  6906
  6907
  6908
  6909
  6910
  6911
  6912
  6913
  6914
  6915
  6916
  6917
  6918
  6919
  6920
  6921
  6922
  6923
  6924
  6925
  6926
  6927
  6928
  6929
  6930
  6931
  6932
  6933
  6934
  6935
  6936
  6937
  6938
  6939
  6940
  6941
  6942
  6943
  6944
  6945
  6946
  6947
  6948
  6949
  6950
  6951
  6952
  6953
  6954
  6955
  6956
  6957
  6958
  6959
  6960
  6961
  6962
  6963
  6964
  6965
  6966
  6967
  6968
  6969
  6970
  6971
  6972
  6973
  6974
  6975
  6976
  6977
  6978
  6979
  6980
  6981
  6982
  6983
  6984
  6985
  6986
  6987
  6988
  6989
  6990
  6991
  6992
  6993
  6994
  6995
  6996
  6997
  6998
  6999
  7000
  7001
  7002
  7003
  7004
  7005
  7006
  7007
  7008
  7009
  7010
  7011
  7012
  7013
  7014
  7015
  7016
  7017
  7018
  7019
  7020
  7021
  7022
  7023
  7024
  7025
  7026
  7027
  7028
  7029
  7030
  7031
  7032
  7033
  7034
  7035
  7036
  7037
  7038
  7039
  7040
  7041
  7042
  7043
  7044
  7045
  7046
  7047
  7048
  7049
  7050
  7051
  7052
  7053
  7054
  7055
  7056
  7057
  7058
  7059
  7060
  7061
  7062
  7063
  7064
  7065
  7066
  7067
  7068
  7069
  7070
  7071
  7072
  7073
  7074
  7075
  7076
  7077
  7078
  7079
  7080
  7081
  7082
  7083
  7084
  7085
  7086
  7087
  7088
  7089
  7090
  7091
  7092
  7093
  7094
  7095
  7096
  7097
  7098
  7099
  7100
  7101
  7102
  7103
  7104
  7105
  7106
  7107
  7108
  7109
  7110
  7111
  7112
  7113
  7114
  7115
  7116
  7117
  7118
  7119
  7120
  7121
  7122
  7123
  7124
  7125
  7126
  7127
  7128
  7129
  7130
  7131
  7132
  7133
  7134
  7135
  7136
  7137
  7138
  7139
  7140
  7141
  7142
  7143
  7144
  7145
  7146
  7147
  7148
  7149
  7150
  7151
  7152
  7153
  7154
  7155
  7156
  7157
  7158
  7159
  7160
  7161
  7162
  7163
  7164
  7165
  7166
  7167
  7168
  7169
  7170
  7171
  7172
  7173
  7174
  7175
  7176
  7177
  7178
  7179
  7180
  7181
  7182
  7183
  7184
  7185
  7186
  7187
  7188
  7189
  7190
  7191
  7192
  7193
  7194
  7195
  7196
  7197
  7198
  7199
  7200
  7201
  7202
  7203
  7204
  7205
  7206
  7207
  7208
  7209
  7210
  7211
  7212
  7213
  7214
  7215
  7216
  7217
  7218
  7219
  7220
  7221
  7222
  7223
  7224
  7225
  7226
  7227
  7228
  7229
  7230
  7231
  7232
  7233
  7234
  7235
  7236
  7237
  7238
  7239
  7240
  7241
  7242
  7243
  7244
  7245
  7246
  7247
  7248
  7249
  7250
  7251
  7252
  7253
  7254
  7255
  7256
  7257
  7258
  7259
  7260
  7261
  7262
  7263
  7264
  7265
  7266
  7267
  7268
  7269
  7270
  7271
  7272
  7273
  7274
  7275
  7276
  7277
  7278
  7279
  7280
  7281
  7282
  7283
  7284
  7285
  7286
  7287
  7288
  7289
  7290
  7291
  7292
  7293
  7294
  7295
  7296
  7297
  7298
  7299
  7300
  7301
  7302
  7303
  7304
  7305
  7306
  7307
  7308
  7309
  7310
  7311
  7312
  7313
  7314
  7315
  7316
  7317
  7318
  7319
  7320
  7321
  7322
  7323
  7324
  7325
  7326
  7327
  7328
  7329
  7330
  7331
  7332
  7333
  7334
  7335
  7336
  7337
  7338
  7339
  7340
  7341
  7342
  7343
  7344
  7345
  7346
  7347
  7348
  7349
  7350
  7351
  7352
  7353
  7354
  7355
  7356
  7357
  7358
  7359
  7360
  7361
  7362
  7363
  7364
  7365
  7366
  7367
  7368
  7369
  7370
  7371
  7372
  7373
  7374
  7375
  7376
  7377
  7378
  7379
  7380
  7381
  7382
  7383
  7384
  7385
  7386
  7387
  7388
  7389
  7390
  7391
  7392
  7393
  7394
  7395
  7396
  7397
  7398
  7399
  7400
  7401
  7402
  7403
  7404
  7405
  7406
  7407
  7408
  7409
  7410
  7411
  7412
  7413
  7414
  7415
  7416
  7417
  7418
  7419
  7420
  7421
  7422
  7423
  7424
  7425
  7426
  7427
  7428
  7429
  7430
  7431
  7432
  7433
  7434
  7435
  7436
  7437
  7438
  7439
  7440
  7441
  7442
  7443
  7444
  7445
  7446
  7447
  7448
  7449
  7450
  7451
  7452
  7453
  7454
  7455
  7456
  7457
  7458
  7459
  7460
  7461
  7462
  7463
  7464
  7465
  7466
  7467
  7468
  7469
  7470
  7471
  7472
  7473
  7474
  7475
  7476
  7477
  7478
  7479
  7480
  7481
  7482
  7483
  7484
  7485
  7486
  7487
  7488
  7489
  7490
  7491
  7492
  7493
  7494
  7495
  7496
  7497
  7498
  7499
  7500
  7501
  7502
  7503
  7504
  7505
  7506
  7507
  7508
  7509
  7510
  7511
  7512
  7513
  7514
  7515
  7516
  7517
  7518
  7519
  7520
  7521
  7522
  7523
  7524
  7525
  7526
  7527
  7528
  7529
  7530
  7531
  7532
  7533
  7534
  7535
  7536
  7537
  7538
  7539
  7540
  7541
  7542
  7543
  7544
  7545
  7546
  7547
  7548
  7549
  7550
  7551
  7552
  7553
  7554
  7555
  7556
  7557
  7558
  7559
  7560
  7561
  7562
  7563
  7564
  7565
  7566
  7567
  7568
  7569
  7570
  7571
  7572
  7573
  7574
  7575
  7576
  7577
  7578
  7579
  7580
  7581
  7582
  7583
  7584
  7585
  7586
  7587
  7588
  7589
  7590
  7591
  7592
  7593
  7594
  7595
  7596
  7597
  7598
  7599
  7600
  7601
  7602
  7603
  7604
  7605
  7606
  7607
  7608
  7609
  7610
  7611
  7612
  7613
  7614
  7615
  7616
  7617
  7618
  7619
  7620
  7621
  7622
  7623
  7624
  7625
  7626
  7627
  7628
  7629
  7630
  7631
  7632
  7633
  7634
  7635
  7636
  7637
  7638
  7639
  7640
  7641
  7642
  7643
  7644
  7645
  7646
  7647
  7648
  7649
  7650
  7651
  7652
  7653
  7654
  7655
  7656
  7657
  7658
  7659
  7660
  7661
  7662
  7663
  7664
  7665
  7666
  7667
  7668
  7669
  7670
  7671
  7672
  7673
  7674
  7675
  7676
  7677
  7678
  7679
  7680
  7681
  7682
  7683
  7684
  7685
  7686
  7687
  7688
  7689
  7690
  7691
  7692
  7693
  7694
  7695
  7696
  7697
  7698
  7699
  7700
  7701
  7702
  7703
  7704
  7705
  7706
  7707
  7708
  7709
  7710
  7711
  7712
  7713
  7714
  7715
  7716
  7717
  7718
  7719
  7720
  7721
  7722
  7723
  7724
  7725
  7726
  7727
  7728
  7729
  7730
  7731
  7732
  7733
  7734
  7735
  7736
  7737
  7738
  7739
  7740
  7741
  7742
  7743
  7744
  7745
  7746
  7747
  7748
  7749
  7750
  7751
  7752
  7753
  7754
  7755
  7756
  7757
  7758
  7759
  7760
  7761
  7762
  7763
  7764
  7765
  7766
  7767
  7768
  7769
  7770
  7771
  7772
  7773
  7774
  7775
  7776
  7777
  7778
  7779
  7780
  7781
  7782
  7783
  7784
  7785
  7786
  7787
  7788
  7789
  7790
  7791
  7792
  7793
  7794
  7795
  7796
  7797
  7798
  7799
  7800
  7801
  7802
  7803
  7804
  7805
  7806
  7807
  7808
  7809
  7810
  7811
  7812
  7813
  7814
  7815
  7816
  7817
  7818
  7819
  7820
  7821
  7822
  7823
  7824
  7825
  7826
  7827
  7828
  7829
  7830
  7831
  7832
  7833
  7834
  7835
  7836
  7837
  7838
  7839
  7840
  7841
  7842
  7843
  7844
  7845
  7846
  7847
  7848
  7849
  7850
  7851
  7852
  7853
  7854
  7855
  7856
  7857
  7858
  7859
  7860
  7861
  7862
  7863
  7864
  7865
  7866
  7867
  7868
  7869
  7870
  7871
  7872
  7873
  7874
  7875
  7876
  7877
  7878
  7879
  7880
  7881
  7882
  7883
  7884
  7885
  7886
  7887
  7888
  7889
  7890
  7891
  7892
  7893
  7894
  7895
  7896
  7897
  7898
  7899
  7900
  7901
  7902
  7903
  7904
  7905
  7906
  7907
  7908
  7909
  7910
  7911
  7912
  7913
  7914
  7915
  7916
  7917
  7918
  7919
  7920
  7921
  7922
  7923
  7924
  7925
  7926
  7927
  7928
  7929
  7930
  7931
  7932
  7933
  7934
  7935
  7936
  7937
  7938
  7939
  7940
  7941
  7942
  7943
  7944
  7945
  7946
  7947
  7948
  7949
  7950
  7951
  7952
  7953
  7954
  7955
  7956
  7957
  7958
  7959
  7960
  7961
  7962
  7963
  7964
  7965
  7966
  7967
  7968
  7969
  7970
  7971
  7972
  7973
  7974
  7975
  7976
  7977
  7978
  7979
  7980
  7981
  7982
  7983
  7984
  7985
  7986
  7987
  7988
  7989
  7990
  7991
  7992
  7993
  7994
  7995
  7996
  7997
  7998
  7999
  8000
  8001
  8002
  8003
  8004
  8005
  8006
  8007
  8008
  8009
  8010
  8011
  8012
  8013
  8014
  8015
  8016
  8017
  8018
  8019
  8020
  8021
  8022
  8023
  8024
  8025
  8026
  8027
  8028
  8029
  8030
  8031
  8032
  8033
  8034
  8035
  8036
  8037
  8038
  8039
  8040
  8041
  8042
  8043
  8044
  8045
  8046
  8047
  8048
  8049
  8050
  8051
  8052
  8053
  8054
  8055
  8056
  8057
  8058
  8059
  8060
  8061
  8062
  8063
  8064
  8065
  8066
  8067
  8068
  8069
  8070
  8071
  8072
  8073
  8074
  8075
  8076
  8077
  8078
  8079
  8080
  8081
  8082
  8083
  8084
  8085
  8086
  8087
  8088
  8089
  8090
  8091
  8092
  8093
  8094
  8095
  8096
  8097
  8098
  8099
  8100
  8101
  8102
  8103
  8104
  8105
  8106
  8107
  8108
  8109
  8110
  8111
  8112
  8113
  8114
  8115
  8116
  8117
  8118
  8119
  8120
  8121
  8122
  8123
  8124
  8125
  8126
  8127
  8128
  8129
  8130
  8131
  8132
  8133
  8134
  8135
  8136
  8137
  8138
  8139
  8140
  8141
  8142
  8143
  8144
  8145
  8146
  8147
  8148
  8149
  8150
  8151
  8152
  8153
  8154
  8155
  8156
  8157
  8158
  8159
  8160
  8161
  8162
  8163
  8164
  8165
  8166
  8167
  8168
  8169
  8170
  8171
  8172
  8173
  8174
  8175
  8176
  8177
  8178
  8179
  8180
  8181
  8182
  8183
  8184
  8185
  8186
  8187
  8188
  8189
  8190
  8191
  8192
  8193
  8194
  8195
  8196
  8197
  8198
  8199
  8200
  8201
  8202
  8203
  8204
  8205
  8206
  8207
  8208
  8209
  8210
  8211
  8212
  8213
  8214
  8215
  8216
  8217
  8218
  8219
  8220
  8221
  8222
  8223
  8224
  8225
  8226
  8227
  8228
  8229
  8230
  8231
  8232
  8233
  8234
  8235
  8236
  8237
  8238
  8239
  8240
  8241
  8242
  8243
  8244
  8245
  8246
  8247
  8248
  8249
  8250
  8251
  8252
  8253
  8254
  8255
  8256
  8257
  8258
  8259
  8260
  8261
  8262
  8263
  8264
  8265
  8266
  8267
  8268
  8269
  8270
  8271
  8272
  8273
  8274
  8275
  8276
  8277
  8278
  8279
  8280
  8281
  8282
  8283
  8284
  8285
  8286
  8287
  8288
  8289
  8290
  8291
  8292
  8293
  8294
  8295
  8296
  8297
  8298
  8299
  8300
  8301
  8302
  8303
  8304
  8305
  8306
  8307
  8308
  8309
  8310
  8311
  8312
  8313
  8314
  8315
  8316
  8317
  8318
  8319
  8320
  8321
  8322
  8323
  8324
  8325
  8326
  8327
  8328
  8329
  8330
  8331
  8332
  8333
  8334
  8335
  8336
  8337
  8338
  8339
  8340
  8341
  8342
  8343
  8344
  8345
  8346
  8347
  8348
  8349
  8350
  8351
  8352
  8353
  8354
  8355
  8356
  8357
  8358
  8359
  8360
  8361
  8362
  8363
  8364
  8365
  8366
  8367
  8368
  8369
  8370
  8371
  8372
  8373
  8374
  8375
  8376
  8377
  8378
  8379
  8380
  8381
  8382
  8383
  8384
  8385
  8386
  8387
  8388
  8389
  8390
  8391
  8392
  8393
  8394
  8395
  8396
  8397
  8398
  8399
  8400
  8401
  8402
  8403
  8404
  8405
  8406
  8407
  8408
  8409
  8410
  8411
  8412
  8413
  8414
  8415
  8416
  8417
  8418
  8419
  8420
  8421
  8422
  8423
  8424
  8425
  8426
  8427
  8428
  8429
  8430
  8431
  8432
  8433
  8434
  8435
  8436
  8437
  8438
  8439
  8440
  8441
  8442
  8443
  8444
  8445
  8446
  8447
  8448
  8449
  8450
  8451
  8452
  8453
  8454
  8455
  8456
  8457
  8458
  8459
  8460
  8461
  8462
  8463
  8464
  8465
  8466
  8467
  8468
  8469
  8470
  8471
  8472
  8473
  8474
  8475
  8476
  8477
  8478
  8479
  8480
  8481
  8482
  8483
  8484
  8485
  8486
  8487
  8488
  8489
  8490
  8491
  8492
  8493
  8494
  8495
  8496
  8497
  8498
  8499
  8500
  8501
  8502
  8503
  8504
  8505
  8506
  8507
  8508
  8509
  8510
  8511
  8512
  8513
  8514
  8515
  8516
  8517
  8518
  8519
  8520
  8521
  8522
  8523
  8524
  8525
  8526
  8527
  8528
  8529
  8530
  8531
  8532
  8533
  8534
  8535
  8536
  8537
  8538
  8539
  8540
  8541
  8542
  8543
  8544
  8545
  8546
  8547
  8548
  8549
  8550
  8551
  8552
  8553
  8554
  8555
  8556
  8557
  8558
  8559
  8560
  8561
  8562
  8563
  8564
  8565
  8566
  8567
  8568
  8569
  8570
  8571
  8572
  8573
  8574
  8575
  8576
  8577
  8578
  8579
  8580
  8581
  8582
  8583
  8584
  8585
  8586
  8587
  8588
  8589
  8590
  8591
  8592
  8593
  8594
  8595
  8596
  8597
  8598
  8599
  8600
  8601
  8602
  8603
  8604
  8605
  8606
  8607
  8608
  8609
  8610
  8611
  8612
  8613
  8614
  8615
  8616
  8617
  8618
  8619
  8620
  8621
  8622
  8623
  8624
  8625
  8626
  8627
  8628
  8629
  8630
  8631
  8632
  8633
  8634
  8635
  8636
  8637
  8638
  8639
  8640
  8641
  8642
  8643
  8644
  8645
  8646
  8647
  8648
  8649
  8650
  8651
  8652
  8653
  8654
  8655
  8656
  8657
  8658
  8659
  8660
  8661
  8662
  8663
  8664
  8665
  8666
  8667
  8668
  8669
  8670
  8671
  8672
  8673
  8674
  8675
  8676
  8677
  8678
  8679
  8680
  8681
  8682
  8683
  8684
  8685
  8686
  8687
  8688
  8689
  8690
  8691
  8692
  8693
  8694
  8695
  8696
  8697
  8698
  8699
  8700
  8701
  8702
  8703
  8704
  8705
  8706
  8707
  8708
  8709
  8710
  8711
  8712
  8713
  8714
  8715
  8716
  8717
  8718
  8719
  8720
  8721
  8722
  8723
  8724
  8725
  8726
  8727
  8728
  8729
  8730
  8731
  8732
  8733
  8734
  8735
  8736
  8737
  8738
  8739
  8740
  8741
  8742
  8743
  8744
  8745
  8746
  8747
  8748
  8749
  8750
  8751
  8752
  8753
  8754
  8755
  8756
  8757
  8758
  8759
  8760
  8761
  8762
  8763
  8764
  8765
  8766
  8767
  8768
  8769
  8770
  8771
  8772
  8773
  8774
  8775
  8776
  8777
  8778
  8779
  8780
  8781
  8782
  8783
  8784
  8785
  8786
  8787
  8788
  8789
  8790
  8791
  8792
  8793
  8794
  8795
  8796
  8797
  8798
  8799
  8800
  8801
  8802
  8803
  8804
  8805
  8806
  8807
  8808
  8809
  8810
  8811
  8812
  8813
  8814
  8815
  8816
  8817
  8818
  8819
  8820
  8821
  8822
  8823
  8824
  8825
  8826
  8827
  8828
  8829
  8830
  8831
  8832
  8833
  8834
  8835
  8836
  8837
  8838
  8839
  8840
  8841
  8842
  8843
  8844
  8845
  8846
  8847
  8848
  8849
  8850
  8851
  8852
  8853
  8854
  8855
  8856
  8857
  8858
  8859
  8860
  8861
  8862
  8863
  8864
  8865
  8866
  8867
  8868
  8869
  8870
  8871
  8872
  8873
  8874
  8875
  8876
  8877
  8878
  8879
  8880
  8881
  8882
  8883
  8884
  8885
  8886
  8887
  8888
  8889
  8890
  8891
  8892
  8893
  8894
  8895
  8896
  8897
  8898
  8899
  8900
  8901
  8902
  8903
  8904
  8905
  8906
  8907
  8908
  8909
  8910
  8911
  8912
  8913
  8914
  8915
  8916
  8917
  8918
  8919
  8920
  8921
  8922
  8923
  8924
  8925
  8926
  8927
  8928
  8929
  8930
  8931
  8932
  8933
  8934
  8935
  8936
  8937
  8938
  8939
  8940
  8941
  8942
  8943
  8944
  8945
  8946
  8947
  8948
  8949
  8950
  8951
  8952
  8953
  8954
  8955
  8956
  8957
  8958
  8959
  8960
  8961
  8962
  8963
  8964
  8965
  8966
  8967
  8968
  8969
  8970
  8971
  8972
  8973
  8974
  8975
  8976
  8977
  8978
  8979
  8980
  8981
  8982
  8983
  8984
  8985
  8986
  8987
  8988
  8989
  8990
  8991
  8992
  8993
  8994
  8995
  8996
  8997
  8998
  8999
  9000
  9001
  9002
  9003
  9004
  9005
  9006
  9007
  9008
  9009
  9010
  9011
  9012
  9013
  9014
  9015
  9016
  9017
  9018
  9019
  9020
  9021
  9022
  9023
  9024
  9025
  9026
  9027
  9028
  9029
  9030
  9031
  9032
  9033
  9034
  9035
  9036
  9037
  9038
  9039
  9040
  9041
  9042
  9043
  9044
  9045
  9046
  9047
  9048
  9049
  9050
  9051
  9052
  9053
  9054
  9055
  9056
  9057
  9058
  9059
  9060
  9061
  9062
  9063
  9064
  9065
  9066
  9067
  9068
  9069
  9070
  9071
  9072
  9073
  9074
  9075
  9076
  9077
  9078
  9079
  9080
  9081
  9082
  9083
  9084
  9085
  9086
  9087
  9088
  9089
  9090
  9091
  9092
  9093
  9094
  9095
  9096
  9097
  9098
  9099
  9100
  9101
  9102
  9103
  9104
  9105
  9106
  9107
  9108
  9109
  9110
  9111
  9112
  9113
  9114
  9115
  9116
  9117
  9118
  9119
  9120
  9121
  9122
  9123
  9124
  9125
  9126
  9127
  9128
  9129
  9130
  9131
  9132
  9133
  9134
  9135
  9136
  9137
  9138
  9139
  9140
  9141
  9142
  9143
  9144
  9145
  9146
  9147
  9148
  9149
  9150
  9151
  9152
  9153
  9154
  9155
  9156
  9157
  9158
  9159
  9160
  9161
  9162
  9163
  9164
  9165
  9166
  9167
  9168
  9169
  9170
  9171
  9172
  9173
  9174
  9175
  9176
  9177
  9178
  9179
  9180
  9181
  9182
  9183
  9184
  9185
  9186
  9187
  9188
  9189
  9190
  9191
  9192
  9193
  9194
  9195
  9196
  9197
  9198
  9199
  9200
  9201
  9202
  9203
  9204
  9205
  9206
  9207
  9208
  9209
  9210
  9211
  9212
  9213
  9214
  9215
  9216
  9217
  9218
  9219
  9220
  9221
  9222
  9223
  9224
  9225
  9226
  9227
  9228
  9229
  9230
  9231
  9232
  9233
  9234
  9235
  9236
  9237
  9238
  9239
  9240
  9241
  9242
  9243
  9244
  9245
  9246
  9247
  9248
  9249
  9250
  9251
  9252
  9253
  9254
  9255
  9256
  9257
  9258
  9259
  9260
  9261
  9262
  9263
  9264
  9265
  9266
  9267
  9268
  9269
  9270
  9271
  9272
  9273
  9274
  9275
  9276
  9277
  9278
  9279
  9280
  9281
  9282
  9283
  9284
  9285
  9286
  9287
  9288
  9289
  9290
  9291
  9292
  9293
  9294
  9295
  9296
  9297
  9298
  9299
  9300
  9301
  9302
  9303
  9304
  9305
  9306
  9307
  9308
  9309
  9310
  9311
  9312
  9313
  9314
  9315
  9316
  9317
  9318
  9319
  9320
  9321
  9322
  9323
  9324
  9325
  9326
  9327
  9328
  9329
  9330
  9331
  9332
  9333
  9334
  9335
  9336
  9337
  9338
  9339
  9340
  9341
  9342
  9343
  9344
  9345
  9346
  9347
  9348
  9349
  9350
  9351
  9352
  9353
  9354
  9355
  9356
  9357
  9358
  9359
  9360
  9361
  9362
  9363
  9364
  9365
  9366
  9367
  9368
  9369
  9370
  9371
  9372
  9373
  9374
  9375
  9376
  9377
  9378
  9379
  9380
  9381
  9382
  9383
  9384
  9385
  9386
  9387
  9388
  9389
  9390
  9391
  9392
  9393
  9394
  9395
  9396
  9397
  9398
  9399
  9400
  9401
  9402
  9403
  9404
  9405
  9406
  9407
  9408
  9409
  9410
  9411
  9412
  9413
  9414
  9415
  9416
  9417
  9418
  9419
  9420
  9421
  9422
  9423
  9424
  9425
  9426
  9427
  9428
  9429
  9430
  9431
  9432
  9433
  9434
  9435
  9436
  9437
  9438
  9439
  9440
  9441
  9442
  9443
  9444
  9445
  9446
  9447
  9448
  9449
  9450
  9451
  9452
  9453
  9454
  9455
  9456
  9457
  9458
  9459
  9460
  9461
  9462
  9463
  9464
  9465
  9466
  9467
  9468
  9469
  9470
  9471
  9472
  9473
  9474
  9475
  9476
  9477
  9478
  9479
  9480
  9481
  9482
  9483
  9484
  9485
  9486
  9487
  9488
  9489
  9490
  9491
  9492
  9493
  9494
  9495
  9496
  9497
  9498
  9499
  9500
  9501
  9502
  9503
  9504
  9505
  9506
  9507
  9508
  9509
  9510
  9511
  9512
  9513
  9514
  9515
  9516
  9517
  9518
  9519
  9520
  9521
  9522
  9523
  9524
  9525
  9526
  9527
  9528
  9529
  9530
  9531
  9532
  9533
  9534
  9535
  9536
  9537
  9538
  9539
  9540
  9541
  9542
  9543
  9544
  9545
  9546
  9547
  9548
  9549
  9550
  9551
  9552
  9553
  9554
  9555
  9556
  9557
  9558
  9559
  9560
  9561
  9562
  9563
  9564
  9565
  9566
  9567
  9568
  9569
  9570
  9571
  9572
  9573
  9574
  9575
  9576
  9577
  9578
  9579
  9580
  9581
  9582
  9583
  9584
  9585
  9586
  9587
  9588
  9589
  9590
  9591
  9592
  9593
  9594
  9595
  9596
  9597
  9598
  9599
  9600
  9601
  9602
  9603
  9604
  9605
  9606
  9607
  9608
  9609
  9610
  9611
  9612
  9613
  9614
  9615
  9616
  9617
  9618
  9619
  9620
  9621
  9622
  9623
  9624
  9625
  9626
  9627
  9628
  9629
  9630
  9631
  9632
  9633
  9634
  9635
  9636
  9637
  9638
  9639
  9640
  9641
  9642
  9643
  9644
  9645
  9646
  9647
  9648
  9649
  9650
  9651
  9652
  9653
  9654
  9655
  9656
  9657
  9658
  9659
  9660
  9661
  9662
  9663
  9664
  9665
  9666
  9667
  9668
  9669
  9670
  9671
  9672
  9673
  9674
  9675
  9676
  9677
  9678
  9679
  9680
  9681
  9682
  9683
  9684
  9685
  9686
  9687
  9688
  9689
  9690
  9691
  9692
  9693
  9694
  9695
  9696
  9697
  9698
  9699
  9700
  9701
  9702
  9703
  9704
  9705
  9706
  9707
  9708
  9709
  9710
  9711
  9712
  9713
  9714
  9715
  9716
  9717
  9718
  9719
  9720
  9721
  9722
  9723
  9724
  9725
  9726
  9727
  9728
  9729
  9730
  9731
  9732
  9733
  9734
  9735
  9736
  9737
  9738
  9739
  9740
  9741
  9742
  9743
  9744
  9745
  9746
  9747
  9748
  9749
  9750
  9751
  9752
  9753
  9754
  9755
  9756
  9757
  9758
  9759
  9760
  9761
  9762
  9763
  9764
  9765
  9766
  9767
  9768
  9769
  9770
  9771
  9772
  9773
  9774
  9775
  9776
  9777
  9778
  9779
  9780
  9781
  9782
  9783
  9784
  9785
  9786
  9787
  9788
  9789
  9790
  9791
  9792
  9793
  9794
  9795
  9796
  9797
  9798
  9799
  9800
  9801
  9802
  9803
  9804
  9805
  9806
  9807
  9808
  9809
  9810
  9811
  9812
  9813
  9814
  9815
  9816
  9817
  9818
  9819
  9820
  9821
  9822
  9823
  9824
  9825
  9826
  9827
  9828
  9829
  9830
  9831
  9832
  9833
  9834
  9835
  9836
  9837
  9838
  9839
  9840
  9841
  9842
  9843
  9844
  9845
  9846
  9847
  9848
  9849
  9850
  9851
  9852
  9853
  9854
  9855
  9856
  9857
  9858
  9859
  9860
  9861
  9862
  9863
  9864
  9865
  9866
  9867
  9868
  9869
  9870
  9871
  9872
  9873
  9874
  9875
  9876
  9877
  9878
  9879
  9880
  9881
  9882
  9883
  9884
  9885
  9886
  9887
  9888
  9889
  9890
  9891
  9892
  9893
  9894
  9895
  9896
  9897
  9898
  9899
  9900
  9901
  9902
  9903
  9904
  9905
  9906
  9907
  9908
  9909
  9910
  9911
  9912
  9913
  9914
  9915
  9916
  9917
  9918
  9919
  9920
  9921
  9922
  9923
  9924
  9925
  9926
  9927
  9928
  9929
  9930
  9931
  9932
  9933
  9934
  9935
  9936
  9937
  9938
  9939
  9940
  9941
  9942
  9943
  9944
  9945
  9946
  9947
  9948
  9949
  9950
  9951
  9952
  9953
  9954
  9955
  9956
  9957
  9958
  9959
  9960
  9961
  9962
  9963
  9964
  9965
  9966
  9967
  9968
  9969
  9970
  9971
  9972
  9973
  9974
  9975
  9976
  9977
  9978
  9979
  9980
  9981
  9982
  9983
  9984
  9985
  9986
  9987
  9988
  9989
  9990
  9991
  9992
  9993
  9994
  9995
  9996
  9997
  9998
  9999
 10000
 10001
 10002
 10003
 10004
 10005
 10006
 10007
 10008
 10009
 10010
 10011
 10012
 10013
 10014
 10015
 10016
 10017
 10018
 10019
 10020
 10021
 10022
 10023
 10024
 10025
 10026
 10027
 10028
 10029
 10030
 10031
 10032
 10033
 10034
 10035
 10036
 10037
 10038
 10039
 10040
 10041
 10042
 10043
 10044
 10045
 10046
 10047
 10048
 10049
 10050
 10051
 10052
 10053
 10054
 10055
 10056
 10057
 10058
 10059
 10060
 10061
 10062
 10063
 10064
 10065
 10066
 10067
 10068
 10069
 10070
 10071
 10072
 10073
 10074
 10075
 10076
 10077
 10078
 10079
 10080
 10081
 10082
 10083
 10084
 10085
 10086
 10087
 10088
 10089
 10090
 10091
 10092
 10093
 10094
 10095
 10096
 10097
 10098
 10099
 10100
 10101
 10102
 10103
 10104
 10105
 10106
 10107
 10108
 10109
 10110
 10111
 10112
 10113
 10114
 10115
 10116
 10117
 10118
 10119
 10120
 10121
 10122
 10123
 10124
 10125
 10126
 10127
 10128
 10129
 10130
 10131
 10132
 10133
 10134
 10135
 10136
 10137
 10138
 10139
 10140
 10141
 10142
 10143
 10144
 10145
 10146
 10147
 10148
 10149
 10150
 10151
 10152
 10153
 10154
 10155
 10156
 10157
 10158
 10159
 10160
 10161
 10162
 10163
 10164
 10165
 10166
 10167
 10168
 10169
 10170
 10171
 10172
 10173
 10174
 10175
 10176
 10177
 10178
 10179
 10180
 10181
 10182
 10183
 10184
 10185
 10186
 10187
 10188
 10189
 10190
 10191
 10192
 10193
 10194
 10195
 10196
 10197
 10198
 10199
 10200
 10201
 10202
 10203
 10204
 10205
 10206
 10207
 10208
 10209
 10210
 10211
 10212
 10213
 10214
 10215
 10216
 10217
 10218
 10219
 10220
 10221
 10222
 10223
 10224
 10225
 10226
 10227
 10228
 10229
 10230
 10231
 10232
 10233
 10234
 10235
 10236
 10237
 10238
 10239
 10240
 10241
 10242
 10243
 10244
 10245
 10246
 10247
 10248
 10249
 10250
 10251
 10252
 10253
 10254
 10255
 10256
 10257
 10258
 10259
 10260
 10261
 10262
 10263
 10264
 10265
 10266
 10267
 10268
 10269
 10270
 10271
 10272
 10273
 10274
 10275
 10276
 10277
 10278
 10279
 10280
 10281
 10282
 10283
 10284
 10285
 10286
 10287
 10288
 10289
 10290
 10291
 10292
 10293
 10294
 10295
 10296
 10297
 10298
 10299
 10300
 10301
 10302
 10303
 10304
 10305
 10306
 10307
 10308
 10309
 10310
 10311
 10312
 10313
 10314
 10315
 10316
 10317
 10318
 10319
 10320
 10321
 10322
 10323
 10324
 10325
 10326
 10327
 10328
 10329
 10330
 10331
 10332
 10333
 10334
 10335
 10336
 10337
 10338
 10339
 10340
 10341
 10342
 10343
 10344
 10345
 10346
 10347
 10348
 10349
 10350
 10351
 10352
 10353
 10354
 10355
 10356
 10357
 10358
 10359
 10360
 10361
 10362
 10363
 10364
 10365
 10366
 10367
 10368
 10369
 10370
 10371
 10372
 10373
 10374
 10375
 10376
 10377
 10378
 10379
 10380
 10381
 10382
 10383
 10384
 10385
 10386
 10387
 10388
 10389
 10390
 10391
 10392
 10393
 10394
 10395
 10396
 10397
 10398
 10399
 10400
 10401
 10402
 10403
 10404
 10405
 10406
 10407
 10408
 10409
 10410
 10411
 10412
 10413
 10414
 10415
 10416
 10417
 10418
 10419
 10420
 10421
 10422
 10423
 10424
 10425
 10426
 10427
 10428
 10429
 10430
 10431
 10432
 10433
 10434
 10435
 10436
 10437
 10438
 10439
 10440
 10441
 10442
 10443
 10444
 10445
 10446
 10447
 10448
 10449
 10450
 10451
 10452
 10453
 10454
 10455
 10456
 10457
 10458
 10459
 10460
 10461
 10462
 10463
 10464
 10465
 10466
 10467
 10468
 10469
 10470
 10471
 10472
 10473
 10474
 10475
 10476
 10477
 10478
 10479
 10480
 10481
 10482
 10483
 10484
 10485
 10486
 10487
 10488
 10489
 10490
 10491
 10492
 10493
 10494
 10495
 10496
 10497
 10498
 10499
 10500
 10501
 10502
 10503
 10504
 10505
 10506
 10507
 10508
 10509
 10510
 10511
 10512
 10513
 10514
 10515
 10516
 10517
 10518
 10519
 10520
 10521
 10522
 10523
 10524
 10525
 10526
 10527
 10528
 10529
 10530
 10531
 10532
 10533
 10534
 10535
 10536
 10537
 10538
 10539
 10540
 10541
 10542
 10543
 10544
 10545
 10546
 10547
 10548
 10549
 10550
 10551
 10552
 10553
 10554
 10555
 10556
 10557
 10558
 10559
 10560
 10561
 10562
 10563
 10564
 10565
 10566
 10567
 10568
 10569
 10570
 10571
 10572
 10573
 10574
 10575
 10576
 10577
 10578
 10579
 10580
 10581
 10582
 10583
 10584
 10585
 10586
 10587
 10588
 10589
 10590
 10591
 10592
 10593
 10594
 10595
 10596
 10597
 10598
 10599
 10600
 10601
 10602
 10603
 10604
 10605
 10606
 10607
 10608
 10609
 10610
 10611
 10612
 10613
 10614
 10615
 10616
 10617
 10618
 10619
 10620
 10621
 10622
 10623
 10624
 10625
 10626
 10627
 10628
 10629
 10630
 10631
 10632
 10633
 10634
 10635
 10636
 10637
 10638
 10639
 10640
 10641
 10642
 10643
 10644
 10645
 10646
 10647
 10648
 10649
 10650
 10651
 10652
 10653
 10654
 10655
 10656
 10657
 10658
 10659
 10660
 10661
 10662
 10663
 10664
 10665
 10666
 10667
 10668
 10669
 10670
 10671
 10672
 10673
 10674
 10675
 10676
 10677
 10678
 10679
 10680
 10681
 10682
 10683
 10684
 10685
 10686
 10687
 10688
 10689
 10690
 10691
 10692
 10693
 10694
 10695
 10696
 10697
 10698
 10699
 10700
 10701
 10702
 10703
 10704
 10705
 10706
 10707
 10708
 10709
 10710
 10711
 10712
 10713
 10714
 10715
 10716
 10717
 10718
 10719
 10720
 10721
 10722
 10723
 10724
 10725
 10726
 10727
 10728
 10729
 10730
 10731
 10732
 10733
 10734
 10735
 10736
 10737
 10738
 10739
 10740
 10741
 10742
 10743
 10744
 10745
 10746
 10747
 10748
 10749
 10750
 10751
 10752
 10753
 10754
 10755
 10756
 10757
 10758
 10759
 10760
 10761
 10762
 10763
 10764
 10765
 10766
 10767
 10768
 10769
 10770
 10771
 10772
 10773
 10774
 10775
 10776
 10777
 10778
 10779
 10780
 10781
 10782
 10783
 10784
 10785
 10786
 10787
 10788
 10789
 10790
 10791
 10792
 10793
 10794
 10795
 10796
 10797
 10798
 10799
 10800
 10801
 10802
 10803
 10804
 10805
 10806
 10807
 10808
 10809
 10810
 10811
 10812
 10813
 10814
 10815
 10816
 10817
 10818
 10819
 10820
 10821
 10822
 10823
 10824
 10825
 10826
 10827
 10828
 10829
 10830
 10831
 10832
 10833
 10834
 10835
 10836
 10837
 10838
 10839
 10840
 10841
 10842
 10843
 10844
 10845
 10846
 10847
 10848
 10849
 10850
 10851
 10852
 10853
 10854
 10855
 10856
 10857
 10858
 10859
 10860
 10861
 10862
 10863
 10864
 10865
 10866
 10867
 10868
 10869
 10870
 10871
 10872
 10873
 10874
 10875
 10876
 10877
 10878
 10879
 10880
 10881
 10882
 10883
 10884
 10885
 10886
 10887
 10888
 10889
 10890
 10891
 10892
 10893
 10894
 10895
 10896
 10897
 10898
 10899
 10900
 10901
 10902
 10903
 10904
 10905
 10906
 10907
 10908
 10909
 10910
 10911
 10912
 10913
 10914
 10915
 10916
 10917
 10918
 10919
 10920
 10921
 10922
 10923
 10924
 10925
 10926
 10927
 10928
 10929
 10930
 10931
 10932
 10933
 10934
 10935
 10936
 10937
 10938
 10939
 10940
 10941
 10942
 10943
 10944
 10945
 10946
 10947
 10948
 10949
 10950
 10951
 10952
 10953
 10954
 10955
 10956
 10957
 10958
 10959
 10960
 10961
 10962
 10963
 10964
 10965
 10966
 10967
 10968
 10969
 10970
 10971
 10972
 10973
 10974
 10975
 10976
 10977
 10978
 10979
 10980
 10981
 10982
 10983
 10984
 10985
 10986
 10987
 10988
 10989
 10990
 10991
 10992
 10993
 10994
 10995
 10996
 10997
 10998
 10999
 11000
 11001
 11002
 11003
 11004
 11005
 11006
 11007
 11008
 11009
 11010
 11011
 11012
 11013
 11014
 11015
 11016
 11017
 11018
 11019
 11020
 11021
 11022
 11023
 11024
 11025
 11026
 11027
 11028
 11029
 11030
 11031
 11032
 11033
 11034
 11035
 11036
 11037
 11038
 11039
 11040
 11041
 11042
 11043
 11044
 11045
 11046
 11047
 11048
 11049
 11050
 11051
 11052
 11053
 11054
 11055
 11056
 11057
 11058
 11059
 11060
 11061
 11062
 11063
 11064
 11065
 11066
 11067
 11068
 11069
 11070
 11071
 11072
 11073
 11074
 11075
 11076
 11077
 11078
 11079
 11080
 11081
 11082
 11083
 11084
 11085
 11086
 11087
 11088
 11089
 11090
 11091
 11092
 11093
 11094
 11095
 11096
 11097
 11098
 11099
 11100
 11101
 11102
 11103
 11104
 11105
 11106
 11107
 11108
 11109
 11110
 11111
 11112
 11113
 11114
 11115
 11116
 11117
 11118
 11119
 11120
 11121
 11122
 11123
 11124
 11125
 11126
 11127
 11128
 11129
 11130
 11131
 11132
 11133
 11134
 11135
 11136
 11137
 11138
 11139
 11140
 11141
 11142
 11143
 11144
 11145
 11146
 11147
 11148
 11149
 11150
 11151
 11152
 11153
 11154
 11155
 11156
 11157
 11158
 11159
 11160
 11161
 11162
 11163
 11164
 11165
 11166
 11167
 11168
 11169
 11170
 11171
 11172
 11173
 11174
 11175
 11176
 11177
 11178
 11179
 11180
 11181
 11182
 11183
 11184
 11185
 11186
 11187
 11188
 11189
 11190
 11191
 11192
 11193
 11194
 11195
 11196
 11197
 11198
 11199
 11200
 11201
 11202
 11203
 11204
 11205
 11206
 11207
 11208
 11209
 11210
 11211
 11212
 11213
 11214
 11215
 11216
 11217
 11218
 11219
 11220
 11221
 11222
 11223
 11224
 11225
 11226
 11227
 11228
 11229
 11230
 11231
 11232
 11233
 11234
 11235
 11236
 11237
 11238
 11239
 11240
 11241
 11242
 11243
 11244
 11245
 11246
 11247
 11248
 11249
 11250
 11251
 11252
 11253
 11254
 11255
 11256
 11257
 11258
 11259
 11260
 11261
 11262
 11263
 11264
 11265
 11266
 11267
 11268
 11269
 11270
 11271
 11272
 11273
 11274
 11275
 11276
 11277
 11278
 11279
 11280
 11281
 11282
 11283
 11284
 11285
 11286
 11287
 11288
 11289
 11290
 11291
 11292
 11293
 11294
 11295
 11296
 11297
 11298
 11299
 11300
 11301
 11302
 11303
 11304
 11305
 11306
 11307
 11308
 11309
 11310
 11311
 11312
 11313
 11314
 11315
 11316
 11317
 11318
 11319
 11320
 11321
 11322
 11323
 11324
 11325
 11326
 11327
 11328
 11329
 11330
 11331
 11332
 11333
 11334
 11335
 11336
 11337
 11338
 11339
 11340
 11341
 11342
 11343
 11344
 11345
 11346
 11347
 11348
 11349
 11350
 11351
 11352
 11353
 11354
 11355
 11356
 11357
 11358
 11359
 11360
 11361
 11362
 11363
 11364
 11365
 11366
 11367
 11368
 11369
 11370
 11371
 11372
 11373
 11374
 11375
 11376
 11377
 11378
 11379
 11380
 11381
 11382
 11383
 11384
 11385
 11386
 11387
 11388
 11389
 11390
 11391
 11392
 11393
 11394
 11395
 11396
 11397
 11398
 11399
 11400
 11401
 11402
 11403
 11404
 11405
 11406
 11407
 11408
 11409
 11410
 11411
 11412
 11413
 11414
 11415
 11416
 11417
 11418
 11419
 11420
 11421
 11422
 11423
 11424
 11425
 11426
 11427
 11428
 11429
 11430
 11431
 11432
 11433
 11434
 11435
 11436
 11437
 11438
 11439
 11440
 11441
 11442
 11443
 11444
 11445
 11446
 11447
 11448
 11449
 11450
 11451
 11452
 11453
 11454
 11455
 11456
 11457
 11458
 11459
 11460
 11461
 11462
 11463
 11464
 11465
 11466
 11467
 11468
 11469
 11470
 11471
 11472
 11473
 11474
 11475
 11476
 11477
 11478
 11479
 11480
 11481
 11482
 11483
 11484
 11485
 11486
 11487
 11488
 11489
 11490
 11491
 11492
 11493
 11494
 11495
 11496
 11497
 11498
 11499
 11500
 11501
 11502
 11503
 11504
 11505
 11506
 11507
 11508
 11509
 11510
 11511
 11512
 11513
 11514
 11515
 11516
 11517
 11518
 11519
 11520
 11521
 11522
 11523
 11524
 11525
 11526
 11527
 11528
 11529
 11530
 11531
 11532
 11533
 11534
 11535
 11536
 11537
 11538
 11539
 11540
 11541
 11542
 11543
 11544
 11545
 11546
 11547
 11548
 11549
 11550
 11551
 11552
 11553
 11554
 11555
 11556
 11557
 11558
 11559
 11560
 11561
 11562
 11563
 11564
 11565
 11566
 11567
 11568
 11569
 11570
 11571
 11572
 11573
 11574
 11575
 11576
 11577
 11578
 11579
 11580
 11581
 11582
 11583
 11584
 11585
 11586
 11587
 11588
 11589
 11590
 11591
 11592
 11593
 11594
 11595
 11596
 11597
 11598
 11599
 11600
 11601
 11602
 11603
 11604
 11605
 11606
 11607
 11608
 11609
 11610
 11611
 11612
 11613
 11614
 11615
 11616
 11617
 11618
 11619
 11620
 11621
 11622
 11623
 11624
 11625
 11626
 11627
 11628
 11629
 11630
 11631
 11632
 11633
 11634
 11635
 11636
 11637
 11638
 11639
 11640
 11641
 11642
 11643
 11644
 11645
 11646
 11647
 11648
 11649
 11650
 11651
 11652
 11653
 11654
 11655
 11656
 11657
 11658
 11659
 11660
 11661
 11662
 11663
 11664
 11665
 11666
 11667
 11668
 11669
 11670
 11671
 11672
 11673
 11674
 11675
 11676
 11677
 11678
 11679
 11680
 11681
 11682
 11683
 11684
 11685
 11686
 11687
 11688
 11689
 11690
 11691
 11692
 11693
 11694
 11695
 11696
 11697
 11698
 11699
 11700
 11701
 11702
 11703
 11704
 11705
 11706
 11707
 11708
 11709
 11710
 11711
 11712
 11713
 11714
 11715
 11716
 11717
 11718
 11719
 11720
 11721
 11722
 11723
 11724
 11725
 11726
 11727
 11728
 11729
 11730
 11731
 11732
 11733
 11734
 11735
 11736
 11737
 11738
 11739
 11740
 11741
 11742
 11743
 11744
 11745
 11746
 11747
 11748
 11749
 11750
 11751
 11752
 11753
 11754
 11755
 11756
 11757
 11758
 11759
 11760
 11761
 11762
 11763
 11764
 11765
 11766
 11767
 11768
 11769
 11770
 11771
 11772
 11773
 11774
 11775
 11776
 11777
 11778
 11779
 11780
 11781
 11782
 11783
 11784
 11785
 11786
 11787
 11788
 11789
 11790
 11791
 11792
 11793
 11794
 11795
 11796
 11797
 11798
 11799
 11800
 11801
 11802
 11803
 11804
 11805
 11806
 11807
 11808
 11809
 11810
 11811
 11812
 11813
 11814
 11815
 11816
 11817
 11818
 11819
 11820
 11821
 11822
 11823
 11824
 11825
 11826
 11827
 11828
 11829
 11830
 11831
 11832
 11833
 11834
 11835
 11836
 11837
 11838
 11839
 11840
 11841
 11842
 11843
 11844
 11845
 11846
 11847
 11848
 11849
 11850
 11851
 11852
 11853
 11854
 11855
 11856
 11857
 11858
 11859
 11860
 11861
 11862
 11863
 11864
 11865
 11866
 11867
 11868
 11869
 11870
 11871
 11872
 11873
 11874
 11875
 11876
 11877
 11878
 11879
 11880
 11881
 11882
 11883
 11884
 11885
 11886
 11887
 11888
 11889
 11890
 11891
 11892
 11893
 11894
 11895
 11896
 11897
 11898
 11899
 11900
 11901
 11902
 11903
 11904
 11905
 11906
 11907
 11908
 11909
 11910
 11911
 11912
 11913
 11914
 11915
 11916
 11917
 11918
 11919
 11920
 11921
 11922
 11923
 11924
 11925
 11926
 11927
 11928
 11929
 11930
 11931
 11932
 11933
 11934
 11935
 11936
 11937
 11938
 11939
 11940
 11941
 11942
 11943
 11944
 11945
 11946
 11947
 11948
 11949
 11950
 11951
 11952
 11953
 11954
 11955
 11956
 11957
 11958
 11959
 11960
 11961
 11962
 11963
 11964
 11965
 11966
 11967
 11968
 11969
 11970
 11971
 11972
 11973
 11974
 11975
 11976
 11977
 11978
 11979
 11980
 11981
 11982
 11983
 11984
 11985
 11986
 11987
 11988
 11989
/*
 * tkText.c --
 *
 *	This module provides a big chunk of the implementation of multi-line
 *	editable text widgets for Tk. Among other things, it provides the Tcl
 *	command interfaces to text widgets. The B-tree representation of text
 *	and its actual display are implemented elsewhere.
 *
 * Copyright (c) 1992-1994 The Regents of the University of California.
 * Copyright (c) 1994-1996 Sun Microsystems, Inc.
 * Copyright (c) 1999 by Scriptics Corporation.
 * Copyright (c) 2015-2018 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkInt.h"
#include "tkText.h"
#include "tkTextUndo.h"
#include "tkTextTagSet.h"
#include "tkBitField.h"
#if TCL_MAJOR_VERSION > 8 || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION >= 7)
#include "tkFont.h"
#endif
#include "tkAlloc.h"
#include <stdlib.h>
#include <assert.h>
#include "default.h"

/* needed for strncasecmp */
#if defined(_WIN32) && !defined(__GNUC__)
# define strncasecmp _strnicmp
#else
# include <strings.h>
#endif

#ifndef TK_C99_INLINE_SUPPORT
# define _TK_NEED_IMPLEMENTATION
# include "tkTextPriv.h"
#endif

#if defined(_MSC_VER ) && _MSC_VER < 1500
/* suppress wrong warnings to support ancient compilers */
# pragma warning (disable : 4305)
#endif

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

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

#if 0
# define FORCE_DISPLAY(winPtr) TkpDisplayWindow(winPtr)
#else
# define FORCE_DISPLAY(winPtr)
#endif

/*
 * For compatibility with Tk 4.0 through 8.4.x, we allow tabs to be
 * mis-specified with non-increasing values. These are converted into tabs
 * which are the equivalent of at least a character width apart.
 */

#if TK_MAJOR_VERSION < 9
# define _TK_ALLOW_DECREASING_TABS
#endif

/*
 * Used to avoid having to allocate and deallocate arrays on the fly for
 * commonly used functions. Must be > 0.
 */

#define PIXEL_CLIENTS 8

/*
 * The 'TkTextState' enum in tkText.h is used to define a type for the -state
 * option of the Text widget. These values are used as indices into the string
 * table below.
 */

static const char *const stateStrings[] = {
    "disabled", "normal", "readonly", NULL
};

/*
 * The 'TkTextTagging' enum in tkText.h is used to define a type for the -tagging
 * option of the Text widget. These values are used as indices into the string table below.
 */

static const char *const taggingStrings[] = {
    "within", "gravity", "none", NULL
};

/*
 * The 'TkTextJustify' enum in tkText.h is used to define a type for the -justify option of
 * the Text widget. These values are used as indices into the string table below.
 */

static const char *const justifyStrings[] = {
    "left", "right", "full", "center", NULL
};

/*
 * The 'TkWrapMode' enum in tkText.h is used to define a type for the -wrap
 * option of the Text widget. These values are used as indices into the string
 * table below.
 */

static const char *const wrapStrings[] = {
    "char", "none", "word", "codepoint", NULL
};

/*
 * The 'TkSpacing' enum in tkText.h is used to define a type for the -spacing
 * option of the Text widget. These values are used as indices into the string
 * table below.
 */

static const char *const spaceModeStrings[] = {
    "none", "exact", "trim", NULL
};

/*
 * The 'TkTextTabStyle' enum in tkText.h is used to define a type for the
 * -tabstyle option of the Text widget. These values are used as indices into
 * the string table below.
 */

static const char *const tabStyleStrings[] = {
    "tabular", "wordprocessor", NULL
};

/*
 * The 'TkTextInsertUnfocussed' enum in tkText.h is used to define a type for
 * the -insertunfocussed option of the Text widget. These values are used as
 * indice into the string table below.
 */

static const char *const insertUnfocussedStrings[] = {
    "hollow", "none", "solid", NULL
};

/*
 * The 'TkTextHyphenRule' enum in tkText.h is used to define a type for the
 * -hyphenrules option of the Text widget. These values are used for applying
 * hyphen rules to soft hyphens.
 *
 * NOTE: Don't forget to update function ParseHyphens() if this array will be
 * modified.
 */

static const char *const hyphenRuleStrings[] = {
    "ck", "doubledigraph", "doublevowel", "gemination", "repeathyphen", "trema",
    "tripleconsonant" /* don't append a trailing NULL */
};

#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE

/*
 * The following functions and custom option type are used to define the
 * "line" option type, and thereby handle the text widget '-startline',
 * '-endline' configuration options which are of that type.
 *
 * We do not need a 'freeProc' because all changes to these two options are
 * handled through the TK_TEXT_LINE_RANGE flag in the optionSpecs list, and
 * the internal storage is just a pointer, which therefore doesn't need
 * freeing.
 */

static int		SetLineStartEnd(ClientData clientData, Tcl_Interp *interp, Tk_Window tkwin,
			    Tcl_Obj **value, char *recordPtr, TkSizeT internalOffset, char *oldInternalPtr,
			    int flags);
static Tcl_Obj *	GetLineStartEnd(ClientData clientData, Tk_Window tkwin, char *recordPtr,
			    TkSizeT internalOffset);
static void		RestoreLineStartEnd(ClientData clientData, Tk_Window tkwin, char *internalPtr,
			    char *oldInternalPtr);

static const Tk_ObjCustomOption lineOption = {
    "line",			/* name */
    SetLineStartEnd,		/* setProc */
    GetLineStartEnd,		/* getProc */
    RestoreLineStartEnd,	/* restoreProc */
    NULL,			/* freeProc */
    0
};

#endif /* SUPPORT_DEPRECATED_STARTLINE_ENDLINE */

/*
 * The following functions and custom option type are used to define the
 * "index" option type, and thereby handle the text widget '-startindex',
 * '-endindex' configuration options which are of that type.
 */

static int		SetTextStartEnd(ClientData clientData, Tcl_Interp *interp, Tk_Window tkwin,
			    Tcl_Obj **value, char *recordPtr, TkSizeT internalOffset, char *oldInternalPtr,
			    int flags);
static Tcl_Obj *	GetTextStartEnd(ClientData clientData, Tk_Window tkwin, char *recordPtr,
			    TkSizeT internalOffset);
static void		RestoreTextStartEnd(ClientData clientData, Tk_Window tkwin, char *internalPtr,
			    char *oldInternalPtr);
static void		FreeTextStartEnd(ClientData clientData, Tk_Window tkwin, char *internalPtr);

static const Tk_ObjCustomOption startEndMarkOption = {
    "index",			/* name */
    SetTextStartEnd,		/* setProc */
    GetTextStartEnd,		/* getProc */
    RestoreTextStartEnd,	/* restoreProc */
    FreeTextStartEnd,		/* freeProc */
    0
};

/*
 * Information used to parse text configuration options:
 */

static const Tk_OptionSpec optionSpecs[] = {
    {TK_OPTION_BOOLEAN, "-autoseparators", "autoSeparators",
	"AutoSeparators", DEF_TEXT_AUTO_SEPARATORS, TCL_INDEX_NONE, offsetof(TkText, autoSeparators),
	TK_OPTION_DONT_SET_DEFAULT, 0, 0},
    {TK_OPTION_BORDER, "-background", "background", "Background",
	DEF_TEXT_BG_COLOR, TCL_INDEX_NONE, offsetof(TkText, border), 0, DEF_TEXT_BG_MONO, TK_TEXT_LINE_REDRAW},
    {TK_OPTION_SYNONYM, "-bd", NULL, NULL,
	NULL, 0, TCL_INDEX_NONE, 0, "-borderwidth", TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_SYNONYM, "-bg", NULL, NULL,
	NULL, 0, TCL_INDEX_NONE, 0, "-background", TK_TEXT_LINE_REDRAW},
    {TK_OPTION_BOOLEAN, "-blockcursor", "blockCursor",
	"BlockCursor", DEF_TEXT_BLOCK_CURSOR, TCL_INDEX_NONE, offsetof(TkText, blockCursorType), 0, 0, 0},
    {TK_OPTION_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
	DEF_TEXT_BORDER_WIDTH, TCL_INDEX_NONE, offsetof(TkText, borderWidth), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_CURSOR, "-cursor", "cursor", "Cursor",
	DEF_TEXT_CURSOR, TCL_INDEX_NONE, offsetof(TkText, cursor), TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_CUSTOM, "-endindex", NULL, NULL,
	 NULL, TCL_INDEX_NONE, offsetof(TkText, newEndIndex), TK_OPTION_NULL_OK, &startEndMarkOption, TK_TEXT_INDEX_RANGE},
#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE
    {TK_OPTION_CUSTOM, "-endline", NULL, NULL,
	 NULL, TCL_INDEX_NONE, offsetof(TkText, endLine), TK_OPTION_NULL_OK, &lineOption, TK_TEXT_LINE_RANGE},
#endif
    {TK_OPTION_STRING, "-eolchar", "eolChar", "EolChar",
	NULL, offsetof(TkText, eolCharPtr), TCL_INDEX_NONE, TK_OPTION_NULL_OK, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_COLOR, "-eolcolor", "eolColor", "EolColor",
	NULL, TCL_INDEX_NONE, offsetof(TkText, eolColor), TK_OPTION_NULL_OK, 0, TK_TEXT_LINE_REDRAW},
    {TK_OPTION_STRING, "-eotchar", "eotChar", "EotChar",
	NULL, offsetof(TkText, eotCharPtr), TCL_INDEX_NONE, TK_OPTION_NULL_OK, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_COLOR, "-eotcolor", "eotColor", "EotColor",
	NULL, TCL_INDEX_NONE, offsetof(TkText, eotColor), TK_OPTION_NULL_OK, 0, TK_TEXT_LINE_REDRAW},
    {TK_OPTION_BOOLEAN, "-exportselection", "exportSelection",
	"ExportSelection", DEF_TEXT_EXPORT_SELECTION, TCL_INDEX_NONE, offsetof(TkText, exportSelection), 0, 0, 0},
    {TK_OPTION_SYNONYM, "-fg", "foreground", NULL,
	NULL, 0, TCL_INDEX_NONE, 0, "-foreground", TK_TEXT_LINE_REDRAW},
    {TK_OPTION_FONT, "-font", "font", "Font",
	DEF_TEXT_FONT, TCL_INDEX_NONE, offsetof(TkText, tkfont), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_COLOR, "-foreground", "foreground", "Foreground",
	DEF_TEXT_FG, TCL_INDEX_NONE, offsetof(TkText, fgColor), 0, 0, TK_TEXT_LINE_REDRAW},
    {TK_OPTION_PIXELS, "-height", "height", "Height",
	DEF_TEXT_HEIGHT, TCL_INDEX_NONE, offsetof(TkText, height), 0, 0, 0},
    {TK_OPTION_COLOR, "-highlightbackground", "highlightBackground", "HighlightBackground",
	DEF_TEXT_HIGHLIGHT_BG, TCL_INDEX_NONE, offsetof(TkText, highlightBgColorPtr), 0, 0, 0},
    {TK_OPTION_COLOR, "-highlightcolor", "highlightColor", "HighlightColor",
	DEF_TEXT_HIGHLIGHT, TCL_INDEX_NONE, offsetof(TkText, highlightColorPtr), 0, 0, 0},
    {TK_OPTION_PIXELS, "-highlightthickness", "highlightThickness", "HighlightThickness",
	DEF_TEXT_HIGHLIGHT_WIDTH, TCL_INDEX_NONE, offsetof(TkText, highlightWidth), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_STRING, "-hyphenrules", NULL, NULL,
	NULL, offsetof(TkText, hyphenRulesPtr), TCL_INDEX_NONE, TK_OPTION_NULL_OK, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_COLOR, "-hyphencolor", "hyphenColor", "HyphenColor",
	DEF_TEXT_FG, TCL_INDEX_NONE, offsetof(TkText, hyphenColor), TK_OPTION_NULL_OK, 0, TK_TEXT_LINE_REDRAW},
    {TK_OPTION_BOOLEAN, "-hyphens", "hyphens", "Hyphens",
	"0", TCL_INDEX_NONE, offsetof(TkText, useHyphenSupport), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_BORDER, "-inactiveselectbackground", "inactiveSelectBackground", "Foreground",
	DEF_TEXT_INACTIVE_SELECT_BG_COLOR, TCL_INDEX_NONE, offsetof(TkText, selAttrs.inactiveBorder),
	TK_OPTION_NULL_OK, DEF_TEXT_SELECT_MONO, 0},
    {TK_OPTION_COLOR, "-inactiveselectforeground", "inactiveSelectForeground", "Background",
    	DEF_TEXT_INACTIVE_SELECT_FG_COLOR, TCL_INDEX_NONE, offsetof(TkText, selAttrs.inactiveFgColor),
	TK_OPTION_NULL_OK, DEF_TEXT_SELECT_FG_MONO, 0},
    {TK_OPTION_BORDER, "-insertbackground", "insertBackground", "Foreground",
	DEF_TEXT_INSERT_BG, TCL_INDEX_NONE, offsetof(TkText, insertBorder), 0, 0, 0},
    {TK_OPTION_PIXELS, "-insertborderwidth", "insertBorderWidth",
	"BorderWidth", DEF_TEXT_INSERT_BD_COLOR, TCL_INDEX_NONE, offsetof(TkText, insertBorderWidth), 0,
	(ClientData) DEF_TEXT_INSERT_BD_MONO, 0},
    {TK_OPTION_COLOR, "-insertforeground", "insertForeground", "InsertForeground",
	DEF_TEXT_BG_COLOR, TCL_INDEX_NONE, offsetof(TkText, insertFgColor), 0, 0, 0},
    {TK_OPTION_INT, "-insertofftime", "insertOffTime", "OffTime",
	DEF_TEXT_INSERT_OFF_TIME, TCL_INDEX_NONE, offsetof(TkText, insertOffTime), 0, 0, 0},
    {TK_OPTION_INT, "-insertontime", "insertOnTime", "OnTime",
	DEF_TEXT_INSERT_ON_TIME, TCL_INDEX_NONE, offsetof(TkText, insertOnTime), 0, 0, 0},
    {TK_OPTION_STRING_TABLE,
	"-insertunfocussed", "insertUnfocussed", "InsertUnfocussed",
	DEF_TEXT_INSERT_UNFOCUSSED, TCL_INDEX_NONE, offsetof(TkText, insertUnfocussed),
	0, insertUnfocussedStrings, 0},
    {TK_OPTION_PIXELS, "-insertwidth", "insertWidth", "InsertWidth",
	DEF_TEXT_INSERT_WIDTH, TCL_INDEX_NONE, offsetof(TkText, insertWidth), 0, 0, 0},
    {TK_OPTION_STRING_TABLE, "-justify", "justify", "Justify",
	"left", TCL_INDEX_NONE, offsetof(TkText, justify), 0, justifyStrings, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_STRING, "-lang", "lang", "Lang",
	 NULL, offsetof(TkText, langPtr), TCL_INDEX_NONE, TK_OPTION_NULL_OK, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_INT, "-maxundo", "maxUndo", "MaxUndo",
	DEF_TEXT_MAX_UNDO, TCL_INDEX_NONE, offsetof(TkText, maxUndoDepth), TK_OPTION_DONT_SET_DEFAULT, 0, 0},
    {TK_OPTION_INT, "-maxundosize", "maxUndoSize", "MaxUndoSize",
	DEF_TEXT_MAX_UNDO, TCL_INDEX_NONE, offsetof(TkText, maxUndoSize), TK_OPTION_DONT_SET_DEFAULT, 0, 0},
    {TK_OPTION_INT, "-maxredo", "maxRedo", "MaxRedo",
	"TCL_INDEX_NONE", TCL_INDEX_NONE, offsetof(TkText, maxRedoDepth), TK_OPTION_DONT_SET_DEFAULT, 0, 0},
    {TK_OPTION_PIXELS, "-padx", "padX", "Pad",
	DEF_TEXT_PADX, TCL_INDEX_NONE, offsetof(TkText, padX), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_PIXELS, "-pady", "padY", "Pad",
	DEF_TEXT_PADY, TCL_INDEX_NONE, offsetof(TkText, padY), 0, 0, 0},
    {TK_OPTION_RELIEF, "-relief", "relief", "Relief",
	DEF_TEXT_RELIEF, TCL_INDEX_NONE, offsetof(TkText, relief), 0, 0, 0},
    {TK_OPTION_INT, "-responsiveness", "responsiveness", "Responsiveness",
	"50", TCL_INDEX_NONE, offsetof(TkText, responsiveness), 0, 0, 0},
    {TK_OPTION_BORDER, "-selectbackground", "selectBackground", "Foreground",
	DEF_TEXT_SELECT_COLOR, TCL_INDEX_NONE, offsetof(TkText, selAttrs.border),
	0, DEF_TEXT_SELECT_MONO, 0},
    {TK_OPTION_PIXELS, "-selectborderwidth", "selectBorderWidth", "BorderWidth",
	DEF_TEXT_SELECT_BD_COLOR, offsetof(TkText, selAttrs.borderWidthPtr),
	offsetof(TkText, selAttrs.borderWidth), TK_OPTION_NULL_OK, DEF_TEXT_SELECT_BD_MONO, 0},
    {TK_OPTION_COLOR, "-selectforeground", "selectForeground", "Background",
	DEF_TEXT_SELECT_FG_COLOR, TCL_INDEX_NONE, offsetof(TkText, selAttrs.fgColor),
	TK_OPTION_NULL_OK, DEF_TEXT_SELECT_FG_MONO, 0},
    {TK_OPTION_BOOLEAN, "-setgrid", "setGrid", "SetGrid",
	DEF_TEXT_SET_GRID, TCL_INDEX_NONE, offsetof(TkText, setGrid), 0, 0, 0},
    {TK_OPTION_BOOLEAN, "-showendofline", "showEndOfLine", "ShowEndOfLine",
	"0", TCL_INDEX_NONE, offsetof(TkText, showEndOfLine), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_BOOLEAN, "-showendoftext", "showEndOfText", "ShowEndOfText",
	"0", TCL_INDEX_NONE, offsetof(TkText, showEndOfText), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_BOOLEAN, "-showinsertforeground", "showInsertForeground", "ShowInsertForeground",
	"0", TCL_INDEX_NONE, offsetof(TkText, showInsertFgColor), 0, 0, 0},
    {TK_OPTION_STRING_TABLE, "-spacemode", "spaceMode", "SpaceMode",
	"none", TCL_INDEX_NONE, offsetof(TkText, spaceMode), 0, spaceModeStrings, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_PIXELS, "-spacing1", "spacing1", "Spacing",
	DEF_TEXT_SPACING1, TCL_INDEX_NONE, offsetof(TkText, spacing1), 0, 0 , TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_PIXELS, "-spacing2", "spacing2", "Spacing",
	DEF_TEXT_SPACING2, TCL_INDEX_NONE, offsetof(TkText, spacing2), 0, 0 , TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_PIXELS, "-spacing3", "spacing3", "Spacing",
	DEF_TEXT_SPACING3, TCL_INDEX_NONE, offsetof(TkText, spacing3), 0, 0 , TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_CUSTOM, "-startindex", NULL, NULL,
	 NULL, TCL_INDEX_NONE, offsetof(TkText, newStartIndex), TK_OPTION_NULL_OK, &startEndMarkOption, TK_TEXT_INDEX_RANGE},
#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE
    {TK_OPTION_CUSTOM, "-startline", NULL, NULL,
	 NULL, TCL_INDEX_NONE, offsetof(TkText, startLine), TK_OPTION_NULL_OK, &lineOption, TK_TEXT_LINE_RANGE},
#endif
    {TK_OPTION_STRING_TABLE, "-state", "state", "State",
	DEF_TEXT_STATE, TCL_INDEX_NONE, offsetof(TkText, state), 0, stateStrings, 0},
    {TK_OPTION_BOOLEAN, "-steadymarks", "steadyMarks", "SteadyMarks",
	"0", TCL_INDEX_NONE, offsetof(TkText, steadyMarks), TK_OPTION_DONT_SET_DEFAULT, 0, 0},
    {TK_OPTION_INT, "-synctime", "syncTime", "SyncTime",
	"150", TCL_INDEX_NONE, offsetof(TkText, syncTime), 0, 0, TK_TEXT_SYNCHRONIZE},
    {TK_OPTION_STRING, "-tabs", "tabs", "Tabs",
	DEF_TEXT_TABS, offsetof(TkText, tabOptionPtr), TCL_INDEX_NONE, TK_OPTION_NULL_OK, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_STRING_TABLE, "-tabstyle", "tabStyle", "TabStyle",
	DEF_TEXT_TABSTYLE, TCL_INDEX_NONE, offsetof(TkText, tabStyle), 0, tabStyleStrings, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_STRING_TABLE, "-tagging", "tagging", "Tagging",
	"within", TCL_INDEX_NONE, offsetof(TkText, tagging), 0, taggingStrings, 0},
    {TK_OPTION_STRING, "-takefocus", "takeFocus", "TakeFocus",
	DEF_TEXT_TAKE_FOCUS, TCL_INDEX_NONE, offsetof(TkText, takeFocus), TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_BOOLEAN, "-undo", "undo", "Undo",
	DEF_TEXT_UNDO, TCL_INDEX_NONE, offsetof(TkText, undo), TK_OPTION_DONT_SET_DEFAULT, 0 ,0},
    {TK_OPTION_BOOLEAN, "-undotagging", "undoTagging", "UndoTagging",
	"1", TCL_INDEX_NONE, offsetof(TkText, undoTagging), 0, 0 ,0},
    {TK_OPTION_BOOLEAN, "-useunibreak", "useUniBreak", "UseUniBreak",
	"0", TCL_INDEX_NONE, offsetof(TkText, useUniBreak), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_INT, "-width", "width", "Width",
	DEF_TEXT_WIDTH, TCL_INDEX_NONE, offsetof(TkText, width), 0, 0, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_STRING_TABLE, "-wrap", "wrap", "Wrap",
	DEF_TEXT_WRAP, TCL_INDEX_NONE, offsetof(TkText, wrapMode), 0, wrapStrings, TK_TEXT_LINE_GEOMETRY},
    {TK_OPTION_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand",
	DEF_TEXT_XSCROLL_COMMAND, TCL_INDEX_NONE, offsetof(TkText, xScrollCmd), TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_STRING, "-yscrollcommand", "yScrollCommand", "ScrollCommand",
	DEF_TEXT_YSCROLL_COMMAND, TCL_INDEX_NONE, offsetof(TkText, yScrollCmd), TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_END, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0}
};

/*
 * These three typedefs, the structure and the SearchPerform, SearchCore
 * functions below are used for line-based searches of the text widget, and,
 * in particular, to handle multi-line matching even though the text widget is
 * a single-line based data structure. They are completely abstracted away
 * from the Text widget internals, however, so could easily be re-used with
 * any line-based entity to provide multi-line matching.
 *
 * We have abstracted this code away from the text widget to try to keep Tk as
 * modular as possible.
 */

struct SearchSpec;	/* Forward declaration. */

typedef ClientData	SearchAddLineProc(int lineNum, struct SearchSpec *searchSpecPtr,
			    Tcl_Obj *theLine, int *lenPtr, int *extraLinesPtr);
typedef int		SearchMatchProc(int lineNum, struct SearchSpec *searchSpecPtr,
			    ClientData clientData, Tcl_Obj *theLine, int matchOffset, int matchLength);
typedef int		SearchLineIndexProc(Tcl_Interp *interp, Tcl_Obj *objPtr,
			    struct SearchSpec *searchSpecPtr, int *linePosPtr, int *offsetPosPtr);

typedef struct SearchSpec {
    TkText *textPtr;		/* Information about widget. */
    int exact;			/* Whether search is exact or regexp. */
    int noCase;		/* Case-insenstivive? */
    int noLineStop;		/* If not set, a regexp search will use the TCL_REG_NLSTOP flag. */
    int overlap;		/* If set, results from multiple searches (-all) are allowed to
    				 * overlap each other. */
    int strictLimits;		/* If set, matches must be completely inside the from,to range.
    				 * Otherwise the limits only apply to the start of each match. */
    int all;			/* Whether all or the first match should be reported. */
    int backwards;		/* Searching forwards or backwards. */
    int searchElide;		/* Search in hidden text as well. */
    int searchHyphens;		/* Search in soft hyhens as well. */
    int startLine;		/* First line to examine. */
    int startOffset;		/* Index in first line to start at. */
    int stopLine;		/* Last line to examine, or -1 when we search all available text. */
    int stopOffset;		/* Index to stop at, provided stopLine is not -1. */
    int numLines;		/* Total lines which are available. */
    Tcl_Obj *varPtr;		/* If non-NULL, store length(s) of match(es) in this variable. */
    Tcl_Obj *countPtr;		/* Keeps track of currently found lengths. */
    Tcl_Obj *resPtr;		/* Keeps track of currently found locations */
    SearchAddLineProc *addLineProc;
				/* Function to call when we need to add another line to the search
				 * string so far */
    SearchMatchProc *foundMatchProc;
				/* Function to call when we have found a match. */
    SearchLineIndexProc *lineIndexProc;
				/* Function to call when we have found a match. */
    ClientData clientData;	/* Information about structure being searched, in this case a text
    				 * widget. */
} SearchSpec;

/*
 * The text-widget-independent functions which actually perform the search,
 * handling both regexp and exact searches.
 */

static int	SearchCore(Tcl_Interp *interp, SearchSpec *searchSpecPtr, Tcl_Obj *patObj);
static int	SearchPerform(Tcl_Interp *interp, SearchSpec *searchSpecPtr, Tcl_Obj *patObj,
		    Tcl_Obj *fromPtr, Tcl_Obj *toPtr);

/*
 * We need a simple linked list for strings:
 */

typedef struct TkTextStringList {
    struct TkTextStringList *nextPtr;
    Tcl_Obj *strObjPtr;
} TkTextStringList;

/*
 * Boolean variable indicating whether or not special debugging code should be executed.
 */

int tkTextDebug = 0;

typedef const TkTextUndoAtom * (*InspectUndoStackProc)(TkTextUndoStack stack);

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

static int		DeleteIndexRange(TkSharedText *sharedTextPtr, TkText *textPtr,
			    const TkTextIndex *indexPtr1, const TkTextIndex *indexPtr2, int flags,
			    int viewUpdate, int triggerWatchDelete, int triggerWatchInsert,
			    int userFlag, int final);
static int		CountIndices(const TkText *textPtr, const TkTextIndex *indexPtr1,
			    const TkTextIndex *indexPtr2, TkTextCountType type);
static void		DestroyText(TkText *textPtr);
static void		ClearText(TkText *textPtr, int clearTags);
static void		FireWidgetViewSyncEvent(ClientData clientData);
static void		FreeEmbeddedWindows(TkText *textPtr);
static void		InsertChars(TkText *textPtr, TkTextIndex *index1Ptr, TkTextIndex *index2Ptr,
			    char const *string, unsigned length, int viewUpdate,
			    TkTextTagSet *tagInfoPtr, TkTextTag *hyphenTagPtr, int parseHyphens);
static void		TextBlinkProc(ClientData clientData);
static void		TextCmdDeletedProc(ClientData clientData);
static int		CreateWidget(TkSharedText *sharedTextPtr, Tk_Window tkwin, Tcl_Interp *interp,
			    const TkText *parent, int objc, Tcl_Obj *const objv[]);
static void		TextEventProc(ClientData clientData, XEvent *eventPtr);
static void		ProcessConfigureNotify(TkText *textPtr, int updateLineGeometry);
static TkSizeT		TextFetchSelection(ClientData clientData, TkSizeT offset, char *buffer,
			    TkSizeT maxBytes);
static int		TextIndexSortProc(const void *first, const void *second);
static int		TextInsertCmd(TkText *textPtr, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const objv[], const TkTextIndex *indexPtr,
			    int viewUpdate, int triggerWatchDelete, int triggerWatchInsert,
			    int userFlag, int parseHyphens);
static int		TextReplaceCmd(TkText *textPtr, Tcl_Interp *interp,
			    const TkTextIndex *indexFromPtr, const TkTextIndex *indexToPtr,
			    int objc, Tcl_Obj *const objv[], int viewUpdate, int triggerWatch,
			    int userFlag, int parseHyphens);
static int		TextSearchCmd(TkText *textPtr, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const objv[]);
static int		TextEditCmd(TkText *textPtr, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const objv[]);
static int		TextWidgetObjCmd(ClientData clientData,
			    Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]);
static void		TextWorldChangedCallback(ClientData instanceData);
static void		TextWorldChanged(TkText *textPtr, int mask);
static void		UpdateLineMetrics(TkText *textPtr, unsigned lineNum, unsigned endLine);
static int		TextChecksumCmd(TkText *textPtr, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const objv[]);
static int		TextDumpCmd(TkText *textPtr, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const objv[]);
static int		TextInspectCmd(TkText *textPtr, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const objv[]);
static int		DumpLine(Tcl_Interp *interp, TkText *textPtr,
			    int what, TkTextLine *linePtr, int start, int end,
			    int lineno, Tcl_Obj *command, TkTextTag **prevTagPtr);
static int		DumpSegment(TkText *textPtr, Tcl_Interp *interp, const char *key,
			    const char *value, Tcl_Obj *command, const TkTextIndex *index, int what);
static void		InspectUndoStack(const TkSharedText *sharedTextPtr,
			    InspectUndoStackProc firstAtomProc, InspectUndoStackProc nextAtomProc,
			    Tcl_Obj *objPtr);
static void		InspectRetainedUndoItems(const TkSharedText *sharedTextPtr, Tcl_Obj *objPtr);
static Tcl_Obj *	TextGetText(TkText *textPtr, const TkTextIndex *index1,
			    const TkTextIndex *index2, TkTextIndex *lastIndexPtr, Tcl_Obj *resultPtr,
			    unsigned maxBytes, int visibleOnly, int includeHyphens);
static void		GenerateEvent(TkSharedText *sharedTextPtr, const char *type);
static void		RunAfterSyncCmd(ClientData clientData);
static void		UpdateModifiedFlag(TkSharedText *sharedTextPtr, int flag);
static Tcl_Obj *	MakeEditInfo(Tcl_Interp *interp, TkText *textPtr, Tcl_Obj *arrayPtr);
static Tcl_Obj *	GetEditInfo(Tcl_Interp *interp, TkText *textPtr, Tcl_Obj *option);
static unsigned		TextSearchIndexInLine(const SearchSpec *searchSpecPtr, TkTextLine *linePtr,
			    int byteIndex);
static int		TextPeerCmd(TkText *textPtr, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const objv[]);
static int		TextWatchCmd(TkText *textPtr, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const objv[]);
static int		TriggerWatchEdit(TkText *textPtr, int userFlag, const char *operation,
			    const TkTextIndex *indexPtr1, const TkTextIndex *indexPtr2,
			    const char *info, int final);
static void		TriggerUndoStackEvent(TkSharedText *sharedTextPtr);
static void		PushRetainedUndoTokens(TkSharedText *sharedTextPtr);
static void		PushUndoSeparatorIfNeeded(TkSharedText *sharedTextPtr, int autoSeparators,
			    TkTextEditMode currentEditMode);
static int		IsEmpty(const TkSharedText *sharedTextPtr, const TkText *textPtr);
static int		IsClean(const TkSharedText *sharedTextPtr, const TkText *textPtr,
			    int discardSelection);
static TkTextUndoPerformProc TextUndoRedoCallback;
static TkTextUndoFreeProc TextUndoFreeCallback;
static TkTextUndoStackContentChangedProc TextUndoStackContentChangedCallback;

/*
 * Some definitions for controlling "dump", "inspect", and "checksum".
 */

enum {
    TK_DUMP_TEXT                    = SEG_GROUP_CHAR,
    TK_DUMP_CHARS                   = TK_DUMP_TEXT|SEG_GROUP_HYPHEN,
    TK_DUMP_MARK                    = SEG_GROUP_MARK,
    TK_DUMP_ELIDE                   = SEG_GROUP_BRANCH,
    TK_DUMP_TAG                     = SEG_GROUP_TAG,
    TK_DUMP_WIN                     = SEG_GROUP_WINDOW,
    TK_DUMP_IMG                     = SEG_GROUP_IMAGE,
    TK_DUMP_NODE                    = 1 << 18,
    TK_DUMP_DUMP_ALL                = TK_DUMP_TEXT|TK_DUMP_CHARS|TK_DUMP_MARK|TK_DUMP_TAG|
                                      TK_DUMP_WIN|TK_DUMP_IMG,

    TK_DUMP_DISPLAY                 = 1 << 19,
    TK_DUMP_DISPLAY_CHARS           = TK_DUMP_CHARS|TK_DUMP_DISPLAY,
    TK_DUMP_DISPLAY_TEXT            = TK_DUMP_TEXT|TK_DUMP_DISPLAY,
    TK_DUMP_CRC_DFLT                = TK_DUMP_TEXT|SEG_GROUP_WINDOW|SEG_GROUP_IMAGE,
    TK_DUMP_CRC_ALL                 = TK_DUMP_TEXT|TK_DUMP_CHARS|TK_DUMP_DISPLAY_TEXT|SEG_GROUP_WINDOW|
			              SEG_GROUP_IMAGE|TK_DUMP_MARK|TK_DUMP_TAG,

    TK_DUMP_NESTED                  = 1 << 20,
    TK_DUMP_TEXT_CONFIGS            = 1 << 21,
    TK_DUMP_TAG_CONFIGS             = 1 << 22,
    TK_DUMP_TAG_BINDINGS            = 1 << 23,
    TK_DUMP_INSERT_MARK             = 1 << 24,
    TK_DUMP_INCLUDE_SEL             = 1 << 25,
    TK_DUMP_DONT_RESOLVE_COLORS     = 1 << 26,
    TK_DUMP_DONT_RESOLVE_FONTS      = 1 << 27,
    TK_DUMP_INCLUDE_DATABASE_CONFIG = 1 << 28,
    TK_DUMP_INCLUDE_SYSTEM_CONFIG   = 1 << 29,
    TK_DUMP_INCLUDE_DEFAULT_CONFIG  = 1 << 30,
    TK_DUMP_INCLUDE_SYSTEM_COLORS   = 1U << 31,
    TK_DUMP_INSPECT_DFLT            = TK_DUMP_DUMP_ALL,
    TK_DUMP_INSPECT_COMPLETE        = TK_DUMP_INSPECT_DFLT|TK_DUMP_TAG_BINDINGS|TK_DUMP_TEXT_CONFIGS|
    			              TK_DUMP_TAG_CONFIGS|TK_DUMP_INCLUDE_SEL|TK_DUMP_INSERT_MARK|
				      TK_DUMP_INCLUDE_DATABASE_CONFIG|TK_DUMP_INCLUDE_SYSTEM_CONFIG|
				      TK_DUMP_INCLUDE_DEFAULT_CONFIG|TK_DUMP_ELIDE|
				      TK_DUMP_INCLUDE_SYSTEM_COLORS,
    TK_DUMP_INSPECT_ALL             = TK_DUMP_INSPECT_COMPLETE|TK_DUMP_DISPLAY_TEXT|
    			              TK_DUMP_DONT_RESOLVE_COLORS|TK_DUMP_DONT_RESOLVE_FONTS|
				      TK_DUMP_NESTED,
};

/*
 * Declarations of the three search procs required by the multi-line search routines.
 */

static SearchMatchProc		TextSearchFoundMatch;
static SearchAddLineProc	TextSearchAddNextLine;
static SearchLineIndexProc	TextSearchGetLineIndex;

/*
 * The structure below defines text class behavior by means of functions that
 * can be invoked from generic window code.
 */

static const Tk_ClassProcs textClass = {
    sizeof(Tk_ClassProcs),	/* size */
    TextWorldChangedCallback,	/* worldChangedProc */
    NULL,			/* createProc */
    NULL			/* modalProc */
};

#if TK_CHECK_ALLOCS

/*
 * Some stuff for memory checks, and allocation statistic.
 */

unsigned tkTextCountNewShared = 0;
unsigned tkTextCountDestroyShared = 0;
unsigned tkTextCountNewPeer = 0;
unsigned tkTextCountDestroyPeer = 0;
unsigned tkTextCountNewPixelInfo = 0;
unsigned tkTextCountDestroyPixelInfo = 0;
unsigned tkTextCountNewSegment = 0;
unsigned tkTextCountDestroySegment = 0;
unsigned tkTextCountNewTag = 0;
unsigned tkTextCountDestroyTag = 0;
unsigned tkTextCountNewUndoToken = 0;
unsigned tkTextCountDestroyUndoToken = 0;
unsigned tkTextCountNewNode = 0;
unsigned tkTextCountDestroyNode = 0;
unsigned tkTextCountNewLine = 0;
unsigned tkTextCountDestroyLine = 0;
unsigned tkTextCountNewSection = 0;
unsigned tkTextCountDestroySection = 0;

extern unsigned tkIntSetCountDestroy;
extern unsigned tkIntSetCountNew;
extern unsigned tkBitCountNew;
extern unsigned tkBitCountDestroy;

typedef struct WatchShared {
    TkSharedText *sharedTextPtr;
    struct WatchShared *nextPtr;
} WatchShared;

static unsigned widgetNumber = 0;
static WatchShared *watchShared;

static void
AllocStatistic()
{
    const WatchShared *wShared;

    if (!tkBTreeDebug) {
	return;
    }

    for (wShared = watchShared; wShared; wShared = wShared->nextPtr) {
	const TkText *peer;

	for (peer = wShared->sharedTextPtr->peers; peer; peer = peer->next) {
	    fprintf(stderr, "Unreleased text widget %d\n", peer->widgetNumber);
	}
    }

    fprintf(stderr, "---------------------------------\n");
    fprintf(stderr, "ALLOCATION:        new    destroy\n");
    fprintf(stderr, "---------------------------------\n");
    fprintf(stderr, "Shared:       %8u - %8u\n", tkTextCountNewShared, tkTextCountDestroyShared);
    fprintf(stderr, "Peer:         %8u - %8u\n", tkTextCountNewPeer, tkTextCountDestroyPeer);
    fprintf(stderr, "Segment:      %8u - %8u\n", tkTextCountNewSegment, tkTextCountDestroySegment);
    fprintf(stderr, "Tag:          %8u - %8u\n", tkTextCountNewTag, tkTextCountDestroyTag);
    fprintf(stderr, "UndoToken:    %8u - %8u\n", tkTextCountNewUndoToken, tkTextCountDestroyUndoToken);
    fprintf(stderr, "Node:         %8u - %8u\n", tkTextCountNewNode, tkTextCountDestroyNode);
    fprintf(stderr, "Line:         %8u - %8u\n", tkTextCountNewLine, tkTextCountDestroyLine);
    fprintf(stderr, "Section:      %8u - %8u\n", tkTextCountNewSection, tkTextCountDestroySection);
    fprintf(stderr, "PixelInfo:    %8u - %8u\n", tkTextCountNewPixelInfo, tkTextCountDestroyPixelInfo);
    fprintf(stderr, "BitField:     %8u - %8u\n", tkBitCountNew, tkBitCountDestroy);
    fprintf(stderr, "IntSet:       %8u - %8u\n", tkIntSetCountNew, tkIntSetCountDestroy);
    fprintf(stderr, "--------------------------------\n");

    if (tkTextCountNewShared != tkTextCountDestroyShared
	    || tkTextCountNewPeer != tkTextCountDestroyPeer
	    || tkTextCountNewSegment != tkTextCountDestroySegment
	    || tkTextCountNewTag != tkTextCountDestroyTag
	    || tkTextCountNewUndoToken != tkTextCountDestroyUndoToken
	    || tkTextCountNewNode != tkTextCountDestroyNode
	    || tkTextCountNewLine != tkTextCountDestroyLine
	    || tkTextCountNewSection != tkTextCountDestroySection
	    || tkTextCountNewPixelInfo != tkTextCountDestroyPixelInfo
	    || tkBitCountNew != tkBitCountDestroy
	    || tkIntSetCountNew != tkIntSetCountDestroy)  {
	fprintf(stderr, "*** memory leak detected ***\n");
	fprintf(stderr, "----------------------------\n");
	/* TkBitCheckAllocs(); */
    }
}
#endif /* TK_CHECK_ALLOCS */

#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE

/*
 * Some helpers.
 */

static void WarnAboutDeprecatedStartLineOption() {
    static int printWarning = 1;
    if (printWarning) {
	fprintf(stderr, "tk::text: Option \"-startline\" is deprecated, "
		"please use option \"-startindex\".\n");
	printWarning = 0;
    }
}
static void WarnAboutDeprecatedEndLineOption() {
    static int printWarning = 1;
    if (printWarning) {
	fprintf(stderr, "tk::text: Option \"-endline\" is deprecated, "
		"please use option \"-endindex\".\n");
	printWarning = 0;
    }
}

#endif /* SUPPORT_DEPRECATED_STARTLINE_ENDLINE */

/*
 * Helper for guarded release of objects.
 */

static void
Tcl_GuardedDecrRefCount(Tcl_Obj *objPtr)
{
#ifndef NDEBUG
    /*
     * Tcl does not provide any function for querying the reference count.
     * So we need a work-around. Why does Tcl not provide a guarded version
     * for such a dangerous function?
     */
    assert(objPtr);
    Tcl_IncrRefCount(objPtr);
    assert(Tcl_IsShared(objPtr));
    Tcl_DecrRefCount(objPtr);
#endif
    Tcl_DecrRefCount(objPtr);
}

/*
 *--------------------------------------------------------------
 *
 * GetByteLength --
 *
 *	This function should be defined by Tcl, but it isn't defined,
 *	so we are doing this.
 *
 * Results:
 *	The length of the string.
 *
 * Side effects:
 *	Calls Tcl_GetString(objPtr) if objPtr->bytes is not yet resolved.
 *
 *--------------------------------------------------------------
 */

static TkSizeT
GetByteLength(
    Tcl_Obj *objPtr)
{
    assert(objPtr);

    if (!objPtr->bytes) {
	Tcl_GetString(objPtr);
    }
    return objPtr->length;
}

/*
 *--------------------------------------------------------------
 *
 * Tk_TextObjCmd --
 *
 *	This function is invoked to process the "text" Tcl command. See the
 *	user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

int
Tk_TextObjCmd(
    ClientData clientData,	/* Main window associated with interpreter. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    Tk_Window tkwin = (Tk_Window)clientData;

    if (objc < 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "pathName ?-option value ...?");
	return TCL_ERROR;
    }

    if (!tkwin) {
	tkwin = Tk_MainWindow(interp);
    }
    return CreateWidget(NULL, tkwin, interp, NULL, objc, objv);
}

/*
 *----------------------------------------------------------------------
 *
 * PushRetainedUndoTokens --
 *
 *	Push the retained undo tokens onto the stack.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Same as TkTextPushUndoToken, additionaly 'undoTagList' and
 *	'undoMarkList' will be cleared.
 *
 *----------------------------------------------------------------------
 */

static void
PushRetainedUndoTokens(
    TkSharedText *sharedTextPtr)
{
    unsigned i;

    assert(sharedTextPtr);
    assert(sharedTextPtr->undoStack);

    for (i = 0; i < sharedTextPtr->undoTagListCount; ++i) {
	TkTextPushUndoTagTokens(sharedTextPtr, sharedTextPtr->undoTagList[i]);
    }

    for (i = 0; i < sharedTextPtr->undoMarkListCount; ++i) {
	TkTextPushUndoMarkTokens(sharedTextPtr, &sharedTextPtr->undoMarkList[i]);
    }

    sharedTextPtr->undoTagListCount = 0;
    sharedTextPtr->undoMarkListCount = 0;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextPushUndoToken --
 *
 *	This function is pushing the given undo/redo token. Don't use
 *	TkTextUndoPushItem, because some of the prepared undo tokens
 *	are retained.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Same as TkTextUndoPushItem, furthermore all retained items
 *	will be pushed.
 *
 *----------------------------------------------------------------------
 */

void
TkTextPushUndoToken(
    TkSharedText *sharedTextPtr,
    void *token,
    unsigned byteSize)
{
    TkTextUndoAction action;

    assert(sharedTextPtr);
    assert(sharedTextPtr->undoStack);
    assert(token);

    action = ((TkTextUndoToken *) token)->undoType->action;

    if (action == TK_TEXT_UNDO_INSERT || action == TK_TEXT_UNDO_DELETE) {
	sharedTextPtr->insertDeleteUndoTokenCount += 1;
    }

    PushRetainedUndoTokens(sharedTextPtr);
    TkTextUndoPushItem(sharedTextPtr->undoStack, token, byteSize);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextPushRedoToken --
 *
 *	This function is pushing the given redo token. This function
 *	is useful only for the reconstruction of the undo stack.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Same as TkTextUndoPushRedoItem.
 *
 *----------------------------------------------------------------------
 */

void
TkTextPushRedoToken(
    TkSharedText *sharedTextPtr,
    void *token,
    unsigned byteSize)
{
    assert(sharedTextPtr);
    assert(sharedTextPtr->undoStack);
    assert(token);

    TkTextUndoPushRedoItem(sharedTextPtr->undoStack, token, byteSize);
}

/*
 *--------------------------------------------------------------
 *
 * CreateWidget --
 *
 *	This function is invoked to process the "text" Tcl command, (when
 *	called by Tk_TextObjCmd) and the "$text peer create" text widget
 *	sub-command (called from TextPeerCmd).
 *
 *	See the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result, places the name of the widget created into the
 *	interp's result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */
# define TK_TEXT_SET_MAX_BIT_SIZE (((512 + TK_BIT_NBITS - 1)/TK_BIT_NBITS)*TK_BIT_NBITS)

static int
CreateWidget(
    TkSharedText *sharedTextPtr,/* Shared widget info, or NULL. */
    Tk_Window tkwin,		/* Main window associated with interpreter. */
    Tcl_Interp *interp,		/* Current interpreter. */
    const TkText *parent,	/* If non-NULL then take default start, end
				 * from this parent. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    TkText *textPtr;
    Tk_OptionTable optionTable;
    TkTextIndex startIndex;
    Tk_Window newWin;

    /*
     * Create the window.
     */

    if (!(newWin = Tk_CreateWindowFromPath(interp, tkwin, Tcl_GetString(objv[1]), NULL))) {
	return TCL_ERROR;
    }

    if (!sharedTextPtr) {
	sharedTextPtr = (TkSharedText *)calloc(1, sizeof(TkSharedText));

	Tcl_InitHashTable(&sharedTextPtr->tagTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->markTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->windowTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->imageTable, TCL_STRING_KEYS);
	sharedTextPtr->usedTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->elisionTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->selectionTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->dontUndoTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->affectDisplayTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->notAffectDisplayTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->affectDisplayNonSelTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->affectGeometryTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->affectGeometryNonSelTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->affectLineHeightTags = TkBitResize(NULL, TK_TEXT_SET_MAX_BIT_SIZE);
	sharedTextPtr->tagLookup = (TkTextTag **)malloc(TK_TEXT_SET_MAX_BIT_SIZE*sizeof(TkTextTag *));
	sharedTextPtr->emptyTagInfoPtr = TkTextTagSetResize(NULL, 0);
	sharedTextPtr->maxRedoDepth = -1;
	sharedTextPtr->autoSeparators = 1;
	sharedTextPtr->undoTagging = 1;
	sharedTextPtr->lastEditMode = TK_TEXT_EDIT_OTHER;
	sharedTextPtr->lastUndoTokenType = -1;
	sharedTextPtr->startMarker = TkTextMakeStartEndMark(NULL, &tkTextLeftMarkType);
	sharedTextPtr->endMarker = TkTextMakeStartEndMark(NULL, &tkTextRightMarkType);
	sharedTextPtr->protectionMark[0] = TkTextMakeMark(NULL, NULL);
	sharedTextPtr->protectionMark[1] = TkTextMakeMark(NULL, NULL);
	sharedTextPtr->protectionMark[0]->typePtr = &tkTextProtectionMarkType;
	sharedTextPtr->protectionMark[1]->typePtr = &tkTextProtectionMarkType;

	DEBUG(memset(sharedTextPtr->tagLookup, 0, TK_TEXT_SET_MAX_BIT_SIZE*sizeof(TkTextTag *)));

	sharedTextPtr->mainPeer = (TkText *)calloc(1, sizeof(TkText));
	sharedTextPtr->mainPeer->startMarker = sharedTextPtr->startMarker;
	sharedTextPtr->mainPeer->endMarker = sharedTextPtr->endMarker;
	sharedTextPtr->mainPeer->sharedTextPtr = sharedTextPtr;

#if TK_CHECK_ALLOCS
	if (tkTextCountNewShared++ == 0) {
	    atexit(AllocStatistic);
	}
	/*
	 * Add this shared resource to global list.
	 */
	{
	    WatchShared *wShared = malloc(sizeof(WatchShared));
	    wShared->sharedTextPtr = sharedTextPtr;
	    wShared->nextPtr = watchShared;
	    watchShared = wShared;
	}
#endif

	/*
	 * The construction of the tree requires a valid setup of the shared resource.
	 */

	sharedTextPtr->tree = TkBTreeCreate(sharedTextPtr, 1);
    }

    DEBUG_ALLOC(tkTextCountNewPeer++);

    /*
     * Create the text widget and initialize everything to zero, then set the
     * necessary initial (non-NULL) values. It is important that the 'set' tag
     * and 'insert', 'current' mark pointers are all NULL to start.
     */

    textPtr = (TkText *)calloc(1, sizeof(TkText));
    textPtr->tkwin = newWin;
    textPtr->display = Tk_Display(newWin);
    textPtr->interp = interp;
    textPtr->widgetCmd = Tcl_CreateObjCommand(interp, Tk_PathName(textPtr->tkwin),
	    TextWidgetObjCmd, textPtr, TextCmdDeletedProc);
    DEBUG_ALLOC(textPtr->widgetNumber = ++widgetNumber);

    /*
     * Add the new widget to the shared list.
     */

    textPtr->sharedTextPtr = sharedTextPtr;
    sharedTextPtr->refCount += 1;
    textPtr->next = sharedTextPtr->peers;
    sharedTextPtr->peers = textPtr;

    /*
     * Clear the indices, do this after the shared widget is created.
     */

    TkTextIndexClear(&textPtr->topIndex, textPtr);
    TkTextIndexClear(&textPtr->selIndex, textPtr);

    /*
     * This refCount will be held until DestroyText is called. Note also that
     * the later call to 'TkTextCreateDInfo' will add more refCounts.
     */

    textPtr->refCount = 1;

    /*
     * Specify start and end lines in the B-tree. The default is the same as
     * the parent, but this can be adjusted to display more or less if the
     * start, end where given as configuration options.
     */

    if (parent) {
	(textPtr->startMarker = parent->startMarker)->refCount += 1;
	(textPtr->endMarker = parent->endMarker)->refCount += 1;
#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE
	textPtr->startLine = parent->startLine;
	textPtr->endLine = parent->endLine;
#endif
    } else {
	(textPtr->startMarker = sharedTextPtr->startMarker)->refCount += 1;
	(textPtr->endMarker = sharedTextPtr->endMarker)->refCount += 1;
    }

    /*
     * Register with the B-tree. In some sense it would be best if we could do
     * this later (after configuration options), so that any changes to
     * start,end do not require a total recalculation.
     */

    TkBTreeAddClient(sharedTextPtr->tree, textPtr, textPtr->lineHeight);

    textPtr->state = TK_TEXT_STATE_NORMAL;
    textPtr->relief = TK_RELIEF_FLAT;
    textPtr->cursor = NULL;
    textPtr->charWidth = 1;
    textPtr->spaceWidth = 1;
    textPtr->lineHeight = -1;
    textPtr->prevWidth = Tk_Width(newWin);
    textPtr->prevHeight = Tk_Height(newWin);
    textPtr->useHyphenSupport = -1;
    textPtr->hyphenRules = TK_TEXT_HYPHEN_MASK;
    textPtr->prevSyncState = -1;
    textPtr->lastLineY = TK_TEXT_NEARBY_IS_UNDETERMINED;
    TkTextTagSetIncrRefCount(textPtr->curTagInfoPtr = sharedTextPtr->emptyTagInfoPtr);

    /*
     * This will add refCounts to textPtr.
     */

    TkTextCreateDInfo(textPtr);
    TkTextIndexSetupToStartOfText(&startIndex, textPtr, sharedTextPtr->tree);
    TkTextSetYView(textPtr, &startIndex, 0);
    textPtr->exportSelection = 1;
    textPtr->pickEvent.type = LeaveNotify;
    textPtr->steadyMarks = sharedTextPtr->steadyMarks;
    textPtr->undo = sharedTextPtr->undo;
    textPtr->maxUndoDepth = sharedTextPtr->maxUndoDepth;
    textPtr->maxRedoDepth = sharedTextPtr->maxRedoDepth;
    textPtr->maxUndoSize = sharedTextPtr->maxUndoSize;
    textPtr->autoSeparators = sharedTextPtr->autoSeparators;
    textPtr->undoTagging = sharedTextPtr->undoTagging;

    /*
     * Create the "sel" tag and the "current" and "insert" marks.
     * Note: it is important that textPtr->selTagPtr is NULL before this
     * initial call.
     */

    textPtr->selTagPtr = TkTextCreateTag(textPtr, "sel", NULL);
    textPtr->insertMarkPtr = TkrTextSetMark(textPtr, "insert", &startIndex);
    textPtr->currentMarkPtr = TkrTextSetMark(textPtr, "current", &startIndex);
    textPtr->currentMarkIndex = startIndex;

    sharedTextPtr->numPeers += 1;

    /*
     * Create the option table for this widget class. If it has already been
     * created, the cached pointer will be returned.
     */

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);

    Tk_SetClass(textPtr->tkwin, "Text");
    Tk_SetClassProcs(textPtr->tkwin, &textClass, textPtr);
    textPtr->optionTable = optionTable;

    Tk_CreateEventHandler(textPtr->tkwin,
	    ExposureMask|StructureNotifyMask|FocusChangeMask, TextEventProc, textPtr);
    Tk_CreateEventHandler(textPtr->tkwin, KeyPressMask|KeyReleaseMask
	    |ButtonPressMask|ButtonReleaseMask|EnterWindowMask
	    |LeaveWindowMask|PointerMotionMask|VirtualEventMask,
	    TkTextBindProc, textPtr);
    Tk_CreateSelHandler(textPtr->tkwin, XA_PRIMARY, XA_STRING, TextFetchSelection, textPtr, XA_STRING);

    if (Tk_InitOptions(interp, textPtr, optionTable, textPtr->tkwin) != TCL_OK) {
	Tk_DestroyWindow(textPtr->tkwin);
	return TCL_ERROR;
    }
    textPtr->textConfigAttrs = textPtr->selAttrs;
    textPtr->selTagPtr->attrs = textPtr->selAttrs;

    if (TkConfigureText(interp, textPtr, objc - 2, objv + 2) != TCL_OK) {
	Tk_DestroyWindow(textPtr->tkwin);
	return TCL_ERROR;
    }

    Tcl_SetObjResult(interp, Tk_NewWindowObj(textPtr->tkwin));
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * UpdateLineMetrics --
 *
 *	This function updates the pixel height calculations of a range of
 *	lines in the widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Line heights may be recalculated.
 *
 *--------------------------------------------------------------
 */

static void
UpdateLineMetrics(
    TkText *textPtr,		/* Information about widget. */
    unsigned startLine,		/* Start at this line. */
    unsigned endLine)		/* Go no further than this line. */
{
    if (!textPtr->sharedTextPtr->allowUpdateLineMetrics) {
	ProcessConfigureNotify(textPtr, 1);
    }
    TkTextUpdateLineMetrics(textPtr, startLine, endLine);
}

/*
 *--------------------------------------------------------------
 *
 * TkTextAttemptToModifyDisabledWidget --
 *
 *	The GUI tries to modify a disabled text widget, so an
 *	error will be thrown.
 *
 * Results:
 *	Returns TCL_ERROR.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static void
ErrorNotAllowed(
    Tcl_Interp *interp,
    const char *text)
{
    Tcl_SetObjResult(interp, Tcl_NewStringObj(text, -1));
    Tcl_SetErrorCode(interp, "TK", "TEXT", "NOT_ALLOWED", NULL);
}

int
TkTextAttemptToModifyDisabledWidget(
    Tcl_Interp *dummy)
{
#if SUPPORT_DEPRECATED_MODS_OF_DISABLED_WIDGET
    static int showWarning = 1;
    if (showWarning) {
	fprintf(stderr, "tk::text: Attempt to modify a disabled widget is deprecated.\n");
	showWarning = 0;
    }
    return TCL_OK;
#else /* if !SUPPORT_DEPRECATED_MODS_OF_DISABLED_WIDGET */
    ErrorNotAllowed(interp, "attempt to modify disabled widget");
    return TCL_ERROR;
#endif
    (void)dummy;
}

/*
 *--------------------------------------------------------------
 *
 * TkTextAttemptToModifyDeadWidget --
 *
 *	The GUI tries to modify a dead text widget, so an
 *	error will be thrown.
 *
 * Results:
 *	Returns TCL_ERROR.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

int
TkTextAttemptToModifyDeadWidget(
    Tcl_Interp *dummy)
{
#if SUPPORT_DEPRECATED_MODS_OF_DISABLED_WIDGET
    static int showWarning = 1;
    if (showWarning) {
	fprintf(stderr, "tk::text: Attempt to modify a dead widget is deprecated.\n");
	showWarning = 0;
    }
    return TCL_OK;
#else /* if !SUPPORT_DEPRECATED_MODS_OF_DISABLED_WIDGET */
    ErrorNotAllowed(interp, "attempt to modify dead widget");
    return TCL_ERROR;
#endif
    (void)dummy;
}

/*
 *--------------------------------------------------------------
 *
 * TextWidgetObjCmd --
 *
 *	This function is invoked to process the Tcl command that corresponds
 *	to a text widget. See the user documentation for details on what it
 *	does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

static int
TestIfTriggerUserMod(
    TkSharedText *sharedTextPtr,
    Tcl_Obj *indexObjPtr)
{
    return sharedTextPtr->triggerWatchCmd && strcmp(Tcl_GetString(indexObjPtr), "insert") == 0;
}

static int
TestIfPerformingUndoRedo(
    Tcl_Interp *interp,
    const TkSharedText *sharedTextPtr,
    int *result)
{
    if (sharedTextPtr->undoStack && TkTextUndoIsPerformingUndoRedo(sharedTextPtr->undoStack)) {
	/*
	 * It's possible that this command command will be invoked inside the "watch" callback,
	 * but this is not allowed when performing undo/redo.
	 */

	ErrorNotAllowed(interp, "cannot modify inside undo/redo operation");
	if (result) {
	    *result = TCL_ERROR;
	}
	return 1;
    }
    return 0;
}

static int
TestIfDisabled(
    Tcl_Interp *interp,
    const TkText *textPtr,
    int *result)
{
    assert(result);

    if (textPtr->state != TK_TEXT_STATE_DISABLED) {
	return 0;
    }
    *result = TkTextAttemptToModifyDisabledWidget(interp);
    return 1;
}

static int
TestIfDead(
    Tcl_Interp *interp,
    const TkText *textPtr,
    int *result)
{
    assert(result);

    if (!TkTextIsDeadPeer(textPtr)) {
	return 0;
    }
    *result = TkTextAttemptToModifyDeadWidget(interp);
    return 1;
}

static Tcl_Obj *
AppendScript(
    const char *oldScript,
    const char *script)
{
    char buffer[1024];
    int lenOfNew = strlen(script);
    int lenOfOld = strlen(oldScript);
    size_t totalLen = lenOfOld + lenOfNew + 1;
    char *newScript = buffer;
    Tcl_Obj *newScriptObj;

    if (totalLen + 2 > sizeof(buffer)) {
	newScript = (char *)malloc(totalLen + 1);
    }

    memcpy(newScript, oldScript, lenOfOld);
    newScript[lenOfOld] = '\n';
    memcpy(newScript + lenOfOld + 1, script, lenOfNew + 1);
    newScriptObj = Tcl_NewStringObj(newScript, totalLen);
    if (newScript != buffer) { free(newScript); }
    return newScriptObj;
}

#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE
static int
MatchOpt(
    const char *opt,
    const char *pattern,
    unsigned minMatchLen)
{
    if (strncmp(opt, pattern, minMatchLen) != 0) {
	return 0;
    }
    opt += minMatchLen;
    pattern += minMatchLen;
    while (1) {
	if (*opt == '\0') {
	    return 1;
	}
	if (*pattern == '\0') {
	    return 0;
	}
	if (*opt != *pattern) {
	    return 0;
	}
	opt += 1;
	pattern += 1;
    }
    return 0; /* never reached */
}
#endif /* SUPPORT_DEPRECATED_STARTLINE_ENDLINE */

static int
TextWidgetObjCmd(
    ClientData clientData,	/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    TkText *textPtr = (TkText *)clientData;
    TkSharedText *sharedTextPtr;
    int result = TCL_OK;
    int commandIndex = -1;
    int oldUndoStackEvent;

    static const char *const optionStrings[] = {
	"tk_bindvar", "tk_textInsert", "tk_textReplace",
	"bbox", "brks", "checksum", "cget", "clear", "compare", "configure",
	"count", "debug", "delete", "dlineinfo", "dump", "edit", "get", "image",
	"index", "insert", "inspect", "isclean", "isdead", "isempty", "lineno",
	"load", "mark", "peer", "pendingsync", "replace", "scan", "search",
	"see", "sync", "tag", "watch", "window", "xview", "yview", NULL
    };
    enum options {
	TEXT_TK_BINDVAR, TEXT_TK_TEXTINSERT, TEXT_TK_TEXTREPLACE,
	TEXT_BBOX, TEXT_BRKS, TEXT_CHECKSUM, TEXT_CGET, TEXT_CLEAR, TEXT_COMPARE, TEXT_CONFIGURE,
	TEXT_COUNT, TEXT_DEBUG, TEXT_DELETE, TEXT_DLINEINFO, TEXT_DUMP, TEXT_EDIT, TEXT_GET, TEXT_IMAGE,
	TEXT_INDEX, TEXT_INSERT, TEXT_INSPECT, TEXT_ISCLEAN, TEXT_ISDEAD, TEXT_ISEMPTY, TEXT_LINENO,
	TEXT_LOAD, TEXT_MARK, TEXT_PEER, TEXT_PENDINGSYNC, TEXT_REPLACE, TEXT_SCAN, TEXT_SEARCH,
	TEXT_SEE, TEXT_SYNC, TEXT_TAG, TEXT_WATCH, TEXT_WINDOW, TEXT_XVIEW, TEXT_YVIEW
    };

    if (objc < 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
	return TCL_ERROR;
    }

    if (Tcl_GetIndexFromObjStruct(interp, objv[1], optionStrings,
	    sizeof(char *), "option", 0, &commandIndex) != TCL_OK) {
	/*
	 * Hide the first three options, generating the error description with
	 * the side effects of Tcl_GetIndexFromObjStruct.
	 */

	(void) Tcl_GetIndexFromObjStruct(interp, objv[1], optionStrings + 3,
		sizeof(char *), "option", 0, &commandIndex);
	return TCL_ERROR;
    }

    textPtr->refCount += 1;
    sharedTextPtr = textPtr->sharedTextPtr;
    oldUndoStackEvent = sharedTextPtr->undoStackEvent;
    sharedTextPtr->undoStackEvent = 0;

    /*
     * Clear saved insert cursor position.
     */

    TkTextIndexClear(&textPtr->insertIndex, textPtr);

    /*
     * Check if we need to update the "current" mark segment.
     */

    if (sharedTextPtr->haveToSetCurrentMark) {
	TkTextUpdateCurrentMark(sharedTextPtr);
    }

    if (CATCH_ASSERTION_FAILED) {
	result = TCL_ERROR;
	goto done;
    }

    switch ((enum options) commandIndex) {
    case TEXT_TK_BINDVAR: {
	TkTextStringList *listPtr;

	/*
	 * Bind a variable to this widget, this variable will be released (Tcl_UnsetVar2)
	 * when the widget will be destroyed.
	 *
	 * I suggest to provide a general support for binding variables to widgets in a
	 * future Tk version.
	 */

	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "varname");
	    result = TCL_ERROR;
	    goto done;
	}

	listPtr = (TkTextStringList *)malloc(sizeof(TkTextStringList));
	Tcl_IncrRefCount(listPtr->strObjPtr = objv[2]);
	listPtr->nextPtr = textPtr->varBindingList;
	textPtr->varBindingList = listPtr;
	break;
    }
    case TEXT_BBOX: {
	int x, y, width, height, argc = 2;
	int extents = 0;
	TkTextIndex index;

	if (objc == 4) {
	    const char* option = Tcl_GetString(objv[2]);

	    if (strcmp(option, "-extents") == 0) {
		extents = 1;
		argc += 1;
	    } else if (*option == '-') {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad option \"%s\": must be -extents", option));
		result = TCL_ERROR;
		goto done;
	    }
	}
	if (objc - argc + 2 != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-extents? index");
	    result = TCL_ERROR;
	    goto done;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[argc], &index)) {
	    result = TCL_ERROR;
	    goto done;
	}
	if (TkTextIndexBbox(textPtr, &index, extents, &x, &y, &width, &height, NULL, NULL)) {
	    Tcl_Obj *listObj = Tcl_NewObj();

	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(x));
	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(y));
	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(width));
	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(height));

	    Tcl_SetObjResult(interp, listObj);
	}
	break;
    }
    case TEXT_BRKS: {
	Tcl_Obj *arrPtr;
	unsigned length, i;
	char const *lang = NULL;
	char buf[1];

	if (objc != 3 && objc != 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index");
	    result = TCL_ERROR;
	    goto done;
	}
	if (objc == 4) {
	    if (!TkTextTestLangCode(interp, objv[3])) {
		result = TCL_ERROR;
		goto done;
	    }
	    if (!TkTextComputeBreakLocations(interp, "", 0, "en", buf)) {
#if 0 && TCL_UTF_MAX > 4
# ifdef __unix__
#  error "The use of external libraries with a proprietary pseudo UTF-8 encoding is safety-endagering and may result in invalid computationial results. This means: TCL_UTF_MAX > 4 cannot be supported here."
#endif
		ErrorNotAllowed(interp, "external library libunibreak/liblinebreak cannot "
			"be used with non-standard encodings");
#else
		ErrorNotAllowed(interp, "external library libunibreak/liblinebreak is not available");
#endif
		result = TCL_ERROR;
		goto done;
	    }
	    lang = Tcl_GetString(objv[3]);
	}
	if ((length = GetByteLength(objv[2])) < textPtr->brksBufferSize) {
	    textPtr->brksBufferSize = MAX(length, textPtr->brksBufferSize + 512);
	    textPtr->brksBuffer = (char *)realloc(textPtr->brksBuffer, textPtr->brksBufferSize);
	}
	TkTextComputeBreakLocations(interp, Tcl_GetString(objv[2]), length, lang, textPtr->brksBuffer);
	arrPtr = Tcl_NewObj();

	for (i = 0; i < length; ++i) {
	    int value;

	    switch (textPtr->brksBuffer[i]) {
	    case LINEBREAK_INSIDEACHAR: continue;
	    case LINEBREAK_MUSTBREAK:   value = 2; break;
	    case LINEBREAK_ALLOWBREAK:  value = 1; break;
	    default:                    value = 0; break;
	    }
	    Tcl_ListObjAppendElement(interp, arrPtr, Tcl_NewIntObj(value));
	}

	Tcl_SetObjResult(interp, arrPtr);
	break;
    }
    case TEXT_CHECKSUM:
	result = TextChecksumCmd(textPtr, interp, objc, objv);
    	break;
    case TEXT_CGET:
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "option");
	    result = TCL_ERROR;
	    goto done;
	} else {
#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE

	    Tcl_Obj *objPtr, *optionObj = NULL;
	    const char *opt = Tcl_GetString(objv[2]);

	    if (strcmp(opt, "-start") == 0) {
		optionObj = Tcl_NewStringObj(textPtr->startLine ? "-startline" : "-startindex", -1);
	    } else if (MatchOpt(opt, "-startline", 7)) {
		optionObj = Tcl_NewStringObj("-startline", -1);
	    } else if (strcmp(opt, "-end") == 0) {
		optionObj = Tcl_NewStringObj(textPtr->endLine ? "-endline" : "-endindex", -1);
	    } else if (MatchOpt(opt, "-endline", 5)) {
		optionObj = Tcl_NewStringObj("-endline", -1);
	    } else {
		Tcl_IncrRefCount(optionObj = objv[2]);
	    }

	    Tcl_IncrRefCount(optionObj);
	    objPtr = Tk_GetOptionValue(interp, (char *) textPtr,
		    textPtr->optionTable, optionObj, textPtr->tkwin);
	    Tcl_GuardedDecrRefCount(optionObj);

#else /* if !SUPPORT_DEPRECATED_STARTLINE_ENDLINE */

	    objPtr = Tk_GetOptionValue(interp, textPtr,
		    textPtr->optionTable, objv[2], textPtr->tkwin);

#endif /* SUPPORT_DEPRECATED_STARTLINE_ENDLINE */

	    if (!objPtr) {
		result = TCL_ERROR;
		goto done;
	    }
	    Tcl_SetObjResult(interp, objPtr);
	    result = TCL_OK;
	}
	break;
    case TEXT_CLEAR:
	if (TestIfPerformingUndoRedo(interp, sharedTextPtr, &result)) {
	    goto done;
	}
	ClearText(textPtr, 1);
	TkTextRelayoutWindow(textPtr, TK_TEXT_LINE_GEOMETRY);
	TK_BTREE_DEBUG(TkBTreeCheck(sharedTextPtr->tree));
	break;
    case TEXT_COMPARE: {
	int relation, value;
	TkTextIndex index1, index2;

	if (objc != 5) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index1 op index2");
	    result = TCL_ERROR;
	    goto done;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[2], &index1)
		|| !TkTextGetIndexFromObj(interp, textPtr, objv[4], &index2)) {
	    result = TCL_ERROR;
	    goto done;
	}
	relation = TkTextIndexCompare(&index1, &index2);
	value = TkTextTestRelation(interp, relation, Tcl_GetString(objv[3]));
	if (value == -1) {
	    result = TCL_ERROR;
	} else {
	    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(value));
	}
	break;
    }
    case TEXT_CONFIGURE:
	if (objc <= 3) {
	    Tcl_Obj *objPtr = Tk_GetOptionInfo(interp, textPtr,
		    textPtr->optionTable, objc == 3 ? objv[2] : NULL, textPtr->tkwin);

	    if (!objPtr) {
		result = TCL_ERROR;
		goto done;
	    }
	    Tcl_SetObjResult(interp, objPtr);
	} else {
	    result = TkConfigureText(interp, textPtr, objc - 2, objv + 2);
	}
	break;
    case TEXT_COUNT: {
	TkTextIndex indexFrom, indexTo;
	Tcl_Obj *objPtr = NULL;
	int update = 0;
	int i, found = 0;

	if (objc < 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-option value ...? index1 index2");
	    result = TCL_ERROR;
	    goto done;
	}

	if (!TkTextGetIndexFromObj(interp, textPtr, objv[objc - 2], &indexFrom)
		|| !TkTextGetIndexFromObj(interp, textPtr, objv[objc - 1], &indexTo)) {
	    result = TCL_ERROR;
	    goto done;
	}

	for (i = 2; i < objc - 2; i++) {
	    int length;
	    int value = INT_MIN;
	    const char *option = Tcl_GetString(objv[i]);

	    length = GetByteLength(objv[i]);
	    if (length < 2 || option[0] != '-') {
		goto badOption;
	    }
	    switch (option[1]) {
	    case 'c':
		if (strncmp("-chars", option, length) == 0) {
		    value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_CHARS);
		}
		break;
	    case 'd':
	    	if (length > 8 && strncmp("-display", option, 8) == 0) {
		    switch (option[8]) {
		    case 'c':
			if (strcmp("chars", option + 8) == 0) {
			    value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_DISPLAY_CHARS);
			}
			break;
		    case 'h':
			if (strcmp("hyphens", option + 8) == 0) {
			    value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_DISPLAY_HYPHENS);
			}
			break;
		    case 'i':
			if (strcmp("indices", option + 8) == 0) {
			    value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_DISPLAY_INDICES);
			}
			break;
		    case 'l':
			if (strcmp("lines", option + 8) == 0) {
			    int compare = TkTextIndexCompare(&indexFrom, &indexTo);

			    if (compare == 0) {
				value = 0;
			    } else {
				const TkTextIndex *indexPtr1;
				const TkTextIndex *indexPtr2;

				if (compare < 0) {
				    indexPtr1 = &indexFrom;
				    indexPtr2 = &indexTo;
				} else {
				    indexPtr1 = &indexTo;
				    indexPtr2 = &indexFrom;
				}
				if (!sharedTextPtr->allowUpdateLineMetrics) {
				    ProcessConfigureNotify(textPtr, 1);
				}
				value = TkTextCountDisplayLines(textPtr, indexPtr1, indexPtr2);
				if (compare > 0) {
				    value = -value;
				}
			    }
			}
			break;
		    case 't':
			if (strcmp("text", option + 8) == 0) {
			    value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_DISPLAY_TEXT);
			}
			break;
		    }
		}
		break;
	    case 'h':
		if (strncmp("-hyphens", option, length) == 0) {
		    value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_HYPHENS);
		}
		break;
	    case 'i':
		if (strncmp("-indices", option, length) == 0) {
		    value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_INDICES);
		}
		break;
	    case 'l':
	    	if (strncmp("-lines", option, length) == 0) {
		    TkTextBTree tree = sharedTextPtr->tree;
		    value = TkBTreeLinesTo(tree, textPtr, TkTextIndexGetLine(&indexTo), NULL)
			    - TkBTreeLinesTo(tree, textPtr, TkTextIndexGetLine(&indexFrom), NULL);
		}
		break;
	    case 't':
		if (strncmp("-text", option, length) == 0) {
		    value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_TEXT);
		}
		break;
	    case 'u':
		if (strncmp("-update", option, length) == 0) {
		    update = 1;
		    continue;
		}
		break;
	    case 'x':
		if (strncmp("-xpixels", option, length) == 0) {
		    int x1, x2;
		    TkTextIndex index;

		    index = indexFrom;
		    TkTextFindDisplayIndex(textPtr, &index, 0, &x1);
		    index = indexTo;
		    TkTextFindDisplayIndex(textPtr, &index, 0, &x2);
		    value = x2 - x1;
		}
		break;
	    case 'y':
		if (strncmp("-ypixels", option, length) == 0) {
		    int from, to;

		    if (update) {
			from = TkTextIndexGetLineNumber(&indexFrom, textPtr);
			to = TkTextIndexGetLineNumber(&indexTo, textPtr);
			if (from != to) {
			    if (from > to) {
				int tmp = from; from = to; to = tmp;
			    }
			    UpdateLineMetrics(textPtr, from, to);
			}
		    }
		    from = TkTextIndexYPixels(textPtr, &indexFrom);
		    to = TkTextIndexYPixels(textPtr, &indexTo);
		    value = to - from;
		}
		break;
	    }
	    if (value == INT_MIN) {
		goto badOption;
	    }

	    found += 1;
	    if (found == 1) {
		Tcl_SetObjResult(interp, Tcl_NewIntObj(value));
	    } else {
		if (found == 2) {
		    /*
		     * Move the first item we put into the result into the
		     * first element of the list object.
		     */

		    objPtr = Tcl_NewObj();
		    Tcl_ListObjAppendElement(NULL, objPtr,
			    Tcl_GetObjResult(interp));
		}
		Tcl_ListObjAppendElement(NULL, objPtr, Tcl_NewIntObj(value));
	    }
	}

	if (found == 0) {
	    /*
	     * Use the default '-indices'.
	     */

	    int value = CountIndices(textPtr, &indexFrom, &indexTo, COUNT_INDICES);
	    Tcl_SetObjResult(interp, Tcl_NewIntObj(value));
	} else if (found > 1) {
	    Tcl_SetObjResult(interp, objPtr);
	}
	break;

    badOption:
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"bad option \"%s\": must be -chars, -displaychars, -displayhyphens, "
		"-displayindices, -displaylines, -displaytext, -hyphens, -indices, "
		"-lines, -text, -update, -xpixels, or -ypixels", Tcl_GetString(objv[i])));
	Tcl_SetErrorCode(interp, "TK", "TEXT", "INDEX_OPTION", NULL);
	result = TCL_ERROR;
	goto done;
    }
    case TEXT_DEBUG:
	if (objc > 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "boolean");
	    result = TCL_ERROR;
	    goto done;
	}
	if (objc == 2) {
	    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(tkBTreeDebug));
	} else {
	    if (Tcl_GetBooleanFromObj(interp, objv[2], &tkBTreeDebug) != TCL_OK) {
		result = TCL_ERROR;
		goto done;
	    }
	    tkTextDebug = tkBTreeDebug;
	}
	break;
    case TEXT_DELETE: {
	int i, flags = 0;
	int ok = 1;

	for (i = 2; i < objc - 1; i++) {
	    const char *option = Tcl_GetString(objv[i]);
	    int length;

	    if (option[0] != '-') {
		break;
	    }
	    length = GetByteLength(objv[i]);
	    if (strncmp("-marks", option, length) == 0) {
		flags |= DELETE_MARKS;
	    } else if (strncmp("-inclusive", option, length) == 0) {
		flags |= DELETE_INCLUSIVE;
	    } else {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"bad option \"%s\": must be -marks, or -inclusive", Tcl_GetString(objv[i])));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "INDEX_OPTION", NULL);
		result = TCL_ERROR;
		goto done;
	    }
	}

	objv += i - 2;
	objc -= i - 2;

	if (objc < 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-marks? ?-inclusive? index1 ?index2 ...?");
	    result = TCL_ERROR;
	    goto done;
	}
	if (TestIfDisabled(interp, textPtr, &result)
		|| TestIfDead(interp, textPtr, &result)
		|| TestIfPerformingUndoRedo(interp, sharedTextPtr, &result)) {
	    goto done;
	}
	if (objc < 5) {
	    /*
	     * Simple case requires no predetermination of indices.
	     */

	    TkTextIndex index1, index2, *index2Ptr;
	    int triggerUserMod = TestIfTriggerUserMod(sharedTextPtr, objv[2]);
	    int triggerWatch = triggerUserMod || sharedTextPtr->triggerAlways;

	    if (triggerWatch) {
		TkTextSaveCursorIndex(textPtr);
	    }

	    /*
	     * Parse the starting and stopping indices.
	     */

	    if (!TkTextGetIndexFromObj(textPtr->interp, textPtr, objv[2], &index1)) {
		result = TCL_ERROR;
		goto done;
	    }
	    if (objc == 4) {
		if (!TkTextGetIndexFromObj(textPtr->interp, textPtr, objv[3], index2Ptr = &index2)) {
		    result = TCL_ERROR;
		    goto done;
		}
	    } else {
		index2Ptr = NULL;
	    }
	    ok = DeleteIndexRange(NULL, textPtr, &index1, index2Ptr, flags, 1,
		    triggerWatch, triggerWatch, triggerUserMod, 1);
	} else {
	    /*
	     * Multi-index pair case requires that we prevalidate the
	     * indices and sort from last to first so that deletes occur
	     * in the exact (unshifted) text. It also needs to handle
	     * partial and fully overlapping ranges. We have to do this
	     * with multiple passes.
	     */

	    TkTextIndex *indices, *ixStart, *ixEnd, *lastStart;
	    char *useIdx;
	    int lastUsed, i;

	    objc -= 2;
	    objv += 2;
	    indices = (TkTextIndex *)malloc((objc + 1)*sizeof(TkTextIndex));

	    /*
	     * First pass verifies that all indices are valid.
	     */

	    for (i = 0; i < objc; i++) {
		if (!TkTextGetIndexFromObj(interp, textPtr, objv[i], &indices[i])) {
		    result = TCL_ERROR;
		    free(indices);
		    goto done;
		}
	    }

	    /*
	     * Pad out the pairs evenly to make later code easier.
	     */

	    if (objc & 1) {
		indices[i] = indices[i - 1];
		TkTextIndexForwChars(textPtr, &indices[i], 1, &indices[i], COUNT_INDICES);
		objc += 1;
	    }
	    useIdx = (char *)malloc(objc);
	    memset(useIdx, 0, (unsigned) objc);

	    /*
	     * Do a decreasing order sort so that we delete the end ranges
	     * first to maintain index consistency.
	     */

	    qsort(indices, (unsigned) objc/2, 2*sizeof(TkTextIndex), TextIndexSortProc);
	    lastStart = NULL;
	    lastUsed = 0; /* otherwise GCC complains */

	    /*
	     * Second pass will handle bogus ranges (end < start) and
	     * overlapping ranges.
	     */

	    for (i = 0; i < objc; i += 2) {
		ixStart = &indices[i];
		ixEnd = &indices[i + 1];
		if (TkTextIndexCompare(ixEnd, ixStart) <= 0) {
		    continue;
		}
		if (lastStart) {
		    if (TkTextIndexCompare(ixStart, lastStart) == 0) {
			/*
			 * Start indices were equal, and the sort placed
			 * the longest range first, so skip this one.
			 */

			continue;
		    } else if (TkTextIndexCompare(lastStart, ixEnd) < 0) {
			/*
			 * The next pair has a start range before the end
			 * point of the last range. Constrain the delete
			 * range, but use the pointer values.
			 */

			*ixEnd = *lastStart;
			if (TkTextIndexCompare(ixEnd, ixStart) <= 0) {
			    continue;
			}
		    }
		}
		lastStart = ixStart;
		useIdx[i] = 1;
		lastUsed = i;
	    }

	    /*
	     * Final pass take the input from the previous and deletes the
	     * ranges which are flagged to be deleted.
	     */

	    for (i = 0; i < objc && ok; i += 2) {
		if (useIdx[i]) {
		    int triggerUserMod = TestIfTriggerUserMod(sharedTextPtr, objv[i]);
		    int triggerWatch = triggerUserMod || sharedTextPtr->triggerAlways;

		    if (triggerWatch) {
			TkTextSaveCursorIndex(textPtr);
		    }

		    /*
		     * We don't need to check the return value because all
		     * indices are preparsed above.
		     */

		    ok = DeleteIndexRange(NULL, textPtr, &indices[i], &indices[i + 1],
			    flags, 1, triggerWatch, triggerWatch, triggerUserMod, i == lastUsed);
		}
	    }
	    free(indices);
	    free(useIdx);
	}

	if (!ok) {
	    return TCL_OK; /* widget has been destroyed */
	}
	break;
    }
    case TEXT_DLINEINFO: {
	int x, y, width, height, base, argc = 2;
	int extents = 0;
	TkTextIndex index;

	if (objc == 4) {
	    const char* option = Tcl_GetString(objv[2]);

	    if (strcmp(option, "-extents") == 0) {
		extents = 1;
		argc += 1;
	    } else if (*option == '-') {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad option \"%s\": must be -extents", option));
		result = TCL_ERROR;
		goto done;
	    }
	}
	if (objc - argc + 2 != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-extents? index");
	    result = TCL_ERROR;
	    goto done;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[argc], &index)) {
	    result = TCL_ERROR;
	    goto done;
	}
	if (TkTextGetDLineInfo(textPtr, &index, extents, &x, &y, &width, &height, &base)) {
	    Tcl_Obj *listObj = Tcl_NewObj();

	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(x));
	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(y));
	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(width));
	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(height));
	    Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(base));

	    Tcl_SetObjResult(interp, listObj);
	}
	break;
    }
    case TEXT_DUMP:
	result = TextDumpCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_EDIT:
	result = TextEditCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_GET: {
	Tcl_Obj *objPtr;
	int i, found;
	int includeHyphens;
	int visibleOnly;
	unsigned countOptions;
	const char *option;

	if (objc < 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-option? ?--? index1 ?index2 ...?");
	    result = TCL_ERROR;
	    goto done;
	}

	objPtr = NULL;
	found = 0;
	includeHyphens = 1;
	visibleOnly = 0;
	countOptions = 0;
	i = 2;

	while (objc > i + 1 && (option = Tcl_GetString(objv[i]))[0] == '-') {
	    int badOption = 0;

	    i += 1;

	    if (option[1] == '-') {
	    	if (option[2] == '\0') {
		    break;
		}
		badOption = 1;
	    } else if (++countOptions > 1) {
		i -= 1;
		break;
	    } else {
		switch (option[1]) {
		case 'c':
		    if (strcmp("-chars", option) != 0) {
			badOption = 1;
		    }
		    break;
		case 't':
		    if (strcmp("-text", option) != 0) {
			badOption = 1;
		    }
		    includeHyphens = 0;
		    break;
		case 'd':
		    if (strcmp("-displaychars", option) == 0) {
			visibleOnly = 1;
		    } else if (strcmp("-displaytext", option) == 0) {
			visibleOnly = 1;
			includeHyphens = 0;
		    } else {
			badOption = 1;
		    }
		    break;
		default:
		    badOption = 1;
		    break;
		}
	    }

	    if (badOption) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad option \"%s\": "
			"must be -chars, -displaychars, -displaytext, or -text", option));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "INDEX_OPTION", NULL);
		result = TCL_ERROR;
		goto done;
	    }
	}

	for (; i < objc; i += 2) {
	    TkTextIndex index1, index2;
	    Tcl_Obj *get;

	    if (!TkTextGetIndexFromObj(interp, textPtr, objv[i], &index1)) {
		if (objPtr) {
		    Tcl_GuardedDecrRefCount(objPtr);
		}
		result = TCL_ERROR;
		goto done;
	    }

	    if (i + 1 == objc) {
		TkTextIndexForwChars(textPtr, &index1, 1, &index2, COUNT_INDICES);
	    } else {
		if (!TkTextGetIndexFromObj(interp, textPtr, objv[i + 1], &index2)) {
		    if (objPtr) {
			Tcl_GuardedDecrRefCount(objPtr);
		    }
		    result = TCL_ERROR;
		    goto done;
		}
		if (TkTextIndexCompare(&index1, &index2) >= 0) {
		    goto done;
		}
	    }

	    /*
	     * We want to move the text we get from the window into the
	     * result, but since this could in principle be a megabyte or
	     * more, we want to do it efficiently!
	     */

	    get = TextGetText(textPtr, &index1, &index2, NULL, NULL, UINT_MAX,
		    visibleOnly, includeHyphens);

	    if (++found == 1) {
		Tcl_SetObjResult(interp, get);
	    } else {
		if (found == 2) {
		    /*
		     * Move the first item we put into the result into the
		     * first element of the list object.
		     */

		    objPtr = Tcl_NewObj();
		    Tcl_ListObjAppendElement(NULL, objPtr, Tcl_GetObjResult(interp));
		}
		Tcl_ListObjAppendElement(NULL, objPtr, get);
	    }
	}
	if (found > 1) {
	    Tcl_SetObjResult(interp, objPtr);
	}
	break;
    }
    case TEXT_IMAGE:
	result = TkTextImageCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_INDEX: {
	TkTextIndex index;

	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index");
	    result = TCL_ERROR;
	    goto done;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[2], &index)) {
	    result = TCL_ERROR;
	    goto done;
	}
	Tcl_SetObjResult(interp, TkTextNewIndexObj(&index));
	break;
    }
    case TEXT_INSERT:
    case TEXT_TK_TEXTINSERT: {
	TkTextIndex index;
	int triggerUserMod, triggerWatch;

	if (objc < 4) {
	    const char *args = (commandIndex == TEXT_TK_TEXTINSERT) ?
		"?-hyphentags tags? index chars ?tagList chars tagList ...?" :
		"index chars ?tagList chars tagList ...?";
	    Tcl_WrongNumArgs(interp, 2, objv, args);
	    result = TCL_ERROR;
	    goto done;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[2], &index)) {
	    result = TCL_ERROR;
	    goto done;
	}
	if (TestIfDisabled(interp, textPtr, &result)
		|| TestIfDead(interp, textPtr, &result)
		|| TestIfPerformingUndoRedo(interp, sharedTextPtr, &result)) {
	    goto done;
	}

	triggerUserMod = TestIfTriggerUserMod(sharedTextPtr, objv[2]);
	triggerWatch = triggerUserMod || sharedTextPtr->triggerAlways;

	if (triggerWatch) {
	    TkTextSaveCursorIndex(textPtr);
	}
	result = TextInsertCmd(textPtr, interp, objc - 3, objv + 3, &index, 1, triggerWatch,
		triggerWatch, triggerUserMod, commandIndex == TEXT_TK_TEXTINSERT);
	break;
    }
    case TEXT_INSPECT:
	result = TextInspectCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_ISCLEAN: {
	int discardSelection = 0;
	const TkText *myTextPtr = textPtr;
	int i;

	for (i = 2; i < objc; ++i) {
	    char const * opt = Tcl_GetString(objv[i]);

	    if (strcmp(opt, "-overall") == 0) {
		myTextPtr = NULL;
	    } else if (strcmp(opt, "-discardselection") == 0) {
		discardSelection = 1;
	    } else {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad option \"%s\": must be -overall", opt));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "BAD_OPTION", NULL);
		result = TCL_ERROR;
		goto done;
	    }
	}

	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(IsClean(sharedTextPtr, myTextPtr, discardSelection)));
	break;
    }
    case TEXT_ISDEAD:
    	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(TkTextIsDeadPeer(textPtr)));
	break;
    case TEXT_ISEMPTY: {
	int overall = 0;
	int i;

	for (i = 2; i < objc; ++i) {
	    char const * opt = Tcl_GetString(objv[i]);

	    if (strcmp(opt, "-overall") == 0) {
		overall = 1;
	    } else {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad option \"%s\": must be -overall", opt));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "BAD_OPTION", NULL);
		result = TCL_ERROR;
		goto done;
	    }
	}

	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(IsEmpty(sharedTextPtr, overall ? NULL : textPtr)));
	break;
    }
    case TEXT_LINENO: {
	TkTextIndex index;
	int lineno;

	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index");
	    result = TCL_ERROR;
	    goto done;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[2], &index)) {
	    result = TCL_ERROR;
	    goto done;
	}
	lineno = TkTextIsDeadPeer(textPtr) ? 0 : TkTextIndexGetLineNumber(&index, textPtr) + 1;
	Tcl_SetObjResult(interp, Tcl_NewIntObj(lineno));
	break;
    }
    case TEXT_LOAD: {
	Tcl_Obj *contentObjPtr;
	int validOptions = 0;

	if (objc != 3 && objc != 4) {
	    Tcl_WrongNumArgs(interp, 2, objv, "textcontent");
	    result = TCL_ERROR;
	    goto done;
	}
	if (objc == 4) {
	    const char *opt = Tcl_GetString(objv[2]);

	    if (strcmp(opt, "-validconfig") != 0) {
		Tcl_SetObjResult(interp,
			Tcl_ObjPrintf("bad option \"%s\": must be -validconfig", opt));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "BAD_OPTION", NULL);
		result = TCL_ERROR;
		goto done;
	    }
	    validOptions = 1;
	    contentObjPtr = objv[3];
	} else {
	    contentObjPtr = objv[2];
	}
	if (TestIfPerformingUndoRedo(interp, sharedTextPtr, &result)) {
	    goto done;
	}
	ClearText(textPtr, 0);
	TkTextRelayoutWindow(textPtr, TK_TEXT_LINE_GEOMETRY);
	if ((result = TkBTreeLoad(textPtr, contentObjPtr, validOptions)) != TCL_OK) {
	    ClearText(textPtr, 0);
	}
	break;
    }
    case TEXT_MARK:
	result = TkTextMarkCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_PEER:
	result = TextPeerCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_PENDINGSYNC: {
        if (objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, NULL);
            result = TCL_ERROR;
            goto done;
        }
	if (!sharedTextPtr->allowUpdateLineMetrics) {
	    ProcessConfigureNotify(textPtr, 1);
	}
	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(TkTextPendingSync(textPtr)));
        break;
    }
    case TEXT_REPLACE:
    case TEXT_TK_TEXTREPLACE: {
	TkTextIndex indexFrom, indexTo, index;
	int triggerUserMod, triggerWatch;

	if (objc < 5) {
	    Tcl_WrongNumArgs(interp, 2, objv, "index1 index2 chars ?tagList chars tagList ...?");
	    result = TCL_ERROR;
	    goto done;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[2], &indexFrom)
		|| !TkTextGetIndexFromObj(interp, textPtr, objv[3], &indexTo)) {
	    result = TCL_ERROR;
	    goto done;
	}
	if (TkTextIndexCompare(&indexFrom, &indexTo) > 0) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "index \"%s\" before \"%s\" in the text",
		    Tcl_GetString(objv[3]), Tcl_GetString(objv[2])));
	    Tcl_SetErrorCode(interp, "TK", "TEXT", "INDEX_ORDER", NULL);
	    result = TCL_ERROR;
	    goto done;
	}
	if (TestIfDisabled(interp, textPtr, &result) || TestIfDead(interp, textPtr, &result)) {
	    goto done;
	}

	triggerUserMod = TestIfTriggerUserMod(sharedTextPtr, objv[2]);
	triggerWatch = triggerUserMod || sharedTextPtr->triggerAlways;

	/*
	 * The 'replace' operation is quite complex to do correctly,
	 * because we want a number of criteria to hold:
	 *
	 * 1.  The insertion point shouldn't move, unless it is within the
	 *	   deleted range. In this case it should end up after the new
	 *	   text.
	 *
	 * 2.  The window should not change the text it shows - should not
	 *	   scroll vertically - unless the result of the replace is
	 *	   that the insertion position which used to be on-screen is
	 *	   now off-screen.
	 */

	TkTextIndexSave(&textPtr->topIndex);
	if (triggerWatch) {
	    TkTextSaveCursorIndex(textPtr);
	}

	TkTextMarkSegToIndex(textPtr, textPtr->insertMarkPtr, &index);

	if (TkTextIndexCompare(&indexFrom, &index) < 0 && TkTextIndexCompare(&index, &indexTo) <= 0) {
	    /*
	     * The insertion point is inside the range to be replaced, so
	     * we have to do some calculations to ensure it doesn't move
	     * unnecessarily.
	     */

	    int deleteInsertOffset, insertLength, j;

	    insertLength = 0;
	    for (j = 4; j < objc; j += 2) {
		insertLength += Tcl_GetCharLength(objv[j]);
	    }

	    /*
	     * Calculate 'deleteInsertOffset' as an offset we will apply
	     * to the insertion point after this operation.
	     */

	    deleteInsertOffset = CountIndices(textPtr, &indexFrom, &index, COUNT_CHARS);
	    if (deleteInsertOffset > insertLength) {
		deleteInsertOffset = insertLength;
	    }

	    result = TextReplaceCmd(textPtr, interp, &indexFrom, &indexTo, objc, objv, 0,
		    triggerWatch, triggerUserMod, commandIndex == TEXT_TK_TEXTREPLACE);
	    if (textPtr->flags & DESTROYED) {
		return result;
	    }

	    if (result == TCL_OK) {
		/*
		 * Move the insertion position to the correct place.
		 */

		TkTextIndexForwChars(textPtr, &indexFrom, deleteInsertOffset, &index, COUNT_INDICES);
		TkBTreeUnlinkSegment(sharedTextPtr, textPtr->insertMarkPtr);
		TkBTreeLinkSegment(sharedTextPtr, textPtr->insertMarkPtr, &index);
		textPtr->insertIndex = index;
	    }
	} else {
	    result = TextReplaceCmd(textPtr, interp, &indexFrom, &indexTo, objc, objv, 0,
		    triggerWatch, triggerUserMod, commandIndex == TEXT_TK_TEXTREPLACE);
	    if (textPtr->flags & DESTROYED) {
		return result;
	    }
	}
	if (result == TCL_OK) {
	    /*
	     * Now ensure the top-line is in the right place.
	     */

	    if (!TkTextIndexRebuild(&textPtr->topIndex)) {
		TkTextSetYView(textPtr, &textPtr->topIndex, TK_TEXT_NOPIXELADJUST);
	    }
	}
	break;
    }
    case TEXT_SCAN:
	result = TkTextScanCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_SEARCH:
	result = TextSearchCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_SEE:
	result = TkTextSeeCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_SYNC: {
	int wrongNumberOfArgs = 0;

	if (objc == 3 || objc == 4) {
	    const char *option = Tcl_GetString(objv[2]);
	    if (*option != '-') {
		wrongNumberOfArgs = 1;
	    } else if (strncmp(option, "-command", objv[2]->length) != 0) {
		Tcl_AppendResult(interp, "wrong option \"", option,
			"\": should be \"-command\"", NULL);
		result = TCL_ERROR;
		goto done;
	    }
	} else if (objc != 2) {
	    wrongNumberOfArgs = 1;
	}
	if (wrongNumberOfArgs) {
	    Tcl_WrongNumArgs(interp, 2, objv, "?-command ?command??");
	    result = TCL_ERROR;
	    goto done;
	}
	if (!sharedTextPtr->allowUpdateLineMetrics) {
	    ProcessConfigureNotify(textPtr, 1);
	}
	if (objc == 3) {
	    if (textPtr->afterSyncCmd) {
		Tcl_SetObjResult(interp, textPtr->afterSyncCmd);
	    }
	} else if (objc == 4) {
	    Tcl_Obj *cmd = objv[3];
	    const char *script = Tcl_GetString(cmd);
	    int append = 0;

	    if (*script == '+') {
		script += 1;
		append = 1;
	    }

	    if (!textPtr->afterSyncCmd) {
		if (append) {
		    cmd = Tcl_NewStringObj(script, -1);
		}
		Tcl_IncrRefCount(textPtr->afterSyncCmd = cmd);
	    } else {
		if (!append && *script == '\0') {
		    if (textPtr->pendingAfterSync) {
			Tcl_CancelIdleCall(RunAfterSyncCmd, (ClientData) textPtr);
			textPtr->pendingAfterSync = 0;
		    }
		    cmd = NULL;
		} else {
		    if (append) {
			cmd = AppendScript(Tcl_GetString(textPtr->afterSyncCmd), script);
		    }
		    Tcl_IncrRefCount(cmd);
		}
		Tcl_GuardedDecrRefCount(textPtr->afterSyncCmd);
		textPtr->afterSyncCmd = cmd;
	    }
	    if (!textPtr->pendingAfterSync) {
		textPtr->pendingAfterSync = 1;
		if (!TkTextPendingSync(textPtr)) {
		    Tcl_DoWhenIdle(RunAfterSyncCmd, (ClientData) textPtr);
		}
	    }
	} else {
	    textPtr->sendSyncEvent = 1;

	    if (!TkTextPendingSync(textPtr)) {
		/*
		 * There is nothing to sync, so fire the <<WidgetViewSync>> event,
		 * because nobody else will do this when no update is pending.
		 */
		TkTextGenerateWidgetViewSyncEvent(textPtr, 0);
	    } else {
		UpdateLineMetrics(textPtr, 0, TkrBTreeNumLines(sharedTextPtr->tree, textPtr));
	    }
	}
	break;
    }
    case TEXT_TAG:
	result = TkTextTagCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_WATCH: {
	Tcl_Obj *cmd = textPtr->watchCmd;

	result = TextWatchCmd(textPtr, interp, objc, objv);
	if (cmd) {
	    Tcl_SetObjResult(interp, cmd);
	    Tcl_GuardedDecrRefCount(cmd);
	}
    	break;
    }
    case TEXT_WINDOW:
	result = TkTextWindowCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_XVIEW:
	result = TkrTextXviewCmd(textPtr, interp, objc, objv);
	break;
    case TEXT_YVIEW:
	result = TkTextYviewCmd(textPtr, interp, objc, objv);
	break;
    }

  done:
    if (--textPtr->refCount == 0) {
	int sharedIsReleased = textPtr->sharedIsReleased;

	assert(textPtr->flags & MEM_RELEASED);
	free(textPtr);
	DEBUG_ALLOC(tkTextCountDestroyPeer++);
	if (sharedIsReleased) {
	    return result;
	}
	textPtr = NULL;
    } else if (textPtr->watchCmd) {
	TkTextTriggerWatchCursor(textPtr);
    }
    if (sharedTextPtr->undoStackEvent) {
	TriggerUndoStackEvent(sharedTextPtr);
    }
    sharedTextPtr->undoStackEvent = oldUndoStackEvent;

    if (textPtr && textPtr->syncTime == 0) {
	UpdateLineMetrics(textPtr, 0, TkrBTreeNumLines(sharedTextPtr->tree, textPtr));
	TK_BTREE_DEBUG(TkBTreeCheck(sharedTextPtr->tree));
    }

    return result;
}

/*
 *--------------------------------------------------------------
 *
 * IsEmpty --
 *
 *	Test whether this widget is empty. The widget is empty
 *	if it contains exact two single newline characters.
 *
 * Results:
 *	Returns 1 if the widget is empty, and false otherwise.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
DoesNotContainTextSegments(
    const TkTextSegment *segPtr1,
    const TkTextSegment *segPtr2)
{
    for ( ; segPtr1 != segPtr2; segPtr1 = segPtr1->nextPtr) {
	if (segPtr1->size > 0) {
	    return !segPtr1->nextPtr; /* ignore trailing newline */
	}
    }

    return 1;
}

static int
IsEmpty(
    const TkSharedText *sharedTextPtr,
    const TkText *textPtr)		/* Can be NULL. */
{
    TkTextSegment *startMarker;
    TkTextSegment *endMarker;

    assert(sharedTextPtr);

    if (TkrBTreeNumLines(sharedTextPtr->tree, textPtr) > 1) {
	return 0;
    }

    if (textPtr) {
	startMarker = textPtr->startMarker;
	endMarker = textPtr->endMarker;
    } else {
	startMarker = sharedTextPtr->startMarker;
	endMarker = sharedTextPtr->endMarker;
    }

    return DoesNotContainTextSegments(startMarker, endMarker);
}

/*
 *--------------------------------------------------------------
 *
 * IsClean --
 *
 *	Test whether this widget is clean. The widget is clean
 *	if it is empty, if no mark is set, and if the solely
 *	newline of this widget is untagged.
 *
 * Results:
 *	Returns true if the widget is clean, and false otherwise.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
ContainsAnySegment(
    const TkTextSegment *segPtr1,
    const TkTextSegment *segPtr2)
{
    for ( ; segPtr1 != segPtr2; segPtr1 = segPtr1->nextPtr) {
	if (segPtr1->size > 0 || segPtr1->normalMarkFlag) {
	    return !!segPtr1->nextPtr; /* ignore trailing newline */
	}
    }

    return 0;
}

static int
IsClean(
    const TkSharedText *sharedTextPtr,
    const TkText *textPtr,		/* Can be NULL. */
    int discardSelection)
{
    const TkTextTagSet *tagInfoPtr;
    const TkTextSegment *startMarker;
    const TkTextSegment *endMarker;
    const TkTextLine *endLine;

    assert(sharedTextPtr);

    if (TkrBTreeNumLines(sharedTextPtr->tree, textPtr) > 1) {
	return 0;
    }

    if (textPtr) {
	startMarker = textPtr->startMarker;
	endMarker = textPtr->endMarker;
    } else {
	startMarker = sharedTextPtr->startMarker;
	endMarker = sharedTextPtr->endMarker;
    }

    if (ContainsAnySegment(startMarker, endMarker)) {
	return 0;
    }

    endLine = endMarker->sectionPtr->linePtr;

    if (!textPtr && ContainsAnySegment(endLine->segPtr, NULL)) {
	/* This widget contains any mark on very last line. */
	return 0;
    }

    tagInfoPtr = endLine->prevPtr->lastPtr->tagInfoPtr;

    return discardSelection ?
	    TkTextTagBitContainsSet(sharedTextPtr->selectionTags, tagInfoPtr) :
	    tagInfoPtr == sharedTextPtr->emptyTagInfoPtr;
}

/*
 *--------------------------------------------------------------
 *
 * TkTextTestRelation --
 *
 *	Given a relation (>0 for greater, =0 for equal, and <0 for
 *	less), this function computes whether the given operator
 *	satisfies this relation.
 *
 * Results:
 *	Returns 1 if the relation will be satsified, 0 if it will
 *	not be satisifed, and -1 if the operator is invalid.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
BadComparisonOperator(
    Tcl_Interp *interp,
    char const *op)
{
    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
	    "bad comparison operator \"%s\": must be <, <=, ==, >=, >, or !=", op));
    Tcl_SetErrorCode(interp, "TK", "VALUE", "COMPARISON", NULL);
    return -1;
}

int
TkTextTestRelation(
    Tcl_Interp *interp,		/* Current interpreter. */
    int relation,		/* Test this relation... */
    char const *op)		/* ...whether it will be satisifed by this operator. */
{
    int value;

    if (op[0] == '<') {
	value = (relation < 0);
	if (op[1] == '=' && op[2] == 0) {
	    value = (relation <= 0);
	} else if (op[1] != 0) {
	    return BadComparisonOperator(interp, op);
	}
    } else if (op[0] == '>') {
	value = (relation > 0);
	if (op[1] == '=' && op[2] == 0) {
	    value = (relation >= 0);
	} else if (op[1] != 0) {
	    return BadComparisonOperator(interp, op);
	}
    } else if (op[0] == '=' && op[1] == '=' && op[2] == 0) {
	value = (relation == 0);
    } else if (op[0] == '!' && op[1] == '=' && op[2] == 0) {
	value = (relation != 0);
    } else {
	return BadComparisonOperator(interp, op);
    }

    return value;
}

/*
 *--------------------------------------------------------------
 *
 * TextWatchCmd --
 *
 *	This function is invoked to process the "text watch" Tcl command. See
 *	the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

static int
TextWatchCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    TkSharedText *sharedTextPtr;

    if (objc > 4) {
	/* NOTE: avoid trigraph "??-" in string. */
	Tcl_WrongNumArgs(interp, 4, objv, "\?\?-always? commandPrefix?");
	return TCL_ERROR;
    }

    sharedTextPtr = textPtr->sharedTextPtr;

    if (objc <= 2) {
	TkText *tPtr;

	if (textPtr->watchCmd) {
	    textPtr->triggerAlways = 0;
	    textPtr->watchCmd = NULL;
	}

	sharedTextPtr->triggerWatchCmd = 0; /* do not trigger recursively */
	sharedTextPtr->triggerAlways = 0;

	for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	    if (tPtr->watchCmd) {
		sharedTextPtr->triggerWatchCmd = 1;
		if (tPtr->triggerAlways) {
		    sharedTextPtr->triggerAlways = 1;
		}
	    }
	}
    } else {
	const char *script;
	Tcl_Obj *cmd;
	int argnum = 2;

	if (objc == 4) {
	    if (strcmp(Tcl_GetString(objv[2]), "-always") != 0) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"bad option \"%s\": must be -always", Tcl_GetString(objv[2])));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "WATCH_OPTION", NULL);
		return TCL_ERROR;
	    }
	    textPtr->triggerAlways = 1;
	    textPtr->sharedTextPtr->triggerAlways = 1;
	    argnum = 3;
	}

	cmd = objv[argnum];
	script = Tcl_GetString(cmd);

	if (*script == '+') {
	    script += 1;
	    if (textPtr->watchCmd) {
		cmd = AppendScript(Tcl_GetString(textPtr->watchCmd), script);
	    } else {
		cmd = Tcl_NewStringObj(script, -1);
	    }
	} else if (argnum == 2) {
	    TkText *tPtr;

	    textPtr->triggerAlways = 0;
	    textPtr->sharedTextPtr->triggerAlways = 0;

	    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
		if (tPtr->triggerAlways) {
		    assert(tPtr->watchCmd);
		    sharedTextPtr->triggerWatchCmd = 1;
		}
	    }
	}

	textPtr->sharedTextPtr->triggerWatchCmd = 1;
	Tcl_IncrRefCount(textPtr->watchCmd = cmd);
    }

    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TextPeerCmd --
 *
 *	This function is invoked to process the "text peer" Tcl command. See
 *	the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

static int
TextPeerCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    Tk_Window tkwin = textPtr->tkwin;
    int index;

    static const char *const peerOptionStrings[] = { "create", "names", NULL };
    enum peerOptions { PEER_CREATE, PEER_NAMES };

    if (objc < 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "option ?arg ...?");
	return TCL_ERROR;
    }
    if (Tcl_GetIndexFromObjStruct(interp, objv[2], peerOptionStrings,
	    sizeof(char *), "peer option", 0, &index) != TCL_OK) {
	return TCL_ERROR;
    }

    switch ((enum peerOptions) index) {
    case PEER_CREATE:
	if (objc < 4) {
	    Tcl_WrongNumArgs(interp, 3, objv, "pathName ?-option value ...?");
	    return TCL_ERROR;
	}
	return CreateWidget(textPtr->sharedTextPtr, tkwin, interp, textPtr, objc - 2, objv + 2);
    case PEER_NAMES: {
	TkText *tPtr = textPtr->sharedTextPtr->peers;
	Tcl_Obj *peersObj;

	if (objc > 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, NULL);
	    return TCL_ERROR;
	}
	peersObj = Tcl_NewObj();
	while (tPtr) {
	    if (tPtr != textPtr) {
		Tcl_ListObjAppendElement(NULL, peersObj, Tk_NewWindowObj(tPtr->tkwin));
	    }
	    tPtr = tPtr->next;
	}
	Tcl_SetObjResult(interp, peersObj);
    }
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * PushUndoSeparatorIfNeeded --
 *
 *	Push undo separator if needed.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May push a separator onto undo stack.
 *
 *----------------------------------------------------------------------
 */

static void
PushUndoSeparatorIfNeeded(
    TkSharedText *sharedTextPtr,
    int autoSeparators,
    TkTextEditMode currentEditMode)
{
    assert(sharedTextPtr->undoStack);

    if (sharedTextPtr->pushSeparator
	    || (autoSeparators && sharedTextPtr->lastEditMode != currentEditMode)) {
	PushRetainedUndoTokens(sharedTextPtr);
	TkTextUndoPushSeparator(sharedTextPtr->undoStack, 1);
	sharedTextPtr->pushSeparator = 0;
	sharedTextPtr->lastUndoTokenType = -1;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextReplaceCmd --
 *
 *	This function is invoked to process part of the "replace" widget
 *	command for text widgets.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *	If 'viewUpdate' is false, then textPtr->topIndex may no longer be a
 *	valid index after this function returns. The caller is responsible for
 *	ensuring a correct index is in place.
 *
 *----------------------------------------------------------------------
 */

static int
TextReplaceCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    const TkTextIndex *indexFromPtr,
				/* Index from which to replace. */
    const TkTextIndex *indexToPtr,
				/* Index to which to replace. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[],	/* Argument objects. */
    int viewUpdate,		/* Update vertical view if set. */
    int triggerWatch,		/* Should we trigger the watch command? */
    int userFlag,		/* Trigger due to user modification? */
    int parseHyphens)		/* Should we parse hyphens (tk_textReplace)? */
{
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    int origAutoSep = sharedTextPtr->autoSeparators;
    int result = TCL_OK;
    TkTextIndex indexTmp;
    int notDestroyed;

    assert(!TkTextIsDeadPeer(textPtr));

    textPtr->refCount += 1;

    /*
     * Perform the deletion and insertion, but ensure no undo-separator is
     * placed between the two operations. Since we are using the helper
     * functions 'DeleteIndexRange' and 'TextInsertCmd' we have to pretend
     * that the autoSeparators setting is off, so that we don't get an
     * undo-separator between the delete and insert.
     */

    if (sharedTextPtr->undoStack) {
	sharedTextPtr->autoSeparators = 0;
	PushUndoSeparatorIfNeeded(sharedTextPtr, origAutoSep, TK_TEXT_EDIT_REPLACE);
    }

    /* The line and segment storage may change when deleting. */
    indexTmp = *indexFromPtr;
    TkTextIndexSave(&indexTmp);

    notDestroyed = DeleteIndexRange(NULL, textPtr, indexFromPtr, indexToPtr,
	    0, viewUpdate, triggerWatch, 0, userFlag, 1);

    if (notDestroyed) {
	TkTextIndexRebuild(&indexTmp);
	result = TextInsertCmd(textPtr, interp, objc - 4, objv + 4, &indexTmp,
		viewUpdate, 0, triggerWatch, userFlag, parseHyphens);
    }

    if (sharedTextPtr->undoStack) {
	sharedTextPtr->lastEditMode = TK_TEXT_EDIT_REPLACE;
	sharedTextPtr->autoSeparators = origAutoSep;
    }

    TkTextDecrRefCountAndTestIfDestroyed(textPtr);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TextIndexSortProc --
 *
 *	This function is called by qsort when sorting an array of indices in
 *	*decreasing* order (last to first).
 *
 * Results:
 *	The return value is less than zero if the first argument should be before
 *	the second element, 0 if it's equivalent, and greater than zero if it should
 *	be after the second element.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
TextIndexSortProc(
    const void *first,		/* Elements to be compared. */
    const void *second)
{
    TkTextIndex *pair1 = (TkTextIndex *) first;
    TkTextIndex *pair2 = (TkTextIndex *) second;
    int cmp = TkTextIndexCompare(&pair1[1], &pair2[1]);

    if (cmp == 0) {
	/*
	 * If the first indices were equal, we want the second index of the
	 * pair also to be the greater. Use pointer magic to access the second
	 * index pair.
	 */

	cmp = TkTextIndexCompare(&pair1[0], &pair2[0]);
    }

    return -cmp;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeEmbeddedWindows --
 *
 *	Free up any embedded windows which belong to this widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	All embedded windows of this widget will be freed.
 *
 *----------------------------------------------------------------------
 */

static void
FreeEmbeddedWindows(
    TkText *textPtr)	/* The concerned text widget. */
{
    Tcl_HashSearch search;
    Tcl_HashEntry *hPtr;
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;

    for (hPtr = Tcl_FirstHashEntry(&sharedTextPtr->windowTable, &search);
	    hPtr;
	    hPtr = Tcl_NextHashEntry(&search)) {
	TkTextSegment *ewPtr = (TkTextSegment *)Tcl_GetHashValue(hPtr);
	TkTextEmbWindowClient *client = ewPtr->body.ew.clients;
	TkTextEmbWindowClient **prev = &ewPtr->body.ew.clients;

	while (client) {
	    TkTextEmbWindowClient *next = client->next;
	    if (client->textPtr == textPtr && client->hPtr == hPtr) {
		TkTextWinFreeClient(hPtr, client);
		*prev = next;
	    } else {
		prev = &client->next;
	    }
	    client = next;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ClearText --
 *
 *	This function is invoked when we reset a text widget to it's intitial
 *	state, but without resetting options. We will free up many of the
 *	internal structure.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Almost everything associated with the text content is cleared.
 *	Note that all the peers of the shared structure will be cleared.
 *
 *----------------------------------------------------------------------
 */

static void
ClearRetainedUndoTokens(
    TkSharedText *sharedTextPtr)
{
    unsigned i;

    assert(sharedTextPtr);

    for (i = 0; i < sharedTextPtr->undoTagListCount; ++i) {
	TkTextReleaseUndoTagToken(sharedTextPtr, sharedTextPtr->undoTagList[i]);
    }

    for (i = 0; i < sharedTextPtr->undoMarkListCount; ++i) {
	TkTextReleaseUndoMarkTokens(sharedTextPtr, &sharedTextPtr->undoMarkList[i]);
    }

    sharedTextPtr->undoTagListCount = 0;
    sharedTextPtr->undoMarkListCount = 0;
}

static void
ClearText(
    TkText *textPtr,		/* Clean up this text widget. */
    int clearTags)		/* Also clear all tags? */
{
    TkTextSegment *retainedMarks;
    TkTextIndex startIndex;
    TkText *tPtr;
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    TkSizeT oldEpoch = TkBTreeEpoch(sharedTextPtr->tree);
    int steadyMarks = textPtr->sharedTextPtr->steadyMarks;
    int debug = tkBTreeDebug;

    tkBTreeDebug = 0; /* debugging is not wanted here */

    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	/*
	 * Always clean up the widget-specific tags first. Common tags (i.e. most)
	 * will only be cleaned up when the shared structure is cleaned up.
	 *
	 * We also need to clean up widget-specific marks ('insert', 'current'),
	 * since otherwise marks will never disappear from the B-tree.
	 *
	 * Do not clear the after sync commands, otherwise the widget may hang.
	 */

	tPtr->refCount += 1;
	TkBTreeUnlinkSegment(sharedTextPtr, tPtr->insertMarkPtr);
	TkBTreeUnlinkSegment(sharedTextPtr, tPtr->currentMarkPtr);
	if (clearTags) {
	    TkTextFreeAllTags(tPtr);
	}
	FreeEmbeddedWindows(tPtr);
	TkTextFreeDInfo(tPtr);
	textPtr->dInfoPtr = NULL;
	textPtr->dontRepick = 0;
	tPtr->abortSelections = 1;
	textPtr->lastLineY = TK_TEXT_NEARBY_IS_UNDETERMINED;
	tPtr->refCount -= 1;
	tPtr->startLine = NULL;
	tPtr->endLine = NULL;

	if (tPtr->startMarker->refCount == 1) {
	    assert(textPtr->startMarker != textPtr->sharedTextPtr->startMarker);
	    TkBTreeUnlinkSegment(sharedTextPtr, tPtr->startMarker);
	    FREE_SEGMENT(tPtr->startMarker);
	    DEBUG_ALLOC(tkTextCountDestroySegment++);
	    (tPtr->startMarker = sharedTextPtr->startMarker)->refCount += 1;
	}
	if (tPtr->endMarker->refCount == 1) {
	    assert(textPtr->endMarker != textPtr->sharedTextPtr->endMarker);
	    TkBTreeUnlinkSegment(sharedTextPtr, tPtr->endMarker);
	    FREE_SEGMENT(tPtr->endMarker);
	    DEBUG_ALLOC(tkTextCountDestroySegment++);
	    (tPtr->endMarker = sharedTextPtr->endMarker)->refCount += 1;
	}
    }

    ClearRetainedUndoTokens(sharedTextPtr);
    TkBTreeUnlinkSegment(sharedTextPtr, sharedTextPtr->startMarker);
    TkBTreeUnlinkSegment(sharedTextPtr, sharedTextPtr->endMarker);
    sharedTextPtr->startMarker->nextPtr = sharedTextPtr->startMarker->prevPtr = NULL;
    sharedTextPtr->endMarker->nextPtr = sharedTextPtr->endMarker->prevPtr = NULL;
    TkBTreeDestroy(sharedTextPtr->tree);
    retainedMarks = TkTextFreeMarks(sharedTextPtr, 1);
    Tcl_DeleteHashTable(&sharedTextPtr->imageTable);
    Tcl_DeleteHashTable(&sharedTextPtr->windowTable);

    if (clearTags) {
	Tcl_DeleteHashTable(&sharedTextPtr->tagTable);
	if (sharedTextPtr->tagBindingTable) {
	    Tk_DeleteBindingTable(sharedTextPtr->tagBindingTable);
	}
	sharedTextPtr->numMotionEventBindings = 0;
	sharedTextPtr->numElisionTags = 0;
    }

    /*
     * Rebuild the internal structures.
     */

    Tcl_InitHashTable(&sharedTextPtr->windowTable, TCL_STRING_KEYS);
    Tcl_InitHashTable(&sharedTextPtr->imageTable, TCL_STRING_KEYS);
    TkTextUndoResetStack(sharedTextPtr->undoStack);
    TkBitClear(sharedTextPtr->elisionTags);
    TkBitClear(sharedTextPtr->selectionTags);
    TkBitClear(sharedTextPtr->dontUndoTags);
    TkBitClear(sharedTextPtr->affectDisplayTags);
    TkBitClear(sharedTextPtr->notAffectDisplayTags);
    TkBitClear(sharedTextPtr->affectDisplayNonSelTags);
    TkBitClear(sharedTextPtr->affectGeometryTags);
    TkBitClear(sharedTextPtr->affectGeometryNonSelTags);
    TkBitClear(sharedTextPtr->affectLineHeightTags);
    sharedTextPtr->isAltered = 0;
    sharedTextPtr->isModified = 0;
    sharedTextPtr->isIrreversible = 0;
    sharedTextPtr->userHasSetModifiedFlag = 0;
    sharedTextPtr->haveToSetCurrentMark = 0;
    sharedTextPtr->undoLevel = 0;
    sharedTextPtr->pushSeparator = 0;
    sharedTextPtr->imageCount = 0;
    sharedTextPtr->tree = TkBTreeCreate(sharedTextPtr, oldEpoch + 1);
    sharedTextPtr->insertDeleteUndoTokenCount = 0;

    if (clearTags) {
	sharedTextPtr->tagInfoSize = 0;
	sharedTextPtr->tagBindingTable = NULL;
	sharedTextPtr->numTags = 0;
	sharedTextPtr->numEnabledTags = sharedTextPtr->numPeers; /* because the "sel" tag will survive */
	Tcl_InitHashTable(&sharedTextPtr->tagTable, TCL_STRING_KEYS);
	TkBitClear(sharedTextPtr->usedTags);
	DEBUG(memset(sharedTextPtr->tagLookup, 0,
		TkBitSize(sharedTextPtr->usedTags)*sizeof(TkTextTag *)));
    }

    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	TkTextCreateDInfo(tPtr);
	TkBTreeAddClient(sharedTextPtr->tree, tPtr, tPtr->lineHeight);
	TkTextIndexSetupToStartOfText(&startIndex, tPtr, sharedTextPtr->tree);
	TkTextSetYView(tPtr, &startIndex, 0);
	sharedTextPtr->tagLookup[tPtr->selTagPtr->index] = tPtr->selTagPtr;
	TkBitSet(sharedTextPtr->usedTags, tPtr->selTagPtr->index);
	tPtr->haveToSetCurrentMark = 0;
	TkBTreeLinkSegment(sharedTextPtr, tPtr->insertMarkPtr, &startIndex);
	TkBTreeLinkSegment(sharedTextPtr, tPtr->currentMarkPtr, &startIndex);
	tPtr->currentMarkIndex = startIndex;
    }

    sharedTextPtr->steadyMarks = 0;
    while (retainedMarks) {
	TkTextSegment *nextPtr = retainedMarks->nextPtr;
	TkTextIndexSetupToStartOfText(&startIndex, NULL, sharedTextPtr->tree);
	TkBTreeLinkSegment(sharedTextPtr, retainedMarks, &startIndex);
	retainedMarks = nextPtr;
    }
    sharedTextPtr->steadyMarks = steadyMarks;

    TkTextResetDInfo(textPtr);
    sharedTextPtr->lastEditMode = TK_TEXT_EDIT_OTHER;
    sharedTextPtr->lastUndoTokenType = -1;

    if (debug) {
	tkBTreeDebug = 1;
	TkBTreeCheck(sharedTextPtr->tree);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyText --
 *
 *	This function is invoked when we receive a destroy event to clean up
 *	the internal structure of a text widget. We will free up most of the
 *	internal structure and delete the associated Tcl command. If there are
 *	no outstanding references to the widget, we also free up the textPtr
 *	itself.
 *
 *	The widget has already been flagged as deleted.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Either everything or almost everything associated with the text is
 *	freed up.
 *
 *----------------------------------------------------------------------
 */

static void
DestroyText(
    TkText *textPtr)		/* Info about text widget. */
{
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    TkTextStringList *listPtr;
    int debug = tkBTreeDebug;

    tkBTreeDebug = 0; /* debugging is not wanted here */

    /*
     * Firstly, remove pending idle commands, and free the array.
     */

    if (textPtr->pendingAfterSync) {
	Tcl_CancelIdleCall(RunAfterSyncCmd, (ClientData) textPtr);
	textPtr->pendingAfterSync = 0;
    }
    if (textPtr->pendingFireEvent) {
	Tcl_CancelIdleCall(FireWidgetViewSyncEvent, (ClientData) textPtr);
	textPtr->pendingFireEvent = 0;
    }
    if (textPtr->afterSyncCmd) {
	Tcl_GuardedDecrRefCount(textPtr->afterSyncCmd);
    }

    /*
     * Free up all the stuff that requires special handling. We have already
     * called let Tk_FreeConfigOptions to handle all the standard
     * option-related stuff (and so none of that exists when we are called).
     *
     * Special note: free up display-related information before deleting the
     * B-tree, since display-related stuff may refer to stuff in the B-tree.
     */

    TkTextFreeDInfo(textPtr);
    textPtr->dInfoPtr = NULL;
    textPtr->undo = 0;

    /*
     * Always clean up the widget-specific tags first. Common tags (i.e. most)
     * will only be cleaned up when the shared structure is cleaned up.
     *
     * Firstly unset all the variables bound to this widget.
     */

    listPtr = textPtr->varBindingList;
    while (listPtr) {
	TkTextStringList *nextPtr = listPtr->nextPtr;

	Tcl_UnsetVar2(textPtr->interp, Tcl_GetString(listPtr->strObjPtr), NULL, TCL_GLOBAL_ONLY);
	Tcl_GuardedDecrRefCount(listPtr->strObjPtr);
	free(listPtr);
	listPtr = nextPtr;
    }

    /*
     * Unset the watch command.
     */

    if (textPtr->watchCmd) {
	Tcl_GuardedDecrRefCount(textPtr->watchCmd);
    }
    TextWatchCmd(textPtr, NULL, 0, NULL);

    /*
     * We also need to clean up widget-specific marks ('insert', 'current'),
     * since otherwise marks will never disappear from the B-tree.
     */

    TkTextDeleteTag(textPtr, textPtr->selTagPtr, NULL);
    TkBTreeUnlinkSegment(sharedTextPtr, textPtr->insertMarkPtr);
    FREE_SEGMENT(textPtr->insertMarkPtr);
    DEBUG_ALLOC(tkTextCountDestroySegment++);
    TkBTreeUnlinkSegment(sharedTextPtr, textPtr->currentMarkPtr);
    FREE_SEGMENT(textPtr->currentMarkPtr);
    DEBUG_ALLOC(tkTextCountDestroySegment++);
    FreeEmbeddedWindows(textPtr);

    /*
     * Clean up the -start/-end markers, do this after cleanup of other segments (not before).
     */

    if (textPtr->startMarker->refCount == 1) {
	assert(textPtr->startMarker != sharedTextPtr->startMarker);
	TkBTreeUnlinkSegment(sharedTextPtr, textPtr->startMarker);
	FREE_SEGMENT(textPtr->startMarker);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
    } else {
	DEBUG(textPtr->startMarker->refCount -= 1);
    }
    if (textPtr->endMarker->refCount == 1) {
	assert(textPtr->endMarker != sharedTextPtr->endMarker);
	TkBTreeUnlinkSegment(sharedTextPtr, textPtr->endMarker);
	FREE_SEGMENT(textPtr->endMarker);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
    } else {
	DEBUG(textPtr->endMarker->refCount -= 1);
    }

    /*
     * Now we've cleaned up everything of relevance to us in the B-tree, so we
     * disassociate ourselves from it.
     *
     * When the refCount reaches zero, it's time to clean up the shared
     * portion of the text widget.
     */

    sharedTextPtr->refCount -= 1;

    if (sharedTextPtr->refCount > 0) {
	sharedTextPtr->numPeers -= 1;

	/*
	 * No need to call 'TkBTreeRemoveClient' first, since this will do
	 * everything in one go, more quickly.
	 */

	TkBTreeRemoveClient(sharedTextPtr->tree, textPtr);

	/*
	 * Remove ourselves from the peer list.
	 */

	if (sharedTextPtr->peers == textPtr) {
	    sharedTextPtr->peers = textPtr->next;
	} else {
	    TkText *nextPtr = sharedTextPtr->peers;
	    while (nextPtr) {
		if (nextPtr->next == textPtr) {
		    nextPtr->next = textPtr->next;
		    break;
		}
		nextPtr = nextPtr->next;
	    }
	}

	if (textPtr->refCount == 1) {
	    /* Don't forget to release the current tag info. */
	    TkTextTagSetDecrRefCount(textPtr->curTagInfoPtr);
	}
    } else {
	/* Prevent that this resource will be released too early. */
	textPtr->refCount += 1;

	ClearRetainedUndoTokens(sharedTextPtr);
	TkTextUndoDestroyStack(&sharedTextPtr->undoStack);
	free(sharedTextPtr->undoTagList);
	free(sharedTextPtr->undoMarkList);
	TkBTreeDestroy(sharedTextPtr->tree);
	assert(sharedTextPtr->startMarker->refCount == 1);
	FREE_SEGMENT(sharedTextPtr->startMarker);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
	assert(sharedTextPtr->endMarker->refCount == 1);
	FREE_SEGMENT(sharedTextPtr->endMarker);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
	FREE_SEGMENT(sharedTextPtr->protectionMark[0]);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
	FREE_SEGMENT(sharedTextPtr->protectionMark[1]);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
	TkTextFreeAllTags(textPtr);
	Tcl_DeleteHashTable(&sharedTextPtr->tagTable);
	TkTextFreeMarks(sharedTextPtr, 0);
	TkBitDestroy(&sharedTextPtr->usedTags);
	TkBitDestroy(&sharedTextPtr->elisionTags);
	TkBitDestroy(&sharedTextPtr->selectionTags);
	TkBitDestroy(&sharedTextPtr->dontUndoTags);
	TkBitDestroy(&sharedTextPtr->affectDisplayTags);
	TkBitDestroy(&sharedTextPtr->notAffectDisplayTags);
	TkBitDestroy(&sharedTextPtr->affectDisplayNonSelTags);
	TkBitDestroy(&sharedTextPtr->affectGeometryTags);
	TkBitDestroy(&sharedTextPtr->affectGeometryNonSelTags);
	TkBitDestroy(&sharedTextPtr->affectLineHeightTags);
	TkTextTagSetDestroy(&sharedTextPtr->emptyTagInfoPtr);
	Tcl_DeleteHashTable(&sharedTextPtr->windowTable);
	Tcl_DeleteHashTable(&sharedTextPtr->imageTable);
	TkTextDeleteBreakInfoTableEntries(&sharedTextPtr->breakInfoTable);
	Tcl_DeleteHashTable(&sharedTextPtr->breakInfoTable);
	free(sharedTextPtr->mainPeer);
	free(sharedTextPtr->tagLookup);

	if (sharedTextPtr->tagBindingTable) {
	    Tk_DeleteBindingTable(sharedTextPtr->tagBindingTable);
	}
	free(sharedTextPtr);
	DEBUG_ALLOC(tkTextCountDestroyShared++);

	textPtr->sharedIsReleased = 1;
	textPtr->refCount -= 1;

#if TK_CHECK_ALLOCS
	/*
	 * Remove this shared resource from global list.
	 */
	{
	    WatchShared *thisPtr = watchShared;
	    WatchShared *prevPtr = NULL;

	    while (thisPtr->sharedTextPtr != sharedTextPtr) {
		prevPtr = thisPtr;
		thisPtr = thisPtr->nextPtr;
		assert(thisPtr);
	    }

	    if (prevPtr) {
		prevPtr->nextPtr = thisPtr->nextPtr;
	    } else {
		watchShared = thisPtr->nextPtr;
	    }

	    free(thisPtr);
	}
#endif
    }

    if (textPtr->tabArrayPtr) {
	free(textPtr->tabArrayPtr);
    }
    if (textPtr->insertBlinkHandler) {
	Tcl_DeleteTimerHandler(textPtr->insertBlinkHandler);
    }

    textPtr->tkwin = NULL;
    Tcl_DeleteCommandFromToken(textPtr->interp, textPtr->widgetCmd);
    assert(textPtr->flags & DESTROYED);
    DEBUG(textPtr->flags |= MEM_RELEASED);
    TkTextReleaseIfDestroyed(textPtr);
    tkBTreeDebug = debug;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextDecrRefCountAndTestIfDestroyed --
 *
 *	This function is decrementing the reference count of the text
 *	widget and destroys the widget if the reference count has been
 *	gone to zero.
 *
 * Results:
 *	Returns whether the widget has been destroyed.
 *
 * Side effects:
 *	Memory might be freed.
 *
 *----------------------------------------------------------------------
 */

int
TkTextDecrRefCountAndTestIfDestroyed(
    TkText *textPtr)
{
    if (--textPtr->refCount == 0) {
	assert(textPtr->flags & DESTROYED);
	assert(textPtr->flags & MEM_RELEASED);
	free(textPtr);
	DEBUG_ALLOC(tkTextCountDestroyPeer++);
	return 1;
    }
    return !!(textPtr->flags & DESTROYED);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextReleaseIfDestroyed --
 *
 *	This function is decrementing the reference count of the text
 *	widget if it has been destroyed. In this case also the memory
 *	will be released.
 *
 * Results:
 *	Returns whether the widget was already destroyed.
 *
 * Side effects:
 *	Memory might be freed.
 *
 *----------------------------------------------------------------------
 */

int
TkTextReleaseIfDestroyed(
    TkText *textPtr)
{
    if (!(textPtr->flags & DESTROYED)) {
	assert(textPtr->refCount > 0);
	return 0;
    }
    if (--textPtr->refCount == 0) {
	assert(textPtr->flags & MEM_RELEASED);
	free(textPtr);
	DEBUG_ALLOC(tkTextCountDestroyPeer++);
    }
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextTestLangCode --
 *
 *	Test the given language code, whether it satsifies ISO 539-1,
 *	and set an error message if the code is invalid.
 *
 * Results:
 *	The return value is 'tue' if given language code will be accepted,
 *	otherwise 'false' will be returned.
 *
 * Side effects:
 *	An error message in the interpreter may be set.
 *
 *----------------------------------------------------------------------
 */

int
TkTextTestLangCode(
    Tcl_Interp *interp,
    Tcl_Obj *langCodePtr)
{
    char const *lang = Tcl_GetString(langCodePtr);

    if (UCHAR(lang[0]) >= 0x80
	    || UCHAR(lang[1]) >= 0x80
	    || !isalpha(UCHAR(lang[0]))
	    || !isalpha(UCHAR(lang[1]))
	    || !islower(UCHAR(lang[0]))
	    || !islower(UCHAR(lang[1]))
	    || lang[2] != '\0') {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf("bad lang \"%s\": "
		"must have the form of an ISO 639-1 language code, or empty", lang));
	Tcl_SetErrorCode(interp, "TK", "VALUE", "LANG", NULL);
	return 0;
    }
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkConfigureText --
 *
 *	This function is called to process an objv/objc list, plus the Tk
 *	option database, in order to configure (or reconfigure) a text widget.
 *
 * Results:
 *	The return value is a standard Tcl result. If TCL_ERROR is returned,
 *	then the interp's result contains an error message.
 *
 * Side effects:
 *	Configuration information, such as text string, colors, font, etc. get
 *	set for textPtr; old resources get freed, if there were any.
 *
 *----------------------------------------------------------------------
 */

static int
IsNumberOrEmpty(
    const char *str)
{
    for ( ; *str; ++str) {
	if (!isdigit(UCHAR(*str))) {
	    return 0;
	}
    }
    return 1;
}

int
TkConfigureText(
    Tcl_Interp *interp,		/* Used for error reporting. */
    TkText *textPtr,		/* Information about widget; may or may not
				 * already have values for some fields. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    Tk_SavedOptions savedOptions;
    TkTextIndex start, end, current;
    TkSizeT currentEpoch;
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    TkTextBTree tree = sharedTextPtr->tree;
    int copyDownFlags = 0;
    int oldExport = (textPtr->exportSelection) && (!Tcl_IsSafe(textPtr->interp));
    int oldTextDebug = tkTextDebug;
    int didHyphenate = textPtr->hyphenate;
    int oldUndoTagging = textPtr->undoTagging;
    int oldHyphenRules = textPtr->hyphenRules;
    int mask = 0;

    tkTextDebug = 0; /* debugging is not useful here */

#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE

    /*
     * We want also to support the "-start", and "-end" abbreviations. The thing that
     * Tcl supports abbreviated options is a real crux.
     */

    {
	Tcl_Obj **myObjv;
	Tcl_Obj *startLineObj = NULL;
	Tcl_Obj *endLineObj = NULL;
	Tcl_Obj *startIndexObj = NULL;
	Tcl_Obj *endIndexObj = NULL;
	int i, rc;

	myObjv = (Tcl_Obj **)malloc(objc * sizeof(Tcl_Obj *));

	for (i = 0; i < objc; ++i) {
	    Tcl_Obj *obj = objv[i];

	    if (!(i & 1)) {
		if (strcmp(Tcl_GetString(objv[i]), "-start") == 0) {
		    if (i + 1 < objc && IsNumberOrEmpty(Tcl_GetString(objv[i + 1]))) {
			if (!startLineObj) {
			    Tcl_IncrRefCount(startLineObj = Tcl_NewStringObj("-startline", -1));
			}
			obj = startLineObj;
			WarnAboutDeprecatedStartLineOption();
		    } else {
			if (!startIndexObj) {
			    Tcl_IncrRefCount(startIndexObj = Tcl_NewStringObj("-startindex", -1));
			}
			obj = startIndexObj;
		    }
		} else if (MatchOpt(Tcl_GetString(objv[i]), "-startline", 7)) {
		    if (!startLineObj) {
			Tcl_IncrRefCount(startLineObj = Tcl_NewStringObj("-startline", -1));
		    }
		    obj = startLineObj;
		    WarnAboutDeprecatedStartLineOption();
		} else if (MatchOpt(Tcl_GetString(objv[i]), "-startindex", 7)) {
		    if (!startIndexObj) {
			Tcl_IncrRefCount(startIndexObj = Tcl_NewStringObj("-startindex", -1));
		    }
		    obj = startIndexObj;
		} else if (strcmp(Tcl_GetString(objv[i]), "-end") == 0) {
		    if (i + 1 < objc && IsNumberOrEmpty(Tcl_GetString(objv[i + 1]))) {
			if (!endLineObj) {
			    Tcl_IncrRefCount(endLineObj = Tcl_NewStringObj("-endline", -1));
			}
			obj = endLineObj;
			WarnAboutDeprecatedEndLineOption();
		    } else {
			if (!endIndexObj) {
			    Tcl_IncrRefCount(endIndexObj = Tcl_NewStringObj("-endindex", -1));
			}
			obj = endIndexObj;
		    }
		} else if (MatchOpt(Tcl_GetString(objv[i]), "-endline", 5)) {
		    if (!endLineObj) {
			Tcl_IncrRefCount(endLineObj = Tcl_NewStringObj("-endline", -1));
		    }
		    obj = endLineObj;
		    WarnAboutDeprecatedEndLineOption();
		} else if (MatchOpt(Tcl_GetString(objv[i]), "-endindex", 5)) {
		    if (!endIndexObj) {
			Tcl_IncrRefCount(endIndexObj = Tcl_NewStringObj("-endindex", -1));
		    }
		    obj = endIndexObj;
		}
	    }
	    myObjv[i] = obj;
	}

	textPtr->selAttrs = textPtr->textConfigAttrs;
	rc = Tk_SetOptions(interp, (char *) textPtr, textPtr->optionTable,
		objc, myObjv, textPtr->tkwin, &savedOptions, &mask);

	if (rc != TCL_OK) {
	    if (startLineObj && startIndexObj) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "cannot use both, -startindex, and deprecated -startline", -1));
		rc = TCL_ERROR;
	    }
	    if (endLineObj && endIndexObj) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "cannot use both, -endindex, and deprecated -endline", -1));
		rc = TCL_ERROR;
	    }
	}

	if (startLineObj)  { Tcl_GuardedDecrRefCount(startLineObj); }
	if (endLineObj)    { Tcl_GuardedDecrRefCount(endLineObj); }
	if (startIndexObj) { Tcl_GuardedDecrRefCount(startIndexObj); }
	if (endIndexObj)   { Tcl_GuardedDecrRefCount(endIndexObj); }

	free(myObjv);

	if (rc != TCL_OK) {
	    goto error;
	}
    }

    if ((mask & TK_TEXT_INDEX_RANGE) == TK_TEXT_LINE_RANGE) {
	TkTextIndexClear2(&start, NULL, tree);
	TkTextIndexClear2(&end, NULL, tree);
	TkTextIndexSetToStartOfLine2(&start, textPtr->startLine ?
		textPtr->startLine : TkBTreeGetStartLine(textPtr));
	TkTextIndexSetToStartOfLine2(&end, textPtr->endLine ?
		textPtr->endLine : TkBTreeGetLastLine(textPtr));
	if (textPtr->endLine && textPtr->startLine != textPtr->endLine) {
	    TkTextIndexBackChars(textPtr, &end, 1, &end, COUNT_INDICES);
	}

	if (TkTextIndexCompare(&start, &end) > 0) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "-startline must be less than or equal to -endline", -1));
	    Tcl_SetErrorCode(interp, "TK", "TEXT", "INDEX_ORDER", NULL);
	    goto error;
	}

	if (textPtr->endLine && textPtr->endLine != sharedTextPtr->endMarker->sectionPtr->linePtr) {
	    if (textPtr->endMarker->refCount > 1) {
		textPtr->endMarker->refCount -= 1;
		textPtr->endMarker = TkTextMakeStartEndMark(textPtr, &tkTextRightMarkType);
	    } else {
		TkBTreeUnlinkSegment(sharedTextPtr, textPtr->endMarker);
	    }
	    TkBTreeLinkSegment(sharedTextPtr, textPtr->endMarker, &end);
	} else if (textPtr->endMarker != sharedTextPtr->endMarker) {
	    if (--textPtr->endMarker->refCount == 0) {
		TkBTreeUnlinkSegment(sharedTextPtr, textPtr->endMarker);
		FREE_SEGMENT(textPtr->endMarker);
		DEBUG_ALLOC(tkTextCountDestroySegment++);
	    }
	    (textPtr->endMarker = sharedTextPtr->endMarker)->refCount += 1;
	}
	if (textPtr->startLine
		&& textPtr->startLine != sharedTextPtr->startMarker->sectionPtr->linePtr) {
	    if (textPtr->startMarker->refCount > 1) {
		textPtr->startMarker->refCount -= 1;
		textPtr->startMarker = TkTextMakeStartEndMark(textPtr, &tkTextLeftMarkType);
	    } else {
		TkBTreeUnlinkSegment(sharedTextPtr, textPtr->startMarker);
	    }
	    TkBTreeLinkSegment(sharedTextPtr, textPtr->startMarker, &start);
	} else if (textPtr->startMarker != sharedTextPtr->startMarker) {
	    if (--textPtr->startMarker->refCount == 0) {
		TkBTreeUnlinkSegment(sharedTextPtr, textPtr->startMarker);
		FREE_SEGMENT(textPtr->startMarker);
		DEBUG_ALLOC(tkTextCountDestroySegment++);
	    }
	    (textPtr->startMarker = sharedTextPtr->startMarker)->refCount += 1;
	}
    }

#else /* if !SUPPORT_DEPRECATED_STARTLINE_ENDLINE */

    textPtr->selAttrs = textPtr->textConfigAttrs;
    if (Tk_SetOptions(interp, (char *) textPtr, textPtr->optionTable,
	    objc, objv, textPtr->tkwin, &savedOptions, &mask) != TCL_OK) {
	textPtr->selAttrs = textPtr->selTagPtr->attrs;
	tkTextDebug = oldTextDebug;
	return TCL_ERROR;
    }

#endif /* SUPPORT_DEPRECATED_STARTLINE_ENDLINE */

    if (sharedTextPtr->steadyMarks != textPtr->steadyMarks) {
	if (!IsClean(sharedTextPtr, NULL, 1)) {
	    ErrorNotAllowed(interp, "setting this option is possible only if the widget "
		    "is overall clean");
	    goto error;
	}
    }

    /*
     * Copy up shared flags.
     */

    /*
     * Update default value for undoing tag operations.
     */

    if (oldUndoTagging != textPtr->undoTagging) {
	sharedTextPtr->undoTagging = textPtr->undoTagging;
	copyDownFlags = 1;
    }

    /* This flag cannot alter if we have peers. */
    sharedTextPtr->steadyMarks = textPtr->steadyMarks;

    if (sharedTextPtr->autoSeparators != textPtr->autoSeparators) {
	sharedTextPtr->autoSeparators = textPtr->autoSeparators;
	copyDownFlags = 1;
    }

    if (textPtr->undo != sharedTextPtr->undo) {
	if (TestIfPerformingUndoRedo(interp, sharedTextPtr, NULL)) {
	    goto error;
	}

	assert(sharedTextPtr->undo == !!sharedTextPtr->undoStack);
	sharedTextPtr->undo = textPtr->undo;
	copyDownFlags = 1;

	if (sharedTextPtr->undo) {
	    sharedTextPtr->undoStack = TkTextUndoCreateStack(
		    sharedTextPtr->maxUndoDepth,
		    sharedTextPtr->maxRedoDepth,
		    sharedTextPtr->maxUndoSize,
		    TextUndoRedoCallback,
		    TextUndoFreeCallback,
		    TextUndoStackContentChangedCallback);
	    TkTextUndoSetContext(sharedTextPtr->undoStack, sharedTextPtr);
	    sharedTextPtr->undoLevel = 0;
	    sharedTextPtr->pushSeparator = 0;
	    sharedTextPtr->isIrreversible = 0;
	    sharedTextPtr->isAltered = 0;
	} else {
	    sharedTextPtr->isIrreversible = TkTextUndoContentIsModified(sharedTextPtr->undoStack);
	    ClearRetainedUndoTokens(sharedTextPtr);
	    TkTextUndoDestroyStack(&sharedTextPtr->undoStack);
	}
    }

    /* normalize values */
    textPtr->maxUndoDepth = MAX(textPtr->maxUndoDepth, 0);
    textPtr->maxRedoDepth = MAX(-1, textPtr->maxRedoDepth);
    textPtr->maxUndoSize = MAX(textPtr->maxUndoSize, 0);

    if (sharedTextPtr->maxUndoDepth != textPtr->maxUndoDepth
	    || sharedTextPtr->maxRedoDepth != textPtr->maxRedoDepth
	    || sharedTextPtr->maxUndoSize != textPtr->maxUndoSize) {
	if (sharedTextPtr->undoStack) {
	    TkTextUndoSetMaxStackDepth(sharedTextPtr->undoStack,
		    textPtr->maxUndoDepth, textPtr->maxRedoDepth);
	    TkTextUndoSetMaxStackSize(sharedTextPtr->undoStack, textPtr->maxUndoSize, 0);
	}
	sharedTextPtr->maxUndoDepth = textPtr->maxUndoDepth;
	sharedTextPtr->maxRedoDepth = textPtr->maxRedoDepth;
	sharedTextPtr->maxUndoSize = textPtr->maxUndoSize;
	copyDownFlags = 1;
    }

    if (copyDownFlags) {
	TkText *tPtr;

	for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	    tPtr->autoSeparators = sharedTextPtr->autoSeparators;
	    tPtr->maxUndoDepth = sharedTextPtr->maxUndoDepth;
	    tPtr->maxRedoDepth = sharedTextPtr->maxRedoDepth;
	    tPtr->maxUndoSize = sharedTextPtr->maxUndoSize;
	    tPtr->undo = sharedTextPtr->undo;
	    tPtr->undoTagging = sharedTextPtr->undoTagging;
	}
    }

    /*
     * Check soft hyphen support.
     */

    textPtr->hyphenate = textPtr->useHyphenSupport
	    && textPtr->state != TK_TEXT_STATE_NORMAL
	    && (textPtr->wrapMode == TEXT_WRAPMODE_WORD || textPtr->wrapMode == TEXT_WRAPMODE_CODEPOINT);
    if (didHyphenate != textPtr->hyphenate) {
	mask |= TK_TEXT_LINE_GEOMETRY;
    }

    /*
     * Parse hyphen rules.
     */

    if (textPtr->hyphenRulesPtr) {
	if (TkTextParseHyphenRules(textPtr, textPtr->hyphenRulesPtr, &textPtr->hyphenRules) != TCL_OK) {
	    goto error;
	}
    } else {
	textPtr->hyphenRules = TK_TEXT_HYPHEN_MASK;
    }
    if (oldHyphenRules != textPtr->hyphenRules && textPtr->hyphenate) {
	mask |= TK_TEXT_LINE_GEOMETRY;
    }

    /*
     * Parse tab stops.
     */

    if (textPtr->tabArrayPtr) {
	free(textPtr->tabArrayPtr);
	textPtr->tabArrayPtr = NULL;
    }
    if (textPtr->tabOptionPtr) {
	textPtr->tabArrayPtr = TkTextGetTabs(interp, textPtr, textPtr->tabOptionPtr);
	if (!textPtr->tabArrayPtr) {
	    Tcl_AddErrorInfo(interp, "\n    (while processing -tabs option)");
	    goto error;
	}
    }

    /*
     * Check language support.
     */

    if (textPtr->langPtr) {
	if (!TkTextTestLangCode(interp, textPtr->langPtr)) {
	    goto error;
	}
	memcpy(textPtr->lang, Tcl_GetString(textPtr->langPtr), 3);
    } else {
	memset(textPtr->lang, 0, 3);
    }

    /*
     * A few other options also need special processing, such as parsing the
     * geometry and setting the background from a 3-D border.
     */

    Tk_SetBackgroundFromBorder(textPtr->tkwin, textPtr->border);

    /*
     * Now setup the -startindex/-setindex range. This step cannot be restored,
     * so this function must not return with an error code after this processing.
     */

    if (mask & TK_TEXT_INDEX_RANGE) {
	if (textPtr->newStartIndex) {
	    if (!TkTextGetIndexFromObj(interp, sharedTextPtr->mainPeer,
		    textPtr->newStartIndex, &start)) {
		goto error;
	    }
	} else {
	    TkTextIndexClear(&start, textPtr);
	    TkTextIndexSetSegment(&start, textPtr->startMarker);
	}
	if (textPtr->newEndIndex) {
	    if (!TkTextGetIndexFromObj(interp, sharedTextPtr->mainPeer, textPtr->newEndIndex, &end)) {
		goto error;
	    }
	} else {
	    TkTextIndexClear(&end, textPtr);
	    TkTextIndexSetSegment(&end, textPtr->endMarker);
	}
	if (TkTextIndexCompare(&start, &end) > 0) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "-startindex must be less than or equal to -endindex", -1));
	    Tcl_SetErrorCode(interp, "TK", "TEXT", "INDEX_ORDER", NULL);
	    goto error;
	}

	start.textPtr = NULL;
	end.textPtr = NULL;

	if (textPtr->newEndIndex) {
	    if (TkTextIndexIsEndOfText(&end)) {
		if (--textPtr->endMarker->refCount == 0) {
		    assert(textPtr->endMarker != sharedTextPtr->endMarker);
		    TkBTreeUnlinkSegment(sharedTextPtr, textPtr->endMarker);
		    FREE_SEGMENT(textPtr->endMarker);
		    DEBUG_ALLOC(tkTextCountDestroySegment++);
		}
		(textPtr->endMarker = sharedTextPtr->endMarker)->refCount += 1;
	    } else {
		if (textPtr->endMarker->refCount > 1) {
		    textPtr->endMarker->refCount -= 1;
		    textPtr->endMarker = TkTextMakeStartEndMark(textPtr, &tkTextRightMarkType);
		} else {
		    assert(textPtr->endMarker != sharedTextPtr->endMarker);
		    TkBTreeUnlinkSegment(sharedTextPtr, textPtr->endMarker);
		}
		TkBTreeLinkSegment(sharedTextPtr, textPtr->endMarker, &end);
	    }
	    Tcl_GuardedDecrRefCount(textPtr->newEndIndex);
	    textPtr->newEndIndex = NULL;
	}

	if (textPtr->newStartIndex) {
	    if (TkTextIndexIsStartOfText(&start)) {
		if (--textPtr->startMarker->refCount == 0) {
		    assert(textPtr->startMarker != sharedTextPtr->startMarker);
		    TkBTreeUnlinkSegment(sharedTextPtr, textPtr->startMarker);
		    FREE_SEGMENT(textPtr->startMarker);
		    DEBUG_ALLOC(tkTextCountDestroySegment++);
		}
		(textPtr->startMarker = sharedTextPtr->startMarker)->refCount += 1;
	    } else {
		if (textPtr->startMarker->refCount > 1) {
		    textPtr->startMarker->refCount -= 1;
		    textPtr->startMarker = TkTextMakeStartEndMark(textPtr, &tkTextLeftMarkType);
		} else {
		    TkBTreeUnlinkSegment(sharedTextPtr, textPtr->startMarker);
		}
		TkBTreeLinkSegment(sharedTextPtr, textPtr->startMarker, &start);
	    }
	    Tcl_GuardedDecrRefCount(textPtr->newStartIndex);
	    textPtr->newStartIndex = NULL;
	}

	/*
	 * Line start and/or end have been adjusted. We need to validate the
	 * first displayed line and arrange for re-layout.
	 */

	TkBTreeClientRangeChanged(textPtr, MAX(0, textPtr->lineHeight));
	TkrTextMakeByteIndex(tree, NULL, TkTextIndexGetLineNumber(&textPtr->topIndex, NULL), 0, &current);

	if (TkTextIndexCompare(&current, &start) < 0 || TkTextIndexCompare(&end, &current) < 0) {
	    TkTextSearch search;
	    TkTextIndex first, last;
	    int selChanged = 0;

	    TkTextSetYView(textPtr, &start, 0);

	    /*
	     * We may need to adjust the selection. So we have to check
	     * whether the "sel" tag was applied to anything outside the
	     * current start,end.
	     */

	    TkrTextMakeByteIndex(tree, NULL, 0, 0, &first);
	    TkBTreeStartSearch(&first, &start, textPtr->selTagPtr, &search, SEARCH_NEXT_TAGON);
	    if (TkBTreeNextTag(&search)) {
		selChanged = 1;
	    } else {
		TkrTextMakeByteIndex(tree, NULL, TkrBTreeNumLines(tree, NULL), 0, &last);
		TkBTreeStartSearchBack(&end, &last, textPtr->selTagPtr,
			&search, SEARCH_EITHER_TAGON_TAGOFF);
		if (TkBTreePrevTag(&search)) {
		    selChanged = 1;
		}
	    }
	    if (selChanged) {
		/*
		 * Send an event that the selection has changed, and abort any
		 * partial-selections in progress.
		 */

		TkTextSelectionEvent(textPtr);
		textPtr->abortSelections = 1;
	    }
	}

	/* Indices are potentially obsolete after changing -start and/or
	 * -end, therefore increase the epoch.
	 * Also, clamp the insert and current (unshared) marks to the new
	 * -start/-end range limits of the widget. All other (shared)
	 * marks are unchanged.
         * The return value of TkTextMarkNameToIndex does not need to be
         * checked: "insert" and "current" marks always exist, and the
         * purpose of the code below precisely is to move them inside the
         * -start/-end range.
	 */

	currentEpoch = TkBTreeIncrEpoch(tree);
	start.textPtr = textPtr;
	end.textPtr = textPtr;

	TkTextMarkNameToIndex(textPtr, "current", &current);
	if (TkTextIndexCompare(&current, &start) < 0) {
	    textPtr->currentMarkPtr = TkrTextSetMark(textPtr, "current", &start);
	} else if (TkTextIndexCompare(&current, &end) > 0) {
	    textPtr->currentMarkPtr = TkrTextSetMark(textPtr, "current", &end);
	}
    } else {
	currentEpoch = TkBTreeEpoch(tree);
    }

    /*
     * Don't allow negative values for specific attributes.
     */

    textPtr->spacing1 = MAX(textPtr->spacing1, 0);
    textPtr->spacing2 = MAX(textPtr->spacing2, 0);
    textPtr->spacing3 = MAX(textPtr->spacing3, 0);
    textPtr->highlightWidth = MAX(textPtr->highlightWidth, 0);
    textPtr->borderWidth = MAX(textPtr->borderWidth, 0);
    textPtr->insertWidth = MAX(textPtr->insertWidth, 0);
    textPtr->syncTime = MAX(0, textPtr->syncTime);
    textPtr->selAttrs.borderWidth = MAX(textPtr->selAttrs.borderWidth, 0);

    /*
     * Make sure that configuration options are properly mirrored between the
     * widget record and the "sel" tags.
     */

    if (textPtr->selAttrs.border != textPtr->textConfigAttrs.border) {
	textPtr->selTagPtr->attrs.border = textPtr->selAttrs.border;
    }
    if (textPtr->selAttrs.inactiveBorder != textPtr->textConfigAttrs.inactiveBorder) {
	textPtr->selTagPtr->attrs.inactiveBorder = textPtr->selAttrs.inactiveBorder;
    }
    if (textPtr->selAttrs.fgColor != textPtr->textConfigAttrs.fgColor) {
	textPtr->selTagPtr->attrs.fgColor = textPtr->selAttrs.fgColor;
    }
    if (textPtr->selAttrs.inactiveFgColor != textPtr->textConfigAttrs.inactiveFgColor) {
	textPtr->selTagPtr->attrs.inactiveFgColor = textPtr->selAttrs.inactiveFgColor;
    }
    if (textPtr->selAttrs.borderWidthPtr != textPtr->textConfigAttrs.borderWidthPtr) {
	textPtr->selTagPtr->attrs.borderWidthPtr = textPtr->selAttrs.borderWidthPtr;
	textPtr->selTagPtr->attrs.borderWidth = textPtr->selAttrs.borderWidth;
    }
    textPtr->textConfigAttrs = textPtr->selAttrs;
    textPtr->selAttrs = textPtr->selTagPtr->attrs;
    TkTextUpdateTagDisplayFlags(textPtr->selTagPtr);
    TkTextRedrawTag(NULL, textPtr, NULL, NULL, textPtr->selTagPtr, 0);

    /*
     * Claim the selection if we've suddenly started exporting it and there
     * are tagged characters.
     */

    if (textPtr->exportSelection && (!oldExport) && (!Tcl_IsSafe(textPtr->interp))) {
	TkTextSearch search;
	TkTextIndex first, last;

	TkTextIndexSetupToStartOfText(&first, textPtr, tree);
	TkTextIndexSetupToEndOfText(&last, textPtr, tree);
	TkBTreeStartSearch(&first, &last, textPtr->selTagPtr, &search, SEARCH_NEXT_TAGON);
	if (TkBTreeNextTag(&search)) {
	    Tk_OwnSelection(textPtr->tkwin, XA_PRIMARY, TkTextLostSelection, textPtr);
	    textPtr->flags |= GOT_SELECTION;
	}
    }

    /*
     * Account for state changes that would reenable blinking cursor state.
     */

    if (textPtr->flags & HAVE_FOCUS) {
	Tcl_DeleteTimerHandler(textPtr->insertBlinkHandler);
	textPtr->insertBlinkHandler = NULL;
	TextBlinkProc(textPtr);
    }

    /*
     * Register the desired geometry for the window, and arrange for the
     * window to be redisplayed.
     */

    textPtr->width = MAX(textPtr->width, 1);
    textPtr->height = MAX(textPtr->height, 1);

    Tk_FreeSavedOptions(&savedOptions);
    TextWorldChanged(textPtr, mask);

    if (textPtr->syncTime == 0 && (mask & TK_TEXT_SYNCHRONIZE)) {
	UpdateLineMetrics(textPtr, 0, TkrBTreeNumLines(sharedTextPtr->tree, textPtr));
    }

    /*
     * At least handle the "watch" command, and set the insert cursor.
     */

    if (mask & TK_TEXT_INDEX_RANGE) {
	/*
	 * Setting the "insert" mark must be done at the end, because the "watch" command
	 * will be triggered. Be sure to use the actual range, mind the epoch.
	 */

	TkTextMarkNameToIndex(textPtr, "insert", &current);

	if (start.stateEpoch != currentEpoch) {
	    /*
	     * The "watch" command did change the content.
	     */
	    TkTextIndexSetupToStartOfText(&start, textPtr, tree);
	    TkTextIndexSetupToEndOfText(&end, textPtr, tree);
	}

	start.textPtr = textPtr;
	end.textPtr = textPtr;

	if (TkTextIndexCompare(&current, &start) < 0) {
	    textPtr->insertMarkPtr = TkrTextSetMark(textPtr, "insert", &start);
	} else if (TkTextIndexCompare(&current, &end) >= 0) {
	    textPtr->insertMarkPtr = TkrTextSetMark(textPtr, "insert", &end);
	}
    }

    tkTextDebug = oldTextDebug;
    TK_BTREE_DEBUG(TkBTreeCheck(sharedTextPtr->tree));

    return TCL_OK;

error:
    Tk_RestoreSavedOptions(&savedOptions);
    textPtr->selAttrs = textPtr->selTagPtr->attrs;
    tkTextDebug = oldTextDebug;
    return TCL_ERROR;
}

/*
 *---------------------------------------------------------------------------
 *
 * TkTextParseHyphenRules --
 *
 *	This function is parsing the object containing the hyphen rules.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

int
TkTextParseHyphenRules(
    TkText *textPtr,
    Tcl_Obj *objPtr,
    int *rulesPtr)
{
    int rules = 0;
    Tcl_Obj **argv;
    int argc, i;
    unsigned k;

    assert(rulesPtr);

    if (Tcl_ListObjGetElements(textPtr->interp, objPtr, &argc, &argv) != TCL_OK) {
	return TCL_ERROR;
    }
    for (i = 0; i < argc; ++i) {
	char const *rule = Tcl_GetString(argv[i]);
	int r = rules;

	for (k = 0; k < sizeof(hyphenRuleStrings)/sizeof(hyphenRuleStrings[0]); ++k) {
	    if (strcmp(rule, hyphenRuleStrings[k]) == 0) {
		rules |= (1 << k);
	    }
	}
	if (r == rules) {
	    Tcl_SetObjResult(textPtr->interp, Tcl_ObjPrintf("unknown hyphen rule \"%s\"", rule));
	    Tcl_SetErrorCode(textPtr->interp, "TK", "TEXT", "VALUE", NULL);
	    return TCL_ERROR;
	}
    }
    *rulesPtr = rules;
    return TCL_OK;
}

/*
 *---------------------------------------------------------------------------
 *
 * TextWorldChangedCallback --
 *
 *	This function is called when the world has changed in some way and the
 *	widget needs to recompute all its graphics contexts and determine its
 *	new geometry.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Configures all tags in the Text with a empty objc/objv, for the side
 *	effect of causing all the items to recompute their geometry and to be
 *	redisplayed.
 *
 *---------------------------------------------------------------------------
 */

static void
TextWorldChangedCallback(
    ClientData instanceData)	/* Information about widget. */
{
    TextWorldChanged((TkText *) instanceData, TK_TEXT_LINE_GEOMETRY);
}

/*
 *---------------------------------------------------------------------------
 *
 * TextWorldChanged --
 *
 *	This function is called when the world has changed in some way and the
 *	widget needs to recompute all its graphics contexts and determine its
 *	new geometry.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Configures all tags in the Text with a empty objc/objv, for the side
 *	effect of causing all the items to recompute their geometry and to be
 *	redisplayed.
 *
 *---------------------------------------------------------------------------
 */

static void
TextWorldChanged(
    TkText *textPtr,		/* Information about widget. */
    int mask)			/* OR'd collection of bits showing what has changed. */
{
    Tk_FontMetrics fm;
    int border;
    int oldLineHeight = textPtr->lineHeight;

    Tk_GetFontMetrics(textPtr->tkfont, &fm);
    textPtr->lineHeight = MAX(1, fm.linespace);
    textPtr->charWidth = MAX(1, Tk_TextWidth(textPtr->tkfont, "0", 1));
    textPtr->spaceWidth = MAX(1, Tk_TextWidth(textPtr->tkfont, " ", 1));

    if (oldLineHeight != textPtr->lineHeight) {
	TkTextFontHeightChanged(textPtr);
    }

    border = textPtr->borderWidth + textPtr->highlightWidth;
    Tk_GeometryRequest(textPtr->tkwin,
	    textPtr->width*textPtr->charWidth + 2*textPtr->padX + 2*border,
	    textPtr->height*(fm.linespace + textPtr->spacing1 + textPtr->spacing3)
		    + 2*textPtr->padY + 2*border);

    Tk_SetInternalBorderEx(textPtr->tkwin,
	    border + textPtr->padX, border + textPtr->padX,
	    border + textPtr->padY, border + textPtr->padY);
    if (textPtr->setGrid) {
	Tk_SetGrid(textPtr->tkwin, textPtr->width, textPtr->height,
		textPtr->charWidth, textPtr->lineHeight);
    } else {
	Tk_UnsetGrid(textPtr->tkwin);
    }

    TkTextRelayoutWindow(textPtr, mask);
    TK_BTREE_DEBUG(TkBTreeCheck(textPtr->sharedTextPtr->tree));
}

/*
 *--------------------------------------------------------------
 *
 * TextEventProc --
 *
 *	This function is invoked by the Tk dispatcher on structure changes to
 *	a text. For texts with 3D borders, this function is also invoked for
 *	exposures.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get cleaned up.
 *	When it gets exposed, it is redisplayed.
 *
 *--------------------------------------------------------------
 */

static void
ProcessConfigureNotify(
    TkText *textPtr,
    int updateLineGeometry)
{
    int mask = updateLineGeometry ? TK_TEXT_LINE_GEOMETRY : 0;

    /*
     * Do not allow line height computations before we accept the first
     * ConfigureNotify event. The problem is the very poor performance
     * in CalculateDisplayLineHeight() with very small widget width.
     */

    if (!textPtr->sharedTextPtr->allowUpdateLineMetrics) {
	textPtr->sharedTextPtr->allowUpdateLineMetrics = 1;
	updateLineGeometry = 1;
	TkTextEventuallyRepick(textPtr);
    }

    if (textPtr->prevHeight != Tk_Height(textPtr->tkwin)
	    || textPtr->prevWidth != Tk_Width(textPtr->tkwin)) {
	mask |= TK_TEXT_LINE_REDRAW_BOTTOM_LINE;
    }
    TkTextRelayoutWindow(textPtr, mask);
    TK_BTREE_DEBUG(TkBTreeCheck(textPtr->sharedTextPtr->tree));

    textPtr->prevWidth = Tk_Width(textPtr->tkwin);
    textPtr->prevHeight = Tk_Height(textPtr->tkwin);
}

static void
ProcessDestroyNotify(
    TkText *textPtr)
{
    if (textPtr->setGrid) {
	Tk_UnsetGrid(textPtr->tkwin);
	textPtr->setGrid = 0;
    }
    if (!(textPtr->flags & OPTIONS_FREED)) {
	/* Restore the original attributes. */
	textPtr->selAttrs = textPtr->textConfigAttrs;
	Tk_FreeConfigOptions((char *) textPtr, textPtr->optionTable, textPtr->tkwin);
	textPtr->flags |= OPTIONS_FREED;
    }
    textPtr->flags |= DESTROYED;

    /*
     * Call 'DestroyTest' to handle the deletion for us. The actual
     * textPtr may still exist after this, if there are some outstanding
     * references. But we have flagged it as DESTROYED just above, so
     * nothing will try to make use of it very extensively.
     */

    DestroyText(textPtr);
}

static void
ProcessFocusInOut(
    TkText *textPtr,
    XEvent *eventPtr)
{
    TkTextIndex index, index2;

    if (eventPtr->xfocus.detail == NotifyInferior
	    || eventPtr->xfocus.detail == NotifyAncestor
	    || eventPtr->xfocus.detail == NotifyNonlinear) {
	if (eventPtr->type == FocusIn) {
	    textPtr->flags |= HAVE_FOCUS | INSERT_ON;
	} else {
	    textPtr->flags &= ~(HAVE_FOCUS | INSERT_ON);
	}
	if (textPtr->state == TK_TEXT_STATE_NORMAL) {
	    if (eventPtr->type == FocusOut) {
		if (textPtr->insertBlinkHandler) {
		    Tcl_DeleteTimerHandler(textPtr->insertBlinkHandler);
		    textPtr->insertBlinkHandler = NULL;
		}
	    } else if (textPtr->insertOffTime && !textPtr->insertBlinkHandler) {
		textPtr->insertBlinkHandler =
			Tcl_CreateTimerHandler(textPtr->insertOnTime, TextBlinkProc, textPtr);
	    }
	    TkTextMarkSegToIndex(textPtr, textPtr->insertMarkPtr, &index);
	    TkTextIndexForwChars(textPtr, &index, 1, &index2, COUNT_INDICES);
	    TkrTextChanged(NULL, textPtr, &index, &index2);
	}
	if (textPtr->selAttrs.inactiveBorder != textPtr->selAttrs.border
		|| textPtr->selAttrs.inactiveFgColor != textPtr->selAttrs.fgColor) {
	    TkTextRedrawTag(NULL, textPtr, NULL, NULL, textPtr->selTagPtr, 0);
	}
	if (textPtr->highlightWidth > 0) {
	    TkTextRedrawRegion(textPtr, 0, 0, textPtr->highlightWidth, textPtr->highlightWidth);
	}
    }
}

static void
TextEventProc(
    ClientData clientData,	/* Information about window. */
    XEvent *eventPtr)		/* Information about event. */
{
    TkText *textPtr = (TkText *)clientData;

    switch (eventPtr->type) {
    case ConfigureNotify:
	if (textPtr->prevWidth != Tk_Width(textPtr->tkwin)
		|| textPtr->prevHeight != Tk_Height(textPtr->tkwin)) {
	    /*
	     * We don't need display computations until the widget is mapped
	     * or as long as the width seems to be unrealistic (not yet expanded
	     * by the geometry manager), see ProcessConfigureNotify() for more
	     * information.
	     */

	    if (Tk_IsMapped(textPtr->tkwin)
		    || (Tk_Width(textPtr->tkwin) >
			MAX(1, 2*(textPtr->highlightWidth + textPtr->borderWidth + textPtr->padX)))) {
		ProcessConfigureNotify(textPtr, textPtr->prevWidth != Tk_Width(textPtr->tkwin));
	    }
	}
	break;
    case DestroyNotify:
	ProcessDestroyNotify(textPtr);
	break;
    default:
	if (!textPtr->sharedTextPtr->allowUpdateLineMetrics) {
	    /*
	     * I don't know whether this can happen, but we want to be sure,
	     * probably we have rejected all ConfigureNotify events before
	     * first Expose arrives.
	     */
	    ProcessConfigureNotify(textPtr, 1);
	}
	switch (eventPtr->type) {
	case Expose:
	    TkTextRedrawRegion(textPtr, eventPtr->xexpose.x, eventPtr->xexpose.y,
		    eventPtr->xexpose.width, eventPtr->xexpose.height);
	    break;
	case FocusIn:
	case FocusOut:
	    ProcessFocusInOut(textPtr, eventPtr);
	    break;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextCmdDeletedProc --
 *
 *	This function is invoked when a widget command is deleted. If the
 *	widget isn't already in the process of being destroyed, this command
 *	destroys it.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The widget is destroyed.
 *
 *----------------------------------------------------------------------
 */

static void
TextCmdDeletedProc(
    ClientData clientData)	/* Pointer to widget record for widget. */
{
    TkText *textPtr = (TkText *)clientData;
    Tk_Window tkwin = textPtr->tkwin;

    /*
     * This function could be invoked either because the window was destroyed
     * and the command was then deleted (in which this flag is already set) or
     * because the command was deleted, and then this function destroys the
     * widget.
     */

    if (!(textPtr->flags & DESTROYED)) {
	if (textPtr->setGrid) {
	    Tk_UnsetGrid(textPtr->tkwin);
	    textPtr->setGrid = 0;
	}
	textPtr->flags |= DESTROYED;
	Tk_DestroyWindow(tkwin);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * InsertChars --
 *
 *	This function implements most of the functionality of the "insert"
 *	widget command.
 *
 * Results:
 *	The length of the inserted string.
 *
 * Side effects:
 *	The characters in "stringPtr" get added to the text just before the
 *	character indicated by "indexPtr".
 *
 *	If 'viewUpdate' is 1, we may adjust the window contents'
 *	y-position, and scrollbar setting.
 *
 *----------------------------------------------------------------------
 */

static void
InitPosition(
    TkSharedText *sharedTextPtr,	/* Shared portion of peer widgets. */
    TkTextPosition *positions)		/* Initialise this position array. */
{
    unsigned i;

    for (i = 0; i < sharedTextPtr->numPeers; ++i, ++positions) {
	positions->lineIndex = -1;
	positions->byteIndex = 0;
    }
}

static void
FindNewTopPosition(
    TkSharedText *sharedTextPtr,	/* Shared portion of peer widgets. */
    TkTextPosition *positions,		/* Fill this position array. */
    const TkTextIndex *index1Ptr,	/* Start position of this insert/delete. */
    const TkTextIndex *index2Ptr,	/* End position of this delete, is NULL in case of insert. */
    unsigned lengthOfInsertion)		/* Length of inserted string, is zero in case of delete. */
{
    TkTextBTree tree = sharedTextPtr->tree;
    TkText *tPtr;

    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next, ++positions) {
	int lineIndex = -1;
	int byteIndex = 0;

	if (index2Ptr == NULL) {
	    if (TkTextIndexGetLine(index1Ptr) == TkTextIndexGetLine(&tPtr->topIndex)) {
		lineIndex = TkBTreeLinesTo(tree, NULL, TkTextIndexGetLine(index1Ptr), NULL);
		byteIndex = TkTextIndexGetByteIndex(&tPtr->topIndex);
		if (byteIndex > TkTextIndexGetByteIndex(index1Ptr)) {
		    byteIndex += lengthOfInsertion;
		}
	    }
	} else if (TkTextIndexCompare(index2Ptr, &tPtr->topIndex) >= 0) {
	    if (TkTextIndexCompare(index1Ptr, &tPtr->topIndex) <= 0) {
		/*
		 * Deletion range straddles topIndex: use the beginning of the
		 * range as the new topIndex.
		 */

		lineIndex = TkBTreeLinesTo(tree, NULL, TkTextIndexGetLine(index1Ptr), NULL);
		byteIndex = TkTextIndexGetByteIndex(index1Ptr);
	    } else if (TkTextIndexGetLine(index1Ptr) == TkTextIndexGetLine(&tPtr->topIndex)) {
		/*
		 * Deletion range starts on top line but after topIndex. Use
		 * the current topIndex as the new one.
		 */

		lineIndex = TkBTreeLinesTo(tree, NULL, TkTextIndexGetLine(index1Ptr), NULL);
		byteIndex = TkTextIndexGetByteIndex(&tPtr->topIndex);
            } else {
                /*
                 * Deletion range starts after the top line. This peers's view
                 * will not need to be reset. Nothing to do.
                 */
	    }
	} else if (TkTextIndexGetLine(index2Ptr) == TkTextIndexGetLine(&tPtr->topIndex)) {
	    /*
	     * Deletion range ends on top line but before topIndex. Figure out
	     * what will be the new character index for the character
	     * currently pointed to by topIndex.
	     */

	    lineIndex = TkBTreeLinesTo(tree, NULL, TkTextIndexGetLine(index2Ptr), NULL);
	    byteIndex = TkTextIndexGetByteIndex(&tPtr->topIndex) - TkTextIndexGetByteIndex(index2Ptr);
	    if (TkTextIndexGetLine(index1Ptr) == TkTextIndexGetLine(index2Ptr)) {
		byteIndex += TkTextIndexGetByteIndex(index1Ptr);
	    }
        } else {
            /*
             * Deletion range ends before the top line. This peers's view
             * will not need to be reset. Nothing to do.
             */
	}

	if (lineIndex != -1) {
	    if (lineIndex == positions->lineIndex) {
		positions->byteIndex = MAX(positions->byteIndex, byteIndex);
	    } else {
		positions->lineIndex = MAX(positions->lineIndex, lineIndex);
		positions->byteIndex = byteIndex;
	    }
	}
    }
}

static void
SetNewTopPosition(
    TkSharedText *sharedTextPtr,	/* Shared portion of peer widgets. */
    TkText *textPtr,			/* Current peer widget, can be NULL. */
    const TkTextPosition *positions,	/* New top positions. */
    int viewUpdate)			/* Update the view of current widget if set. */
{
    TkText *tPtr;

    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next, ++positions) {
	if (positions->lineIndex != -1) {
	    TkTextIndex index;

	    if (tPtr == textPtr && !viewUpdate) {
		continue;
	    }

	    TkrTextMakeByteIndex(sharedTextPtr->tree, NULL, positions->lineIndex, 0, &index);
	    TkrTextIndexForwBytes(tPtr, &index, positions->byteIndex, &index);

	    if (tPtr == textPtr) {
		/*
		 * Line cannot be before -startindex of textPtr because this line
		 * corresponds to an index which is necessarily between "begin"
		 * and "end" relative to textPtr. Therefore no need to clamp line
		 * to the -start/-end range.
		 */
	    } else {
		TkTextIndex start;

                /*
                 * Line may be before -startindex of tPtr and must be clamped to -startindex
		 * before providing it to TkTextSetYView otherwise lines before -startindex
                 * would be displayed. There is no need to worry about -endline however,
                 * because the view will only be reset if the deletion involves the TOP
		 * line of the screen.
                 */

		TkTextIndexClear2(&start, tPtr, sharedTextPtr->tree);
		TkTextIndexSetSegment(&start, tPtr->startMarker);
		if (TkTextIndexCompare(&index, &start) < 0) {
		    index = start;
		}
	    }

	    TkTextSetYView(tPtr, &index, 0);
	}
    }
}

static void
ParseHyphens(
    const char *string,
    const char *end,
    char *buffer)
{
#if 0 && TCL_UTF_MAX > 4
# error "The text widget is designed for UTF-8, this applies also to the legacy code. Undocumented pseudo UTF-8 strings cannot be processed with this function, because it relies on the UTF-8 specification."
#endif

    assert(TK_TEXT_HYPHEN_MASK < 256); /* otherwise does not fit into char */

    /*
     * Preparing a string for hyphenation support. Note that 0xff is not allowed in
     * UTF-8 strings, so we can use this value for special purposes.
     */

    while (string != end) {
	if (*string == '\\') {
	    switch (*++string) {
	    case '\0':
		*buffer++ = '\\';
		break;
	    case '-':
		*buffer++ = 0xff;
		*buffer++ = '-';
		string += 1;
		break;
	    case '+':
	    	*buffer++ = 0xff;
		*buffer++ = '+';
		string += 1;
		break;
	    case ':':
		switch (string[1]) {
		case 'c':
		    if (strncmp(string, ":ck:", 4) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_CK);
			string += 4;
			break;
		    }
		    *buffer++ = *string++;
		    break;
		case 'd':
		    if (strncmp(string, ":dd:", 4) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_DOUBLE_DIGRAPH);
			string += 4;
			break;
		    }
		    if (strncmp(string, ":dv:", 4) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_DOUBLE_VOWEL);
			string += 4;
			break;
		    }
		    if (strncmp(string, ":doubledigraph:", 15) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_DOUBLE_DIGRAPH);
			string += 15;
			break;
		    }
		    if (strncmp(string, ":doublevowel:", 13) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_DOUBLE_VOWEL);
			string += 13;
			break;
		    }
		    *buffer++ = *string++;
		    break;
		case 'g':
		    if (strncmp(string, ":ge:", 4) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_GEMINATION);
			string += 4;
			break;
		    }
		    if (strncmp(string, ":gemination:", 12) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_GEMINATION);
			string += 12;
			break;
		    }
		    *buffer++ = *string++;
		    break;
		case 'r':
		    if (strncmp(string, ":rh:", 4) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_REPEAT);
			string += 4;
			break;
		    }
		    if (strncmp(string, ":repeathyphen:", 14) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_REPEAT);
			string += 14;
			break;
		    }
		    *buffer++ = *string++;
		    break;
		case 't':
		    if (strncmp(string, ":tr:", 4) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_TREMA);
			string += 4;
			break;
		    }
		    if (strncmp(string, ":tc:", 4) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_TRIPLE_CONSONANT);
			string += 4;
			break;
		    }
		    if (strncmp(string, ":trema:", 7) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_TREMA);
			string += 7;
			break;
		    }
		    if (strncmp(string, ":tripleconsonant:", 17) == 0) {
			*buffer++ = 0xff;
			*buffer++ = (char) (1 << TK_TEXT_HYPHEN_TRIPLE_CONSONANT);
			string += 17;
			break;
		    }
		    *buffer++ = *string++;
		    break;
	    default:
		*buffer++ = *string++;
		break;
	    }
	    }
	} else {
	    *buffer++ = *string++;
	}
    }
    *buffer = '\0';
}

static void
InsertChars(
    TkText *textPtr,		/* Overall information about text widget. */
    TkTextIndex *index1Ptr,	/* Where to insert new characters. May be modified if the index
    				 * is not valid for insertion (e.g. if at "end"). */
    TkTextIndex *index2Ptr,	/* Out: Index at the end of the inserted text. */
    char const *string,		/* Null-terminated string containing new information to add to text. */
    unsigned length,		/* Length of string content. */
    int viewUpdate,		/* Update the view if set. */
    TkTextTagSet *tagInfoPtr,	/* Add these tags to the inserted text, can be NULL. */
    TkTextTag *hyphenTagPtr,	/* Associate this tag with soft hyphens, can be NULL. */
    int parseHyphens)		/* Should we parse hyphens (tk_textInsert)? */
{
    TkSharedText *sharedTextPtr;
    TkText *tPtr;
    TkTextPosition *textPosition;
    TkTextPosition textPosBuf[PIXEL_CLIENTS];
    TkTextUndoInfo undoInfo;
    TkTextUndoInfo *undoInfoPtr;
    TkTextIndex startIndex;
    const char *text = string;
    char textBuf[4096];

    assert(textPtr);
    assert(length > 0);
    assert(!TkTextIsDeadPeer(textPtr));

    sharedTextPtr = textPtr->sharedTextPtr;

    /*
     * Don't allow insertions on the last (dummy) line of the text. This is
     * the only place in this function where the index1Ptr is modified.
     */

    if (TkTextIndexGetLine(index1Ptr) == TkBTreeGetLastLine(textPtr)) {
	TkTextIndexBackChars(textPtr, index1Ptr, 1, index1Ptr, COUNT_INDICES);
    }

    /*
     * Notify the display module that lines are about to change, then do the
     * insertion. If the insertion occurs on the top line of the widget
     * (textPtr->topIndex), then we have to recompute topIndex after the
     * insertion, since the insertion could invalidate it.
     */

    if (sharedTextPtr->numPeers > sizeof(textPosBuf)/sizeof(textPosBuf[0])) {
	textPosition = (TkTextPosition *)malloc(sizeof(TkTextPosition)*sharedTextPtr->numPeers);
    } else {
	textPosition = textPosBuf;
    }
    InitPosition(sharedTextPtr, textPosition);
    FindNewTopPosition(sharedTextPtr, textPosition, index1Ptr, NULL, length);

    TkrTextChanged(sharedTextPtr, NULL, index1Ptr, index1Ptr);
    undoInfoPtr = TkTextUndoStackIsFull(sharedTextPtr->undoStack) ? NULL : &undoInfo;
    startIndex = *index1Ptr;
    TkTextIndexToByteIndex(&startIndex); /* we need the byte position after insertion */

    if (parseHyphens) {
	text = (length >= sizeof(textBuf)) ? (char *)malloc(length + 1) : textBuf;
	ParseHyphens(string, string + length, (char *) text);
    }

    TkBTreeInsertChars(sharedTextPtr->tree, index1Ptr, text, tagInfoPtr, hyphenTagPtr, undoInfoPtr);

    /*
     * Push the insertion on the undo stack, and update the modified status of the widget.
     * Try to join with previously pushed undo token, if possible.
     */

    if (undoInfoPtr) {
	const TkTextUndoSubAtom *subAtom;
	int triggerStackEvent = 0;
	int pushToken;

	assert(undoInfo.byteSize == 0);

	PushUndoSeparatorIfNeeded(sharedTextPtr, sharedTextPtr->autoSeparators, TK_TEXT_EDIT_INSERT);

	pushToken = sharedTextPtr->lastUndoTokenType != TK_TEXT_UNDO_INSERT
		|| !((subAtom = TkTextUndoGetLastUndoSubAtom(sharedTextPtr->undoStack))
			&& (triggerStackEvent = TkBTreeJoinUndoInsert(
				(TkTextUndoToken *)subAtom->item, subAtom->size, undoInfo.token, undoInfo.byteSize)));

	assert(undoInfo.token->undoType->rangeProc);
	sharedTextPtr->prevUndoStartIndex = ((TkTextUndoTokenRange *) undoInfo.token)->startIndex;
	sharedTextPtr->prevUndoEndIndex = ((TkTextUndoTokenRange *) undoInfo.token)->endIndex;
	sharedTextPtr->lastUndoTokenType = TK_TEXT_UNDO_INSERT;
	sharedTextPtr->lastEditMode = TK_TEXT_EDIT_INSERT;

	if (pushToken) {
	    TkTextPushUndoToken(sharedTextPtr, undoInfo.token, undoInfo.byteSize);
	} else {
	    assert(!undoInfo.token->undoType->destroyProc);
	    free(undoInfo.token);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	}
	if (triggerStackEvent) {
	    sharedTextPtr->undoStackEvent = 1; /* TkBTreeJoinUndoInsert didn't trigger */
	}
    }

    *index2Ptr = *index1Ptr;
    *index1Ptr = startIndex;
    UpdateModifiedFlag(sharedTextPtr, 1);
    TkTextUpdateAlteredFlag(sharedTextPtr);
    SetNewTopPosition(sharedTextPtr, textPtr, textPosition, viewUpdate);

    if (textPosition != textPosBuf) {
	free(textPosition);
    }

    /*
     * Invalidate any selection retrievals in progress, and send an event
     * that the selection changed if that is the case.
     */

    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
        if (TkBTreeCharTagged(index1Ptr, tPtr->selTagPtr)) {
            TkTextSelectionEvent(tPtr);
        }
	tPtr->abortSelections = 1;
    }

    if (parseHyphens && text != textBuf) {
	free((char *) text);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextUndoRedoCallback --
 *
 *	This function is registered with the generic undo/redo code to handle
 *	'insert' and 'delete' actions on all text widgets. We cannot perform
 *	those actions on any particular text widget, because that text widget
 *	might have been deleted by the time we get here.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Will change anything, depending on the undo token.
 *
 *----------------------------------------------------------------------
 */

static void
TriggerWatchUndoRedo(
    TkSharedText *sharedTextPtr,
    TkTextUndoToken *token,
    int isRedo,
    int isFinal,
    TkText **peers,
    int numPeers)
{
    TkTextIndex index1, index2;
    Tcl_Obj *cmdPtr;
    char buf[100];
    int i;

    assert(sharedTextPtr->triggerWatchCmd);
    assert(token->undoType->rangeProc);
    assert(token->undoType->commandProc);

    sharedTextPtr->triggerWatchCmd = 0; /* do not trigger recursively */
    token->undoType->rangeProc(sharedTextPtr, token, &index1, &index2);
    Tcl_IncrRefCount(cmdPtr = token->undoType->commandProc(sharedTextPtr, token));
    snprintf(buf, sizeof(buf), "%s", isFinal ? "yes" : "no");

    for (i = 0; i < numPeers; ++i) {
	TkText *tPtr = peers[i];

	if (tPtr->watchCmd && !(tPtr->flags & DESTROYED)) {
	    char idx[2][TK_POS_CHARS];
	    const char *info = isRedo ? "redo" : "undo";

	    TkrTextPrintIndex(tPtr, &index1, idx[0]);
	    TkrTextPrintIndex(tPtr, &index2, idx[1]);
	    TkTextTriggerWatchCmd(tPtr, info, idx[0], idx[1], Tcl_GetString(cmdPtr), buf, NULL, 0);
	}
    }

    Tcl_GuardedDecrRefCount(cmdPtr);
    sharedTextPtr->triggerWatchCmd = 1;
}

void
TextUndoRedoCallback(
    TkTextUndoStack stack,
    const TkTextUndoAtom *atom)
{
    TkSharedText *sharedTextPtr = (TkSharedText *) TkTextUndoGetContext(stack);
    TkTextUndoInfo undoInfo;
    TkTextUndoInfo redoInfo;
    TkTextUndoInfo *redoInfoPtr;
    TkTextPosition *textPosition = NULL;
    TkTextPosition textPosBuf[PIXEL_CLIENTS];
    int eventuallyRepick = 0;
    TkText *peerArr[20];
    TkText **peers = peerArr;
    TkText *tPtr;
    int i, k, countPeers = 0;

    assert(stack);

    if (sharedTextPtr->triggerWatchCmd) {
	if (sharedTextPtr->numPeers > sizeof(peerArr) / sizeof(peerArr[0])) {
	    peers = (TkText **)malloc(sharedTextPtr->numPeers * sizeof(peerArr[0]));
	}
	for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	    if (tPtr->watchCmd) {
		TkTextSaveCursorIndex(tPtr);
		peers[countPeers++] = tPtr;
		tPtr->refCount += 1;
	    }
	}
    }

    memset(&undoInfo, 0, sizeof(undoInfo));
    redoInfoPtr = TkTextUndoStackIsFull(stack) ? NULL : &redoInfo;

    for (i = atom->arraySize - 1; i >= 0; --i) {
	TkTextIndex index1, index2;
	const TkTextUndoSubAtom *subAtom = atom->array + i;
	TkTextUndoToken *token = (TkTextUndoToken *)subAtom->item;
	int isDelete = token->undoType->action == TK_TEXT_UNDO_INSERT
		|| token->undoType->action == TK_TEXT_REDO_DELETE;
	int isInsert = token->undoType->action == TK_TEXT_UNDO_DELETE
		|| token->undoType->action == TK_TEXT_REDO_INSERT;

	if (isInsert || isDelete) {
	    const TkTextUndoTokenRange *range = (const TkTextUndoTokenRange *) token;

	    if (isDelete && sharedTextPtr->triggerWatchCmd) {
		TriggerWatchUndoRedo(sharedTextPtr, token, subAtom->redo, i == 0, peers, countPeers);
	    }
	    if (!textPosition) {
		if (sharedTextPtr->numPeers > sizeof(textPosBuf)/sizeof(textPosBuf[0])) {
		    textPosition = (TkTextPosition *)malloc(sizeof(textPosition[0])*sharedTextPtr->numPeers);
		} else {
		    textPosition = textPosBuf;
		}
		InitPosition(sharedTextPtr, textPosition);
	    }
	    if (isInsert) {
		TkBTreeUndoIndexToIndex(sharedTextPtr, &range->startIndex, &index1);
		TkrTextChanged(sharedTextPtr, NULL, &index1, &index1);
		FindNewTopPosition(sharedTextPtr, textPosition, &index1, NULL, subAtom->size);
	    } else {
		token->undoType->rangeProc(sharedTextPtr, token, &index1, &index2);
		TkrTextChanged(sharedTextPtr, NULL, &index1, &index2);
		FindNewTopPosition(sharedTextPtr, textPosition, &index1, &index2, 0);
	    }
	    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
		if (!tPtr->abortSelections) {
		    if (isInsert) {
			tPtr->abortSelections = 1;
		    } else {
			if (range->startIndex.lineIndex < range->endIndex.lineIndex
				&& TkBTreeTag(sharedTextPtr, NULL, &index1, &index2,
					tPtr->selTagPtr, 0, NULL, TkTextRedrawTag)) {
			    TkTextSelectionEvent(tPtr);
			    tPtr->abortSelections = 1;
			}
		    }
		}
	    }
	}

	/*
	 * Now perform the undo/redo action.
	 */

	if (redoInfoPtr) {
	    memset(redoInfoPtr, 0, sizeof(redoInfo));
	}
	undoInfo.token = token;
	undoInfo.byteSize = atom->size;
	token->undoType->undoProc(sharedTextPtr, &undoInfo, redoInfoPtr, atom->redo);

	if (token->undoType->action == TK_TEXT_UNDO_TAG) {
	    eventuallyRepick = 1;
	}
	if (redoInfoPtr) {
	    if (redoInfo.token == token) {
		/*
		 * We are re-using a token, this is possible because the current undo token
		 * will expire after this action.
		 */
		if (!subAtom->redo) {
		    if (token->undoType->action == TK_TEXT_UNDO_INSERT
			    || token->undoType->action == TK_TEXT_UNDO_DELETE) {
			assert(sharedTextPtr->insertDeleteUndoTokenCount > 0);
			sharedTextPtr->insertDeleteUndoTokenCount -= 1;
		    }
		}
		if (token->undoType->destroyProc) {
		    /* We need a balanced call of perform/destroy. */
		    token->undoType->destroyProc(sharedTextPtr, (TkTextUndoToken *)subAtom->item, 1);
		}
		/*
		 * Do not free this item.
		 */
		((TkTextUndoSubAtom *) subAtom)->item = NULL;
	    }
	    TkTextPushUndoToken(sharedTextPtr, redoInfo.token, redoInfo.byteSize);
	}
	if (!isDelete && sharedTextPtr->triggerWatchCmd) {
	    TriggerWatchUndoRedo(sharedTextPtr, token, subAtom->redo, i == 0, peers, countPeers);
	}
    }

    if (eventuallyRepick) {
	for (k = 0; k < countPeers; ++k) {
	    TkText *tPtr = peers[k];

	    if (!(tPtr->flags & DESTROYED)) {
		TkTextEventuallyRepick(tPtr);
	    }
	}
    }

    sharedTextPtr->lastEditMode = TK_TEXT_EDIT_OTHER;
    sharedTextPtr->lastUndoTokenType = -1;
    UpdateModifiedFlag(sharedTextPtr, 0);
    TkTextUpdateAlteredFlag(sharedTextPtr);

    if (textPosition) {
	SetNewTopPosition(sharedTextPtr, NULL, textPosition, 1);
	if (textPosition != textPosBuf) {
	    free(textPosition);
	}
    }

    if (sharedTextPtr->triggerWatchCmd) {
	for (i = 0; i < countPeers; ++i) {
	    TkText *tPtr = peers[i];

	    if (!(tPtr->flags & DESTROYED)) {
		TkTextIndexClear(&tPtr->insertIndex, tPtr);
		TkTextTriggerWatchCursor(tPtr);
	    }
	    TkTextDecrRefCountAndTestIfDestroyed(tPtr);
	}
    }

    /*
     * Freeing the peer array has to be done even if sharedTextPtr->triggerWatchCmd
     * is false, possibly the user has cleared the watch command inside the trigger
     * callback.
     */

    if (peers != peerArr) {
	free(peers);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextUndoStackContentChangedCallback --
 *
 *	This function is registered with the generic undo/redo code to handle
 *	undo/redo stack changes.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
TextUndoStackContentChangedCallback(
    const TkTextUndoStack stack)
{
    ((TkSharedText *) TkTextUndoGetContext(stack))->undoStackEvent = 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TriggerUndoStackEvent --
 *
 *	This function is triggering the <<UndoStack>> event for all peers.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May force the text window (and all peers) into existence.
 *
 *----------------------------------------------------------------------
 */

static void
TriggerUndoStackEvent(
    TkSharedText *sharedTextPtr)
{
    TkText *textPtr;

    assert(sharedTextPtr->undoStackEvent);
    sharedTextPtr->undoStackEvent = 0;

    for (textPtr = sharedTextPtr->peers; textPtr; textPtr = textPtr->next) {
	if (!(textPtr->flags & DESTROYED)) {
	    Tk_MakeWindowExist(textPtr->tkwin);
	    Tk_SendVirtualEvent(textPtr->tkwin, "UndoStack", NULL);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextUndoFreeCallback --
 *
 *	This function is registered with the generic undo/redo code to handle
 *	the freeing operation of undo/redo items.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Some memory will be freed.
 *
 *----------------------------------------------------------------------
 */

static void
TextUndoFreeCallback(
    const TkTextUndoStack stack,
    const TkTextUndoSubAtom *subAtom)	/* Destroy this token. */
{
    TkTextUndoToken *token = (TkTextUndoToken *) subAtom->item;

    /*
     * Consider that the token is possibly null.
     */

    if (token) {
	TkTextUndoAction action = token->undoType->action;

	if (action == TK_TEXT_UNDO_INSERT || action == TK_TEXT_UNDO_DELETE) {
	    TkSharedText *sharedTextPtr = (TkSharedText *) TkTextUndoGetContext(stack);
	    assert(sharedTextPtr->insertDeleteUndoTokenCount > 0);
	    sharedTextPtr->insertDeleteUndoTokenCount -= 1;
	}
	if (token->undoType->destroyProc) {
	    token->undoType->destroyProc((TkSharedText *)TkTextUndoGetContext(stack), (TkTextUndoToken *)subAtom->item, 0);
	}
	free(subAtom->item);
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * CountIndices --
 *
 *	This function implements most of the functionality of the "count"
 *	widget command.
 *
 *	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
 *
 * Results:
 *	Returns the number of characters in the range.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
CountIndices(
    const TkText *textPtr,	/* Overall information about text widget. */
    const TkTextIndex *indexPtr1,
				/* Index describing location of first character to delete. */
    const TkTextIndex *indexPtr2,
				/* Index describing location of last character to delete. NULL means
				 * just delete the one character given by indexPtr1. */
    TkTextCountType type)	/* The kind of indices to count. */
{
    /*
     * Order the starting and stopping indices.
     */

    int compare = TkTextIndexCompare(indexPtr1, indexPtr2);

    if (compare == 0) {
	return 0;
    }
    if (compare > 0) {
	return -((int) TkTextIndexCount(textPtr, indexPtr2, indexPtr1, type));
    }
    return TkTextIndexCount(textPtr, indexPtr1, indexPtr2, type);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetUndeletableNewline --
 *
 *	Return pointer to undeletable newline. The search will start at
 *	start of deletion. See comments in function about the properties
 *	of an undeletable newline.
 *
 *	Note that this functions expects that the deletions end on very
 *	last line in B-Tree, otherwise the newline is always deletable.
 *
 * Results:
 *	Returns the undeletable newline, or NULL.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

const TkTextSegment *
TkTextGetUndeletableNewline(
    const TkTextLine *lastLinePtr)	/* last line of deletion, must be last line of B-Tree */
{
    assert(lastLinePtr);
    assert(!lastLinePtr->nextPtr);

#if 0 /* THIS IS OLD IMPLEMENTATION */
    const TkTextSegment *segPtr = TkTextIndexGetContentSegment(&index1, NULL);

    /*
     * Advance to next character.
     */

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

    /*
     * Assume the following text content:
     *
     *    {"1" "\n"} {"\n"} {"2" "\n"} {"\n"}
     *      A   B      C      D   E      F
     *
     * Segment E is the last newline (F belongs to addtional empty line).
     * We have two cases where the last newline has to be preserved.
     *
     * 1. Deletion is starting in first line, then we have to preserve the
     *    last newline, return segment E.
     *
     * 2. Deletion is not starting at the first character in this line, then
     *    we have to preserve the last newline, return segment E.
     *
     * In all other cases return NULL.
     */

    if (segPtr->sectionPtr->linePtr->prevPtr && SegIsAtStartOfLine(segPtr)) {
	return NULL;
    }
#endif

    /*
     * The old implementation is erroneous, and has been changed:
     *
     * 1. Test the following script with old implementation:
     *	    text .t
     *      .t insert end "1\n2"
     *      .t delete 2.0 end
     *      .t insert end "2"
     *    The result of [.t get begin end] -> "12\n" is unexpected, the expected result is "1\n2\n".
     *
     * 2. The mathematical consistency now will be preserved:
     *      - The newly created text widget is clean and contains "\e"
     *        (\e is the always existing final newline in last line).
     *      - After insertion of "1\n2" at 'begin' we have "1\n2\e".
     *      - After [.t delete 2.0 end] the deletion starts with inserted character "2",
     *        and not with the inserted newline. Thus from mathematical point of view
     *        the result must be "1\n\e" (this means: the always existing final newline
     *        will never be deleted).
     *      - After [.t insert end "2"] the string "2" has been inserted at end, this means
     *        before "\e", so the new result is "1\n2\e".
     *
     * 3. It's a clean concept if the artificial newline is undeletable, the old concept is
     *    hard to understand for a user, and error-prone.
     */

    assert(lastLinePtr->prevPtr);
    return lastLinePtr->prevPtr->lastPtr; /* return final newline \e */
}

/*
 *----------------------------------------------------------------------
 *
 * DeleteIndexRange --
 *
 *	This function implements most of the functionality of the "delete"
 *	widget command.
 *
 * Results:
 *	Returns whether the widget hasn't been destroyed.
 *
 * Side effects:
 *	Characters and other entities (windows, images) get deleted from the
 *	text.
 *
 *	If 'viewUpdate' is 1, we may adjust the window contents'
 *	y-position, and scrollbar setting.
 *
 *	If 'viewUpdate' is 1, true we can guarantee that textPtr->topIndex
 *	points to a valid TkTextLine after this function returns. However, if
 *	'viewUpdate' is false, then there is no such guarantee (since
 *	topIndex.linePtr can be garbage). The caller is expected to take
 *	actions to ensure the topIndex is validated before laying out the
 *	window again.
 *
 *----------------------------------------------------------------------
 */

static int
DeleteOnLastLine(
    TkSharedText *sharedTextPtr,
    const TkTextLine *lastLinePtr,
    int flags) /* deletion flags */
{
	(void)sharedTextPtr;
    assert(lastLinePtr);
    assert(!lastLinePtr->nextPtr);

    if (flags & DELETE_MARKS) {
	const TkTextSegment *segPtr = lastLinePtr->segPtr;

	while (segPtr->size == 0) {
	    if ((flags & DELETE_MARKS) && TkTextIsNormalMark(segPtr)) {
		return 1;
	    }
	    segPtr = segPtr->nextPtr;
	}
    }

    return 0;
}

static int
DeleteEndMarker(
    const TkTextIndex *indexPtr,
    int flags)
{
    const TkTextSegment *segPtr;

    return (flags & DELETE_MARKS)
	    && (segPtr = TkTextIndexGetSegment(indexPtr))
	    && TkTextIsNormalMark(segPtr);
}

static int
DeleteIndexRange(
    TkSharedText *sharedTextPtr,/* Shared portion of peer widgets. */
    TkText *textPtr,		/* Overall information about text widget. */
    const TkTextIndex *indexPtr1,
				/* Index describing location of first character (or other entity)
				 * to delete. */
    const TkTextIndex *indexPtr2,
				/* Index describing location of last character (or other entity)
				 * to delete. NULL means just delete the one character given by
				 * indexPtr1. */
    int flags,			/* Flags controlling the deletion. */
    int viewUpdate,		/* Update vertical view if set. */
    int triggerWatchDelete,	/* Should we trigger the watch command for deletion? */
    int triggerWatchInsert,	/* Should we trigger the watch command for insertion? */
    int userFlag,		/* Trigger user modification? */
    int final)			/* This is the final call in a sequence of ranges. */
{
    TkTextIndex index1, index2, index3;
    TkTextPosition *textPosition;
    TkTextPosition textPosBuf[PIXEL_CLIENTS];
    TkTextUndoInfo undoInfo;
    TkTextUndoInfo *undoInfoPtr;
    TkTextLine *lastLinePtr;

    if (!sharedTextPtr) {
	sharedTextPtr = textPtr->sharedTextPtr;
    }

    if (triggerWatchInsert) {
	TkTextIndexToByteIndex((TkTextIndex *) indexPtr1); /* mutable due to concept */
    }

    if (TkTextIndexIsEndOfText(indexPtr1)) {
	return 1; /* nothing to delete */
    }

    /*
     * Prepare the starting and stopping indices.
     */

    if (indexPtr2) {
	if (TkTextIndexCompare(indexPtr1, indexPtr2) >= 0) {
	    return 1; /* there is nothing to delete */
	}
	index1 = *indexPtr1;
	index2 = *indexPtr2;
    } else if (!TkTextIndexForwChars(textPtr, indexPtr1, 1, &index2, COUNT_INDICES)) {
	return 1;
    } else {
	index1 = *indexPtr1;
    }

    index3 = index2;

    if (!TkTextIndexGetLine(&index2)->nextPtr
	    && !DeleteEndMarker(&index2, flags)
	    && TkTextGetUndeletableNewline(lastLinePtr = TkTextIndexGetLine(&index2))
	    && !DeleteOnLastLine(sharedTextPtr, lastLinePtr, flags)) {
	/*
	 * This is a very special case. If the last newline is undeletable, we do not
	 * have a deletable marker at end of range, and there is no deletable mark on
	 * last line, then decrement the end of range.
	 */

	TkrTextIndexBackBytes(textPtr, &index2, 1, &index2);

	if (TkTextIndexIsEqual(&index1, &index2)) {
	    if (lastLinePtr->prevPtr) {
		if (lastLinePtr->prevPtr->lastPtr->tagInfoPtr != sharedTextPtr->emptyTagInfoPtr) {
		    /* we have to delete tags on previous newline, that's all */
		    TkTextClearSelection(sharedTextPtr, &index1, &index3);
		    TkTextClearTags(sharedTextPtr, textPtr, &index1, &index3, 0);
		} else {
		    assert(TkTextTagSetIsEmpty(lastLinePtr->prevPtr->lastPtr->tagInfoPtr));
		}
	    }
	    return 1; /* nothing to do */
	}

	if (lastLinePtr->prevPtr->lastPtr->tagInfoPtr != sharedTextPtr->emptyTagInfoPtr) {
	    if (!TkTextTagBitContainsSet(sharedTextPtr->selectionTags,
		    lastLinePtr->prevPtr->lastPtr->tagInfoPtr)) {
		/*
		 * Last newline is tagged with any non-selection tag, so we have to
		 * re-include this character.
		 */
		flags |= DELETE_LASTLINE;
		index2 = index3;
	    }
	}
    }

    /*
     * Call the "watch" command for deletion. Take into account that the
     * receiver might change the text content inside the callback, although
     * he shouldn't do this.
     */

    if (triggerWatchDelete) {
	Tcl_Obj *delObj = TextGetText(textPtr, &index1, &index2, NULL, NULL, UINT_MAX, 0, 1);
	char const *deleted = Tcl_GetString(delObj);
	int unchanged;
	int rc;

	TkTextIndexSave(&index1);
	TkTextIndexSave(&index2);
	Tcl_IncrRefCount(delObj);
	rc = TriggerWatchEdit(textPtr, userFlag, "delete", &index1, &index2, deleted, final);
	Tcl_GuardedDecrRefCount(delObj);
	unchanged = TkTextIndexRebuild(&index1) && TkTextIndexRebuild(&index2);

	if (!rc) { return 0; } /* the receiver has destroyed this widget */

	if (!unchanged && TkTextIndexCompare(&index1, &index2) >= 0) {
	    /* This can only happen if the receiver of the trigger command did any modification. */
	    return 1;
	}
    }

    TkTextClearSelection(sharedTextPtr, &index1, &index3);

    /*
     * Tell the display what's about to happen, so it can discard obsolete
     * display information, then do the deletion. Also, if the deletion
     * involves the top line on the screen, then we have to reset the view
     * (the deletion will invalidate textPtr->topIndex). Compute what the new
     * first character will be, then do the deletion, then reset the view.
     */

    TkrTextChanged(sharedTextPtr, NULL, &index1, &index2);

    if (sharedTextPtr->numPeers > sizeof(textPosBuf)/sizeof(textPosBuf[0])) {
	textPosition = (TkTextPosition *)malloc(sizeof(textPosition[0])*sharedTextPtr->numPeers);
    } else {
	textPosition = textPosBuf;
    }
    InitPosition(sharedTextPtr, textPosition);
    FindNewTopPosition(sharedTextPtr, textPosition, &index1, &index2, 0);

    undoInfoPtr = TkTextUndoStackIsFull(sharedTextPtr->undoStack) ? NULL : &undoInfo;
    TkBTreeDeleteIndexRange(sharedTextPtr, &index1, &index2, flags, undoInfoPtr);

    /*
     * Push the deletion onto the undo stack, and update the modified status of the widget.
     * Try to join with previously pushed undo token, if possible.
     */

    if (undoInfoPtr) {
	const TkTextUndoSubAtom *subAtom;

	PushUndoSeparatorIfNeeded(sharedTextPtr, sharedTextPtr->autoSeparators, TK_TEXT_EDIT_DELETE);

	if (TkTextUndoGetMaxSize(sharedTextPtr->undoStack) == 0
		|| TkTextUndoGetCurrentSize(sharedTextPtr->undoStack) + undoInfo.byteSize
			<= TkTextUndoGetMaxSize(sharedTextPtr->undoStack)) {
	    if (sharedTextPtr->lastUndoTokenType != TK_TEXT_UNDO_DELETE
		    || !((subAtom = TkTextUndoGetLastUndoSubAtom((TkTextUndoStack)sharedTextPtr->undoStack))
			    && TkBTreeJoinUndoDelete((TkTextUndoToken *)subAtom->item, subAtom->size,
				    undoInfo.token, undoInfo.byteSize))) {
		TkTextPushUndoToken(sharedTextPtr, undoInfo.token, undoInfo.byteSize);
	    }
	    sharedTextPtr->lastUndoTokenType = TK_TEXT_UNDO_DELETE;
	    sharedTextPtr->prevUndoStartIndex =
		    ((TkTextUndoTokenRange *) undoInfo.token)->startIndex;
	    sharedTextPtr->prevUndoEndIndex = ((TkTextUndoTokenRange *) undoInfo.token)->endIndex;
	    /* stack has changed anyway, but TkBTreeJoinUndoDelete didn't trigger */
	    sharedTextPtr->undoStackEvent = 1;
	} else {
	    assert(undoInfo.token->undoType->destroyProc);
	    undoInfo.token->undoType->destroyProc(sharedTextPtr, undoInfo.token, 0);
	    free(undoInfo.token);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	}

	sharedTextPtr->lastEditMode = TK_TEXT_EDIT_DELETE;
    }

    UpdateModifiedFlag(sharedTextPtr, 1);
    TkTextUpdateAlteredFlag(sharedTextPtr);
    SetNewTopPosition(sharedTextPtr, textPtr, textPosition, viewUpdate);

    if (textPosition != textPosBuf) {
	free(textPosition);
    }

    /*
     * Lastly, trigger the "watch" command for insertion. This must be the last action,
     * probably the receiver is calling some widget commands inside the callback.
     */

    if (triggerWatchInsert) {
	if (!TriggerWatchEdit(textPtr, userFlag, "insert", indexPtr1, indexPtr1, NULL, final)) {
	    return 0; /* widget has been destroyed */
	}
    }

    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TextFetchSelection --
 *
 *	This function is called back by Tk when the selection is requested by
 *	someone. It returns part or all of the selection in a buffer provided
 *	by the caller.
 *
 * Results:
 *	The return value is the number of non-NULL bytes stored at buffer.
 *	Buffer is filled (or partially filled) with a NULL-terminated string
 *	containing part or all of the selection, as given by offset and
 *	maxBytes.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static TkSizeT
TextFetchSelection(
    ClientData clientData,	/* Information about text widget. */
    TkSizeT offset,			/* Offset within selection of first character to be returned. */
    char *buffer,		/* Location in which to place selection. */
    TkSizeT maxBytes)		/* Maximum number of bytes to place at buffer, not including
    				 * terminating NULL character. */
{
    TkText *textPtr = (TkText *)clientData;
    TkTextSearch *searchPtr;
    Tcl_Obj *selTextPtr;
    int numBytes;

    if ((!textPtr->exportSelection) || Tcl_IsSafe(textPtr->interp)) {
	return TCL_INDEX_NONE;
    }

    /*
     * Find the beginning of the next range of selected text. Note: if the
     * selection is being retrieved in multiple pieces (offset != 0) and some
     * modification has been made to the text that affects the selection then
     * reject the selection request (make 'em start over again).
     */

    if (offset == 0) {
	TkTextIndexSetupToStartOfText(&textPtr->selIndex, textPtr, textPtr->sharedTextPtr->tree);
	textPtr->abortSelections = 0;
    } else if (textPtr->abortSelections) {
	return 0;
    }

    searchPtr = &textPtr->selSearch;

    if (offset == 0 || !TkBTreeCharTagged(&textPtr->selIndex, textPtr->selTagPtr)) {
	TkTextIndex eof;

	TkTextIndexSetupToEndOfText(&eof, textPtr, textPtr->sharedTextPtr->tree);
	TkBTreeStartSearch(&textPtr->selIndex, &eof, textPtr->selTagPtr, searchPtr, SEARCH_NEXT_TAGON);
	if (!TkBTreeNextTag(searchPtr)) {
	    return offset == 0 ? TCL_INDEX_NONE : 0;
	}
	textPtr->selIndex = searchPtr->curIndex;

	/*
	 * Find the end of the current range of selected text.
	 */

	if (!TkBTreeNextTag(searchPtr)) {
	    assert(!"TextFetchSelection couldn't find end of range");
	}
    } else {
	/* we are still inside tagged range */
    }

    /*
     * Iterate through the the selected ranges and collect the text content.
     *
     * NOTE:
     * The crux with TextFetchSelection is the old interface of this callback function,
     * it does not fit with the object design (Tcl_Obj), otherwise it would expect an
     * object as the result. Thus the actual "natural" implementation is a bit
     * ineffecient, because we are collecting the data with an object (we are using the
     * "get" mechanism), and afterwards the content of this object will be copied into
     * the buffer, and the object will be destroyed. Hopefully some day function
     * TextFetchSelection will be changed to new object design.
     */

    Tcl_IncrRefCount(selTextPtr = Tcl_NewObj());

    while (1) {
	TextGetText(textPtr, &textPtr->selIndex, &searchPtr->curIndex, &textPtr->selIndex,
		selTextPtr, maxBytes - GetByteLength(selTextPtr), 1, 0);

	if (GetByteLength(selTextPtr) == maxBytes) {
	    break;
	}

	/*
	 * Find the beginning of the next range of selected text.
	 */

	if (!TkBTreeNextTag(searchPtr)) {
	    break;
	}

	textPtr->selIndex = searchPtr->curIndex;

	/*
	 * Find the end of the current range of selected text.
	 */

	if (!TkBTreeNextTag(searchPtr)) {
	    assert(!"TextFetchSelection couldn't find end of range");
	}
    }

    numBytes = GetByteLength(selTextPtr);
    memcpy(buffer, Tcl_GetString(selTextPtr), numBytes);
    Tcl_GuardedDecrRefCount(selTextPtr);
    return numBytes;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextSelectionEvent --
 *
 *	When anything relevant to the "sel" tag has been changed, call this
 *	function to generate a <<Selection>> event.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	If <<Selection>> bindings are present, they will trigger.
 *
 *----------------------------------------------------------------------
 */

void
TkTextSelectionEvent(
    TkText *textPtr)
{
    /*
     * Send an event that the selection changed. This is equivalent to:
     *     event generate $textWidget <<Selection>>
     */

    Tk_SendVirtualEvent(textPtr->tkwin, "Selection", NULL);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextLostSelection --
 *
 *	This function is called back by Tk when the selection is grabbed away
 *	from a text widget. On Windows and Mac systems, we want to remember
 *	the selection for the next time the focus enters the window. On Unix,
 *	just remove the "sel" tag from everything in the widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The "sel" tag is cleared from the window.
 *
 *----------------------------------------------------------------------
 */

void
TkTextLostSelection(
    ClientData clientData)	/* Information about text widget. */
{
    TkText *textPtr = (TkText *)clientData;

    if (Tk_AlwaysShowSelection(textPtr->tkwin)) {
	TkTextIndex start, end;

	if ((!textPtr->exportSelection) || Tcl_IsSafe(textPtr->interp)) {
	    return;
	}

	/*
	 * On Windows and Mac systems, we want to remember the selection for
	 * the next time the focus enters the window. On Unix, just remove the
	 * "sel" tag from everything in the widget.
	 */

	TkTextIndexSetupToStartOfText(&start, textPtr, textPtr->sharedTextPtr->tree);
	TkTextIndexSetupToEndOfText(&end, textPtr, textPtr->sharedTextPtr->tree);
	TkBTreeTag(textPtr->sharedTextPtr, textPtr, &start, &end, textPtr->selTagPtr,
		0, NULL, TkTextRedrawTag);
    }

    /*
     * Send an event that the selection changed. This is equivalent to:
     *	   event generate $textWidget <<Selection>>
     */

    TkTextSelectionEvent(textPtr);

    textPtr->flags &= ~GOT_SELECTION;
}

/*
 *----------------------------------------------------------------------
 *
 * TextBlinkProc --
 *
 *	This function is called as a timer handler to blink the insertion
 *	cursor off and on.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The cursor gets turned on or off, redisplay gets invoked, and this
 *	function reschedules itself.
 *
 *----------------------------------------------------------------------
 */

static void
TextBlinkProc(
    ClientData clientData)	/* Pointer to record describing text. */
{
    TkText *textPtr = (TkText *)clientData;
    unsigned oldFlags = textPtr->flags;

    if (textPtr->state == TK_TEXT_STATE_DISABLED
	    || !(textPtr->flags & HAVE_FOCUS)
	    || textPtr->insertOffTime == 0) {
	if (!(textPtr->flags & HAVE_FOCUS) && textPtr->insertUnfocussed != TK_TEXT_INSERT_NOFOCUS_NONE) {
	    /*
	     * The widget doesn't have the focus yet it is configured to
	     * display the cursor when it doesn't have the focus. Act now!
	     */

	    textPtr->flags |= INSERT_ON;
	} else if (textPtr->insertOffTime == 0) {
	    /*
	     * The widget was configured to have zero offtime while the
	     * insertion point was not displayed. We have to display it once.
	     */

	    textPtr->flags |= INSERT_ON;
	}
    } else {
	if (textPtr->flags & INSERT_ON) {
	    textPtr->flags &= ~INSERT_ON;
	    textPtr->insertBlinkHandler = Tcl_CreateTimerHandler(
		    textPtr->insertOffTime, TextBlinkProc, textPtr);
	} else {
	    textPtr->flags |= INSERT_ON;
	    textPtr->insertBlinkHandler = Tcl_CreateTimerHandler(
		    textPtr->insertOnTime, TextBlinkProc, textPtr);
	}
    }

    if (oldFlags != textPtr->flags) {
	int x, y, w, h;

	if (TkTextGetCursorBbox(textPtr, &x, &y, &w, &h)) {
	    int inset = textPtr->borderWidth + textPtr->highlightWidth;
	    TkTextRedrawRegion(textPtr, x + inset, y + inset, w, h);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextInsertCmd --
 *
 *	This function is invoked to process the "insert" and "replace" widget
 *	commands for text widgets.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *	If 'viewUpdate' is true, we may adjust the window contents'
 *	y-position, and scrollbar setting.
 *
 *----------------------------------------------------------------------
 */

static int
TextInsertCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[],	/* Argument objects. */
    const TkTextIndex *indexPtr,/* Index at which to insert. */
    int viewUpdate,		/* Update the view if set. */
    int triggerWatchDelete,	/* Should we trigger the watch command for deletion? */
    int triggerWatchInsert,	/* Should we trigger the watch command for insertion? */
    int userFlag,		/* Trigger user modification? */
    int parseHyphens)		/* Should we parse hyphens? (tk_textInsert) */
{
    TkTextIndex index1, index2;
    TkSharedText *sharedTextPtr;
    TkTextTag *hyphenTagPtr = NULL;
    int rc = TCL_OK;
    int j;

    assert(textPtr);
    assert(!TkTextIsDeadPeer(textPtr));

    sharedTextPtr = textPtr->sharedTextPtr;

    if (parseHyphens && objc > 1 && *Tcl_GetString(objv[0]) == '-') {
	int argc;
	Tcl_Obj **argv;

	if (strcmp(Tcl_GetString(objv[0]), "-hyphentags") != 0) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "bad option \"%s\": must be -hyphentags", Tcl_GetString(objv[0])));
	    Tcl_SetErrorCode(interp, "TK", "TEXT", "INDEX_OPTION", NULL);
	    return TCL_ERROR;
	}
	if (Tcl_ListObjGetElements(interp, objv[1], &argc, &argv) != TCL_OK) {
	    return TCL_ERROR;
	}
	for (j = 0; j < argc; ++j) {
	    TkTextTag *tagPtr = TkTextCreateTag(textPtr, Tcl_GetString(argv[j]), NULL);
	    tagPtr->nextPtr = hyphenTagPtr;
	    hyphenTagPtr = tagPtr;
	}
	objc -= 2;
	objv += 2;
    }

    for (j = 0; j < objc && GetByteLength(objv[j]) == 0; j += 2) {
	/* empty loop body */
    }
    index1 = *indexPtr;

    while (j < objc) {
	Tcl_Obj *stringPtr = objv[j];
	Tcl_Obj *tagPtr = (j + 1 < objc) ? objv[j + 1] : NULL;
	char const *string = Tcl_GetString(stringPtr);
	unsigned length = GetByteLength(stringPtr);
	int k = j + 2;
	int final;

	while (k < objc && GetByteLength(objv[k]) == 0) {
	    k += 2;
	}
	final = objc <= k;

	if (length > 0) {
	    int numTags = 0;
	    Tcl_Obj **tagNamePtrs = NULL;
	    TkTextTagSet *tagInfoPtr = NULL;

	    /*
	     * Call the "watch" command for deletion. Take into account that the
	     * receiver might change the text content, although he shouldn't do this.
	     */

	    if (triggerWatchDelete) {
		TkTextIndexSave(&index1);
		if (!TriggerWatchEdit(textPtr, userFlag, "delete", &index1, &index1, NULL, final)) {
		    return rc;
		}
		TkTextIndexRebuild(&index1);
	    }

	    if (tagPtr) {
		int i;

		if (Tcl_ListObjGetElements(interp, tagPtr, &numTags, &tagNamePtrs) != TCL_OK) {
		    rc = TCL_ERROR;
		} else if (numTags > 0) {
		    TkTextTag *tagPtr;

		    tagInfoPtr = TkTextTagSetResize(NULL, sharedTextPtr->tagInfoSize);

		    for (i = 0; i < numTags; ++i) {
			tagPtr = TkTextCreateTag(textPtr, Tcl_GetString(tagNamePtrs[i]), NULL);
			if (tagPtr->index >= TkTextTagSetSize(tagInfoPtr)) {
			    tagInfoPtr = TkTextTagSetResize(tagInfoPtr, sharedTextPtr->tagInfoSize);
			}
			tagInfoPtr = TkTextTagSetAddToThis(tagInfoPtr, tagPtr->index);
		    }
		}
	    }

	    InsertChars(textPtr, &index1, &index2, string, length,
		    viewUpdate, tagInfoPtr, hyphenTagPtr, parseHyphens);
	    if (tagInfoPtr) {
		TkTextTagSetDecrRefCount(tagInfoPtr);
	    }

	    /*
	     * Lastly, trigger the "watch" command for insertion. This must be the last action,
	     * probably the receiver is calling some widget commands inside the callback.
	     */

	    if (triggerWatchInsert) {
		if (!TriggerWatchEdit(textPtr, userFlag, "insert", &index1, &index2, string, final)) {
		    return rc;
		}
	    }

	    if (rc != TCL_OK) {
		return rc;
	    }
	    index1 = index2;
	}

	j = k;
    }

    return rc;
}

/*
 *----------------------------------------------------------------------
 *
 * TextSearchCmd --
 *
 *	This function is invoked to process the "search" widget command for
 *	text widgets. See the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *----------------------------------------------------------------------
 */

static int
TextSearchCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    int i, argsLeft, code;
    SearchSpec searchSpec;

    static const char *const switchStrings[] = {
	"-hidden",
	"--", "-all", "-backwards", "-count", "-discardhyphens", "-elide",
	"-exact", "-forwards", "-nocase", "-nolinestop", "-overlap", "-regexp",
	"-strictlimits", NULL
    };
    enum SearchSwitches {
	TK_TEXT_SEARCH_HIDDEN, TK_TEXT_SEARCH_END, TK_TEXT_SEARCH_ALL, TK_TEXT_SEARCH_BACK,
	TK_TEXT_SEARCH_COUNT, TK_TEXT_SEARCH_DISCARDHYPHENS, TK_TEXT_SEARCH_ELIDE, TK_TEXT_SEARCH_EXACT,
	TK_TEXT_SEARCH_FWD, TK_TEXT_SEARCH_NOCASE, TK_TEXT_SEARCH_NOLINESTOP, TK_TEXT_SEARCH_OVERLAP,
	TK_TEXT_SEARCH_REGEXP, TK_TEXT_SEARCH_STRICTLIMITS
    };

    /*
     * Set up the search specification, including the last 4 fields which are
     * text widget specific.
     */

    searchSpec.textPtr = textPtr;
    searchSpec.exact = 1;
    searchSpec.noCase = 0;
    searchSpec.all = 0;
    searchSpec.backwards = 0;
    searchSpec.varPtr = NULL;
    searchSpec.countPtr = NULL;
    searchSpec.resPtr = NULL;
    searchSpec.searchElide = 0;
    searchSpec.searchHyphens = 1;
    searchSpec.noLineStop = 0;
    searchSpec.overlap = 0;
    searchSpec.strictLimits = 0;
    searchSpec.numLines = TkrBTreeNumLines(textPtr->sharedTextPtr->tree, textPtr);
    searchSpec.clientData = textPtr;
    searchSpec.addLineProc = &TextSearchAddNextLine;
    searchSpec.foundMatchProc = &TextSearchFoundMatch;
    searchSpec.lineIndexProc = &TextSearchGetLineIndex;

    /*
     * Parse switches and other arguments.
     */

    for (i = 2; i < objc; ++i) {
	int index;

	if (Tcl_GetString(objv[i])[0] != '-') {
	    break;
	}

	if (Tcl_GetIndexFromObjStruct(NULL, objv[i], switchStrings,
		sizeof(char *), "switch", 0, &index) != TCL_OK) {
	    /*
	     * Hide the -hidden option, generating the error description with
	     * the side effects of T_GIFO.
	     */

	    (void) Tcl_GetIndexFromObjStruct(interp, objv[i], switchStrings + 1,
		    sizeof(char *), "switch", 0, &index);
	    return TCL_ERROR;
	}

	switch ((enum SearchSwitches) index) {
	case TK_TEXT_SEARCH_END:
	    i += 1;
	    goto endOfSwitchProcessing;
	case TK_TEXT_SEARCH_ALL:
	    searchSpec.all = 1;
	    break;
	case TK_TEXT_SEARCH_BACK:
	    searchSpec.backwards = 1;
	    break;
	case TK_TEXT_SEARCH_COUNT:
	    if (i >= objc - 1) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("no value given for \"-count\" option", -1));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "VALUE", NULL);
		return TCL_ERROR;
	    }
	    i += 1;

	    /*
	     * Assumption objv[i] isn't going to disappear on us during this
	     * function, which is fair.
	     */

	    searchSpec.varPtr = objv[i];
	    break;
	case TK_TEXT_SEARCH_DISCARDHYPHENS:
	    searchSpec.searchHyphens = 0;
	    break;
	case TK_TEXT_SEARCH_ELIDE:
	case TK_TEXT_SEARCH_HIDDEN:
	    searchSpec.searchElide = 1;
	    break;
	case TK_TEXT_SEARCH_EXACT:
	    searchSpec.exact = 1;
	    break;
	case TK_TEXT_SEARCH_FWD:
	    searchSpec.backwards = 0;
	    break;
	case TK_TEXT_SEARCH_NOCASE:
	    searchSpec.noCase = 1;
	    break;
	case TK_TEXT_SEARCH_NOLINESTOP:
	    searchSpec.noLineStop = 1;
	    break;
	case TK_TEXT_SEARCH_OVERLAP:
	    searchSpec.overlap = 1;
	    break;
	case TK_TEXT_SEARCH_STRICTLIMITS:
	    searchSpec.strictLimits = 1;
	    break;
	case TK_TEXT_SEARCH_REGEXP:
	    searchSpec.exact = 0;
	    break;
	default:
	    assert(!"unexpected switch fallthrough");
	}
    }
  endOfSwitchProcessing:

    argsLeft = objc - (i + 2);
    if (argsLeft != 0 && argsLeft != 1) {
	Tcl_WrongNumArgs(interp, 2, objv, "?switches? pattern index ?stopIndex?");
	return TCL_ERROR;
    }

    if (searchSpec.noLineStop && searchSpec.exact) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"the \"-nolinestop\" option requires the \"-regexp\" option to be present", -1));
	Tcl_SetErrorCode(interp, "TK", "TEXT", "SEARCH_USAGE", NULL);
	return TCL_ERROR;
    }

    if (searchSpec.overlap && !searchSpec.all) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"the \"-overlap\" option requires the \"-all\" option to be present", -1));
	Tcl_SetErrorCode(interp, "TK", "TEXT", "SEARCH_USAGE", NULL);
	return TCL_ERROR;
    }

    /*
     * Scan through all of the lines of the text circularly, starting at the
     * given index. 'objv[i]' is the pattern which may be an exact string or a
     * regexp pattern depending on the flags set above.
     */

    code = SearchPerform(interp, &searchSpec, objv[i], objv[i + 1], argsLeft == 1 ? objv[i + 2] : NULL);
    if (code != TCL_OK) {
	goto cleanup;
    }

    /*
     * Set the '-count' variable, if given.
     */

    if (searchSpec.varPtr && searchSpec.countPtr) {
	Tcl_IncrRefCount(searchSpec.countPtr);
	if (!Tcl_ObjSetVar2(interp, searchSpec.varPtr, NULL, searchSpec.countPtr, TCL_LEAVE_ERR_MSG)) {
	    code = TCL_ERROR;
	    goto cleanup;
	}
    }

    /*
     * Set the result.
     */

    if (searchSpec.resPtr) {
	Tcl_SetObjResult(interp, searchSpec.resPtr);
    }

  cleanup:
    if (searchSpec.countPtr) {
	Tcl_GuardedDecrRefCount(searchSpec.countPtr);
    }
    if (searchSpec.resPtr) {
	Tcl_GuardedDecrRefCount(searchSpec.resPtr);
    }
    return code;
}

/*
 *----------------------------------------------------------------------
 *
 * TextSearchGetLineIndex --
 *
 *	Extract a row, text offset index position from an objPtr.
 *
 *	This means we ignore any embedded windows/images and elidden text
 *	(unless we are searching that).
 *
 * Results:
 *	Standard Tcl error code (with a message in the interpreter on error
 *	conditions).
 *
 *	The offset placed in offsetPosPtr is a utf-8 char* byte index for
 *	exact searches, and a Unicode character index for regexp searches.
 *
 *	The line number should start at zero (searches which wrap around
 *	assume the first line is numbered 0).
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
TextSearchGetLineIndex(
    Tcl_Interp *interp,		/* For error messages. */
    Tcl_Obj *objPtr,		/* Contains a textual index like "1.2" */
    SearchSpec *searchSpecPtr,	/* Contains other search parameters. */
    int *linePosPtr,		/* For returning the line number. */
    int *offsetPosPtr)		/* For returning the text offset in the line. */
{
    TkTextIndex index;
    int line, byteIndex;
    TkText *textPtr = (TkText *)searchSpecPtr->clientData;
    TkTextLine *linePtr;

    if (!TkTextGetIndexFromObj(interp, textPtr, objPtr, &index)) {
	return TCL_ERROR;
    }

    assert(textPtr);
    line = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, TkTextIndexGetLine(&index), NULL);
    if (line >= searchSpecPtr->numLines) {
	line = searchSpecPtr->numLines - 1;
	linePtr = TkBTreeFindLine(textPtr->sharedTextPtr->tree, textPtr, line);
	assert(linePtr); /* this may only fail with dead peers */
	if (textPtr->endMarker == textPtr->sharedTextPtr->endMarker
		|| textPtr->endMarker->sectionPtr->linePtr != TkTextIndexGetLine(&index)) {
	    byteIndex = linePtr->size;
	} else {
	    byteIndex = TkTextSegToIndex(textPtr->endMarker);
	}
    } else {
	linePtr = TkTextIndexGetLine(&index);
	byteIndex = TkTextIndexGetByteIndex(&index);
    }

    *offsetPosPtr = TextSearchIndexInLine(searchSpecPtr, linePtr, byteIndex);
    *linePosPtr = line;

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TextSearchIndexInLine --
 *
 *	Find textual index of 'byteIndex' in the searchable characters of
 *	'linePtr'.
 *
 *	This means we ignore any embedded windows/images and elidden text
 *	(unless we are searching that).
 *
 * Results:
 *	The returned index is a utf-8 char* byte index for exact searches, and
 *	a Unicode character index for regexp searches.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

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

static unsigned
TextSearchIndexInLine(
    const SearchSpec *searchSpecPtr,
				/* Search parameters. */
    TkTextLine *linePtr,	/* The line we're looking at. */
    int byteIndex)		/* Index into the line. */
{
    TkTextSegment *segPtr;
    int leftToScan;
    unsigned index = 0;
    TkText *textPtr = (TkText *)searchSpecPtr->clientData;
    TkTextLine *startLinePtr = textPtr->startMarker->sectionPtr->linePtr;
    int isCharSeg;

    index = 0;
    segPtr = (startLinePtr == linePtr) ? textPtr->startMarker : linePtr->segPtr;

    /*
     * TODO: Use new elide structure, but this requires a redesign of the whole
     * search algorithm.
     */

    for (leftToScan = byteIndex; leftToScan > 0; segPtr = segPtr->nextPtr) {
	if ((isCharSeg = segPtr->typePtr == &tkTextCharType)
		|| (searchSpecPtr->searchHyphens && segPtr->typePtr == &tkTextHyphenType)) {
	    if (searchSpecPtr->searchElide || !TkTextSegmentIsElided(textPtr, segPtr)) {
		if (leftToScan < segPtr->size) {
		    if (searchSpecPtr->exact) {
			index += leftToScan;
		    } else {
			index += isCharSeg ? Tcl_NumUtfChars(segPtr->body.chars, leftToScan) : 1;
		    }
		} else if (searchSpecPtr->exact) {
		    index += isCharSeg ? segPtr->size : 2;
		} else {
		    index += isCharSeg ? CountCharsInSeg(segPtr) : 1;
		}
	    }
	}
	leftToScan -= segPtr->size;
    }

    return index;
}

/*
 *----------------------------------------------------------------------
 *
 * TextSearchAddNextLine --
 *
 *	Adds a line from the text widget to the object 'theLine'.
 *
 * Results:
 *	A pointer to the TkTextLine corresponding to the given line, or NULL
 *	if there was no available line.
 *
 *	Also 'lenPtr' (if non-NULL) is filled in with the total length of
 *	'theLine' (not just what we added to it, but the length including what
 *	was already in there). This is in bytes for an exact search and in
 *	chars for a regexp search.
 *
 *	Also 'extraLinesPtr' (if non-NULL) will have its value incremented by
 *	1 for each additional logical line we have added because a newline is
 *	elided (this will only ever happen if we have chosen not to search
 *	elided text, of course).
 *
 * Side effects:
 *	Memory may be allocated or re-allocated for theLine's string
 *	representation.
 *
 *----------------------------------------------------------------------
 */

static ClientData
TextSearchAddNextLine(
    int lineNum,		/* Line we must add. */
    SearchSpec *searchSpecPtr,	/* Search parameters. */
    Tcl_Obj *theLine,		/* Object to append to. */
    int *lenPtr,		/* For returning the total length. */
    int *extraLinesPtr)		/* If non-NULL, will have its value
				 * incremented by the number of additional
				 * logical lines which are merged into this
				 * one by newlines being elided. */
{
    TkTextLine *linePtr, *thisLinePtr;
    TkTextSegment *segPtr, *lastPtr;
    TkText *textPtr = (TkText *)searchSpecPtr->clientData;
    TkTextLine *startLinePtr = textPtr->startMarker->sectionPtr->linePtr;
    TkTextLine *endLinePtr = textPtr->endMarker->sectionPtr->linePtr;
    int nothingYet = 1;

    /*
     * Extract the text from the line.
     */

    if (!(linePtr = TkBTreeFindLine(textPtr->sharedTextPtr->tree, textPtr, lineNum))) {
	return NULL;
    }
    thisLinePtr = linePtr;

    while (thisLinePtr) {
	int elideWraps = 0;

	segPtr = (startLinePtr == thisLinePtr) ? textPtr->startMarker : thisLinePtr->segPtr;
	lastPtr = (endLinePtr == thisLinePtr) ? textPtr->endMarker : NULL;

	/*
	 * TODO: Use new elide structure, but this requires a redesign of the whole
	 * search algorithm.
	 */

	for ( ; segPtr != lastPtr; segPtr = segPtr->nextPtr) {
	    if (segPtr->typePtr == &tkTextCharType
		    || (searchSpecPtr->searchHyphens && segPtr->typePtr == &tkTextHyphenType)) {
		if (!searchSpecPtr->searchElide && TkTextSegmentIsElided(textPtr, segPtr)) {
		    /*
		     * If we reach the end of the logical line, and if we have at
		     * least one character in the string, then we continue
		     * wrapping to the next logical line. If there are no
		     * characters yet, then the entire line of characters is
		     * elided and there's no need to complicate matters by
		     * wrapping - we'll look at the next line in due course.
		     */

		    if (!segPtr->nextPtr && !nothingYet) {
			elideWraps = 1;
		    }
		} else if (segPtr->typePtr == &tkTextCharType) {
		    Tcl_AppendToObj(theLine, segPtr->body.chars, segPtr->size);
		    nothingYet = 0;
		} else {
		    Tcl_AppendToObj(theLine, "\xc2\xad", 2); /* U+00AD */
		    nothingYet = 0;
		}
	    }
	}
	if (!elideWraps) {
	    break;
	}
	lineNum += 1;
	if (lineNum >= searchSpecPtr->numLines) {
	    break;
	}
	thisLinePtr = TkBTreeNextLine(textPtr, thisLinePtr);
	if (thisLinePtr && extraLinesPtr) {
	    /*
	     * Tell our caller we have an extra line merged in.
	     */

	    *extraLinesPtr = *extraLinesPtr + 1;
	}
    }

    /*
     * If we're ignoring case, convert the line to lower case. There is no
     * need to do this for regexp searches, since they handle a flag for this
     * purpose.
     */

    if (searchSpecPtr->exact && searchSpecPtr->noCase) {
	Tcl_SetObjLength(theLine, Tcl_UtfToLower(Tcl_GetString(theLine)));
    }

    if (lenPtr) {
	*lenPtr = searchSpecPtr->exact ? GetByteLength(theLine) : Tcl_GetCharLength(theLine);
    }
    return linePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TextSearchFoundMatch --
 *
 *	Stores information from a successful search.
 *
 * Results:
 *	'true' if the information was stored, 'false' if the position at
 *	which the match was found actually falls outside the allowable
 *	search region (and therefore the search is actually complete).
 *
 * Side effects:
 *	Memory may be allocated in the 'countPtr' and 'resPtr' fields of
 *	'searchSpecPtr'. Each of those objects will have refCount zero and
 *	must eventually be freed or stored elsewhere as appropriate.
 *
 *----------------------------------------------------------------------
 */

static int
TextSearchFoundMatch(
    int lineNum,		/* Line on which match was found. */
    SearchSpec *searchSpecPtr,	/* Search parameters. */
    ClientData clientData,	/* Token returned by the 'addNextLineProc', TextSearchAddNextLine.
    				 * May be NULL, in which we case we must generate it (from lineNum). */
    Tcl_Obj *theLine,		/* Text from current line, only accessed for exact searches, and
    				 * is allowed to be NULL for regexp searches. */
    int matchOffset,		/* Offset of found item in utf-8 bytes for exact search, Unicode
    				 * chars for regexp. */
    int matchLength)		/* Length also in bytes/chars as per search type. */
{
    int numChars;
    int leftToScan;
    TkTextIndex foundIndex;
    TkTextSegment *segPtr;
    TkTextLine *linePtr, *startLinePtr;
    TkText *textPtr = (TkText *)searchSpecPtr->clientData;
    int byteIndex;

    if (lineNum == searchSpecPtr->stopLine) {
	/*
	 * If the current index is on the wrong side of the stopIndex, then
	 * the item we just found is actually outside the acceptable range,
	 * and the search is over.
	 */

	if (searchSpecPtr->backwards ^ (matchOffset >= searchSpecPtr->stopOffset)) {
	    return 0;
	}
    }

    /*
     * Calculate the character count, which may need augmenting if there are
     * embedded windows or elidden text.
     */

    if (searchSpecPtr->exact) {
	numChars = Tcl_NumUtfChars(Tcl_GetString(theLine) + matchOffset, matchLength);
    } else {
	numChars = matchLength;
    }

    /*
     * If we're using strict limits checking, ensure that the match with its
     * full length fits inside the given range.
     */

    if (searchSpecPtr->strictLimits && lineNum == searchSpecPtr->stopLine) {
	if (searchSpecPtr->backwards ^ (matchOffset + numChars > searchSpecPtr->stopOffset)) {
	    return 0;
	}
    }

    /*
     * The index information returned by the regular expression parser only
     * considers textual information: it doesn't account for embedded windows,
     * elided text (when we are not searching elided text) or any other
     * non-textual info. Scan through the line's segments again to adjust both
     * matchChar and matchCount.
     *
     * We will walk through the segments of this line until we have either
     * reached the end of the match or we have reached the end of the line.
     */

    linePtr = (TkTextLine *)clientData;
    if (!linePtr) {
	linePtr = TkBTreeFindLine(textPtr->sharedTextPtr->tree, textPtr, lineNum);
    }
    startLinePtr = textPtr->startMarker->sectionPtr->linePtr;

    /*
     * Find the starting point.
     */

    leftToScan = matchOffset;
    while (1) {
	/*
	 * Note that we allow leftToScan to be zero because we want to skip
	 * over any preceding non-textual items.
	 */

	segPtr = (linePtr == startLinePtr) ? textPtr->startMarker : linePtr->segPtr;
	byteIndex = TkTextSegToIndex(segPtr);

	/*
	 * TODO: Use new elide structure, but this requires a redesign of the whole
	 * search algorithm.
	 */

	for ( ; leftToScan >= 0 && segPtr; segPtr = segPtr->nextPtr) {
	    if (segPtr->typePtr == &tkTextCharType) {
		int size = searchSpecPtr->exact ? segPtr->size : (int) CountCharsInSeg(segPtr);

		if (!searchSpecPtr->searchElide && TkTextSegmentIsElided(textPtr, segPtr)) {
		    matchOffset += size;
		} else {
		    leftToScan -= size;
		}
	    } else if (searchSpecPtr->searchHyphens && segPtr->typePtr == &tkTextHyphenType) {
		int size = searchSpecPtr->exact ? 2 : 1;

		if (!searchSpecPtr->searchElide && TkTextSegmentIsElided(textPtr, segPtr)) {
		    matchOffset += size;
		} else {
		    leftToScan -= size;
		}
	    } else {
		assert(segPtr->size <= 1);
		matchOffset += segPtr->size;
	    }
	    byteIndex += segPtr->size;
	}

	assert(!segPtr || leftToScan < 0 || TkBTreeNextLine(textPtr, linePtr));

	if (segPtr || leftToScan < 0) {
	    break;
	}

	/*
	 * This will only happen if we are eliding newlines.
	 *
	 * We've wrapped to the beginning of the next logical line, which
	 * has been merged with the previous one whose newline was elided.
	 */

	linePtr = linePtr->nextPtr;
	lineNum += 1;
	matchOffset = 0;
    }

    /*
     * Calculate and store the found index in the result.
     */

    if (searchSpecPtr->exact) {
	TkrTextMakeByteIndex(textPtr->sharedTextPtr->tree, textPtr, lineNum, matchOffset, &foundIndex);
    } else {
	TkTextMakeCharIndex(textPtr->sharedTextPtr->tree, textPtr, lineNum, matchOffset, &foundIndex);
    }

    if (searchSpecPtr->all) {
	if (!searchSpecPtr->resPtr) {
	    Tcl_IncrRefCount(searchSpecPtr->resPtr = Tcl_NewObj());
	}
	Tcl_ListObjAppendElement(NULL, searchSpecPtr->resPtr, TkTextNewIndexObj(&foundIndex));
    } else {
	Tcl_IncrRefCount(searchSpecPtr->resPtr = TkTextNewIndexObj(&foundIndex));
    }

    /*
     * Find the end point. Here 'leftToScan' could be negative already as a
     * result of the above loop if the segment we reached spanned the start of
     * the string. When we add matchLength it will become non-negative.
     */

    /*
     * TODO: Use new elide structure, but this requires a redesign of the whole
     * search algorithm.
     */

    for (leftToScan += matchLength; leftToScan > 0; segPtr = segPtr->nextPtr) {
	int isCharSeg;

	if (!segPtr) {
	    /*
	     * We are on the next line - this of course should only ever
	     * happen with searches which have matched across multiple lines.
	     */

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

	isCharSeg = (segPtr->typePtr == &tkTextCharType);

	if (!isCharSeg && (!searchSpecPtr->searchHyphens || segPtr->typePtr != &tkTextHyphenType)) {
	    /*
	     * Anything we didn't count in the search needs adding.
	     */

	    assert(segPtr->size <= 1);
	    numChars += segPtr->size;
	} else if (!searchSpecPtr->searchElide && TkTextSegmentIsElided(textPtr, segPtr)) {
	    numChars += isCharSeg ? CountCharsInSeg(segPtr) : 1;
	} else if (searchSpecPtr->exact) {
	    leftToScan -= isCharSeg ? segPtr->size : 2;
	} else {
	    leftToScan -= isCharSeg ? CountCharsInSeg(segPtr) : 1;
	}
    }

    /*
     * Now store the count result, if it is wanted.
     */

    if (searchSpecPtr->varPtr) {
	Tcl_Obj *tmpPtr = Tcl_NewIntObj(numChars);
	if (searchSpecPtr->all) {
	    if (!searchSpecPtr->countPtr) {
		searchSpecPtr->countPtr = Tcl_NewObj();
	    }
	    Tcl_ListObjAppendElement(NULL, searchSpecPtr->countPtr, tmpPtr);
	} else {
	    searchSpecPtr->countPtr = tmpPtr;
	}
    }

    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetTabs --
 *
 *	Parses a string description of a set of tab stops.
 *
 * Results:
 *	The return value is a pointer to a malloc'ed structure holding parsed
 *	information about the tab stops. If an error occurred then the return
 *	value is NULL and an error message is left in the interp's result.
 *
 * Side effects:
 *	Memory is allocated for the structure that is returned. It is up to
 *	the caller to free this structure when it is no longer needed.
 *
 *----------------------------------------------------------------------
 */

TkTextTabArray *
TkTextGetTabs(
    Tcl_Interp *interp,		/* Used for error reporting. */
    TkText *textPtr,		/* Information about the text widget. */
    Tcl_Obj *stringPtr)		/* Description of the tab stops. See the text
				 * manual entry for details. */
{
    int objc, i, count;
    Tcl_Obj **objv;
    TkTextTabArray *tabArrayPtr;
    TkTextTab *tabPtr;
    double prevStop, lastStop;
    /*
     * Map these strings to TkTextTabAlign values.
     */
    static const char *const tabOptionStrings[] = {
	"left", "right", "center", "numeric", NULL
    };

    if (Tcl_ListObjGetElements(interp, stringPtr, &objc, &objv) != TCL_OK) {
	return NULL;
    }

    /*
     * First find out how many entries we need to allocate in the tab array.
     */

    count = 0;
    for (i = 0; i < objc; i++) {
	char c = Tcl_GetString(objv[i])[0];

	if (c != 'l' && c != 'r' && c != 'c' && c != 'n') {
	    count += 1;
	}
    }

    /*
     * Parse the elements of the list one at a time to fill in the array.
     */

    tabArrayPtr = (TkTextTabArray *)malloc(sizeof(TkTextTabArray) + (count - 1)*sizeof(TkTextTab));
    tabArrayPtr->numTabs = 0;
    prevStop = 0.0;
    lastStop = 0.0;
    for (i = 0, tabPtr = &tabArrayPtr->tabs[0]; i < objc; i++, tabPtr++) {
	int index;

	/*
	 * This will round fractional pixels above 0.5 upwards, and otherwise
	 * downwards, to find the right integer pixel position.
	 */

	if (Tk_GetPixelsFromObj(interp, textPtr->tkwin, objv[i], &tabPtr->location) != TCL_OK) {
	    goto error;
	}

	if (tabPtr->location <= 0) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "tab stop \"%s\" is not at a positive distance", Tcl_GetString(objv[i])));
	    Tcl_SetErrorCode(interp, "TK", "VALUE", "TAB_STOP", NULL);
	    goto error;
	}

	prevStop = lastStop;
	if (Tk_GetDoublePixelsFromObj(interp, textPtr->tkwin, objv[i], &lastStop) != TCL_OK) {
	    goto error;
	}

	if (i > 0 && tabPtr->location <= (tabPtr - 1)->location) {
	    /*
	     * This tab is actually to the left of the previous one, which is
	     * illegal.
	     */

#ifdef _TK_ALLOW_DECREASING_TABS
	    /*
	     * Force the tab to be a typical character width to the right of
	     * the previous one, and update the 'lastStop' with the changed
	     * position.
	     */

	    tabPtr->location = (tabPtr - 1)->location;
	    tabPtr->location += (textPtr->charWidth > 0 ? textPtr->charWidth : 8);
	    lastStop = tabPtr->location;
#else
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "tabs must be monotonically increasing, but \"%s\" is "
		    "smaller than or equal to the previous tab",
		    Tcl_GetString(objv[i])));
	    Tcl_SetErrorCode(interp, "TK", "VALUE", "TAB_STOP", NULL);
	    goto error;
#endif /* _TK_ALLOW_DECREASING_TABS */
	}

	tabArrayPtr->numTabs += 1;

	/*
	 * See if there is an explicit alignment in the next list element.
	 * Otherwise just use "left".
	 */

	tabPtr->alignment = LEFT;
	if (i + 1 == objc) {
	    continue;
	}

	/*
	 * There may be a more efficient way of getting this.
	 */

	{ /* local scope */
#if 0 && 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(Tcl_GetString(objv[i + 1]), &ch);
#else
	    /*
	     * Proper implementation for UTF-8 strings:
	     */

	    Tcl_UniChar ch;
	    Tcl_UtfToUniChar(Tcl_GetString(objv[i + 1]), &ch);
#endif
	    if (!Tcl_UniCharIsAlpha(ch)) {
		continue;
	    }
	}
	i += 1;

	if (Tcl_GetIndexFromObjStruct(interp, objv[i], tabOptionStrings,
		sizeof(char *), "tab alignment", 0, &index) != TCL_OK) {
	    goto error;
	}
	tabPtr->alignment = (TkTextTabAlign) index;
    }

    /*
     * For when we need to interpolate tab stops, store these two so we know
     * the tab stop size to very high precision. With the above checks, we can
     * guarantee that tabIncrement is strictly positive here.
     */

    tabArrayPtr->lastTab = lastStop;
    tabArrayPtr->tabIncrement = lastStop - prevStop;

    return tabArrayPtr;

  error:
    free(tabArrayPtr);
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * TextDumpCmd --
 *
 *	Return information about the text, tags, marks, and embedded windows
 *	and images in a text widget. See the man page for the description of
 *	the text dump operation for all the details.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Memory is allocated for the result, if needed (standard Tcl result
 *	side effects).
 *
 *----------------------------------------------------------------------
 */

static void
AppendOption(
    char *result,
    const char *str,
    const char *delim)
{
    unsigned len = strlen(result);

    if (delim && len > 0 && result[len - 1] != ' ' && result[len - 1] != '?') {
	strcpy(result + len, delim);
	len += strlen(delim);
    }
    strcpy(result + len, str);
}

static int
GetDumpFlags(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[],	/* Argument objects. */
    unsigned allowed,		/* Which options are allowed? */
    unsigned dflt,		/* Default options (-all) */
    unsigned complete,		/* Complete options (-complete) */
    unsigned *what,		/* Store flags here. */
    int *lastArg,		/* Store index of last used argument, can be NULL. */
    TkTextIndex *index1,	/* Store first index here. */
    TkTextIndex *index2,	/* Store second index here. */
    Tcl_Obj **command)		/* Store command here, can be NULL. */
{
    static const char *const optStrings[] = {
	"-all", "-bindings", "-chars", "-command", "-complete", "-configurations",
	"-displaychars", "-displaytext", "-dontresolvecolors",
	"-dontresolvefonts", "-elide", "-image", "-includedbconfig",
	"-includedefaultconfig", "-includeselection", "-includesyscolors",
	"-includesysconfig", "-insertmark", "-mark", "-nested", "-node",
	"-setup", "-tag", "-text", "-window",
	NULL
    };
    enum opts {
	DUMP_ALL, DUMP_TAG_BINDINGS, DUMP_CHARS, DUMP_CMD, DUMP_COMPLETE, DUMP_TAG_CONFIGS,
	DUMP_DISPLAY_CHARS, DUMP_DISPLAY_TEXT, DUMP_DONT_RESOLVE_COLORS,
	DUMP_DONT_RESOLVE_FONTS, DUMP_ELIDE, DUMP_IMG, DUMP_INCLUDE_DATABASE_CONFIG,
	DUMP_INCLUDE_DEFAULT_CONFIG, DUMP_INCLUDE_SEL, DUMP_INCLUDE_SYSTEM_COLORS,
	DUMP_INCLUDE_SYSTEM_CONFIG, DUMP_INSERT_MARK, DUMP_MARK, DUMP_NESTED, DUMP_NODE,
	DUMP_TEXT_CONFIGS, DUMP_TAG, DUMP_TEXT, DUMP_WIN
    };
    static const unsigned dumpFlags[] = {
	0, TK_DUMP_TAG_BINDINGS, TK_DUMP_CHARS, 0, TK_DUMP_INSPECT_COMPLETE, TK_DUMP_TAG_CONFIGS,
	TK_DUMP_DISPLAY_CHARS, TK_DUMP_DISPLAY_TEXT, TK_DUMP_DONT_RESOLVE_COLORS,
	TK_DUMP_DONT_RESOLVE_FONTS, TK_DUMP_ELIDE, TK_DUMP_IMG, TK_DUMP_INCLUDE_DATABASE_CONFIG,
	TK_DUMP_INCLUDE_DEFAULT_CONFIG, TK_DUMP_INCLUDE_SEL, TK_DUMP_INCLUDE_SYSTEM_COLORS,
	TK_DUMP_INCLUDE_SYSTEM_CONFIG, TK_DUMP_INSERT_MARK, TK_DUMP_MARK, TK_DUMP_NESTED, TK_DUMP_NODE,
	TK_DUMP_TEXT_CONFIGS, TK_DUMP_TAG, TK_DUMP_TEXT, TK_DUMP_WIN
    };

    int arg;
    unsigned i;
    unsigned flags = 0;
    const char *myOptStrings[sizeof(optStrings)/sizeof(optStrings[0])];
    int myOptIndices[sizeof(optStrings)/sizeof(optStrings[0])];
    int myOptCount;

    assert(what);
    assert(!index1 == !index2);
    assert(DUMP_ALL == 0); /* otherwise next loop is wrong */
    assert(!complete || (complete & dflt) == dflt);

    /* We know that option -all is allowed in any case. */
    myOptStrings[0] = optStrings[DUMP_ALL];
    myOptIndices[0] = DUMP_ALL;
    myOptCount = 1;

    for (i = 1; i < sizeof(optStrings)/sizeof(optStrings[0]) - 1; ++i) {
	if (i == DUMP_CMD ? !!command : (allowed & dumpFlags[i]) == dumpFlags[i]) {
	    myOptStrings[myOptCount] = optStrings[i];
	    myOptIndices[myOptCount] = i;
	    myOptCount += 1;
	}
    }
    myOptStrings[myOptCount] = NULL;

    if (lastArg) {
	*lastArg = 0;
    }
    *what = 0;

    for (arg = 2; arg < objc && Tcl_GetString(objv[arg])[0] == '-'; ++arg) {
	int index;

	if (Tcl_GetString(objv[arg])[1] == '-'
		&& Tcl_GetString(objv[arg])[2] == '\0'
		&& (arg < objc - 1 || Tcl_GetString(objv[arg + 1])[0] != '-')) {
	    continue;
	}

	if (Tcl_GetIndexFromObjStruct(interp, objv[arg], myOptStrings,
		sizeof(char *), "option", 0, &index) != TCL_OK) {
	    return TCL_ERROR;
	}

	switch ((enum opts) myOptIndices[index]) {
#define CASE(Flag) case DUMP_##Flag: *what |= TK_DUMP_##Flag; flags |= TK_DUMP_##Flag; break;
	CASE(CHARS);
	CASE(TEXT);
	CASE(DISPLAY_CHARS);
	CASE(DISPLAY_TEXT);
	CASE(TAG);
	CASE(MARK);
	CASE(ELIDE);
	CASE(NESTED);
	CASE(NODE);
	CASE(INCLUDE_SEL);
	CASE(INSERT_MARK);
	CASE(TEXT_CONFIGS);
	CASE(TAG_BINDINGS);
	CASE(TAG_CONFIGS);
	CASE(DONT_RESOLVE_COLORS);
	CASE(DONT_RESOLVE_FONTS);
	CASE(INCLUDE_DEFAULT_CONFIG);
	CASE(INCLUDE_DATABASE_CONFIG);
	CASE(INCLUDE_SYSTEM_CONFIG);
	CASE(INCLUDE_SYSTEM_COLORS);
	CASE(IMG);
	CASE(WIN);
#undef CASE
	case DUMP_ALL:
	    *what = dflt;
	    break;
	case DUMP_COMPLETE:
	    if (!complete)
		goto wrongArgs;
	    *what = complete;
	    break;
	case DUMP_CMD:
	    arg += 1;
	    if (!command || arg >= objc) {
		goto wrongArgs;
	    }
	    *command = objv[arg];
	    break;
	}
	if (~allowed & flags) {
	    goto wrongArgs;
	}
    }
    if (!(*what & dflt)) {
	*what |= dflt;
    }
    if (!index1) {
	if (arg < objc) {
	    goto wrongArgs;
	}
	return TCL_OK;
    }
    if (arg >= objc || arg + 2 < objc) {
	goto wrongArgs;
    }
    if (!TkTextGetIndexFromObj(interp, textPtr, objv[arg], index1)) {
	return TCL_ERROR;
    }
    arg += 1;
    if (lastArg) {
	*lastArg = arg;
    }
    if (objc == arg) {
	TkTextIndexForwChars(textPtr, index1, 1, index2, COUNT_INDICES);
    } else if (!TkTextGetIndexFromObj(interp, textPtr, objv[arg], index2)) {
	return TCL_ERROR;
    }
    return TCL_OK;

wrongArgs:
    {
	char result[500];
	unsigned i;

	result[0] = 0;
	AppendOption(result, "?", NULL);

	for (i = 0; myOptStrings[i]; ++i) {
	    if (myOptIndices[i] != DUMP_CMD) {
		AppendOption(result, myOptStrings[i], " ");
	    }
	}
	AppendOption(result, "? ?", NULL);
	if (command) { AppendOption(result, "-command script", NULL); }
	AppendOption(result, "?", NULL);
	if (index1)  { AppendOption(result, " index ?index2?", NULL); }

	Tcl_SetObjResult(interp, Tcl_ObjPrintf("Usage: %s %s %s",
		Tcl_GetString(objv[0]), Tcl_GetString(objv[1]), result));
	Tcl_SetErrorCode(interp, "TCL", "WRONGARGS", NULL);
    }
    return TCL_ERROR;
}

static int
TextDumpCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. Someone else has already parsed this command
    				 * enough to know that objv[1] is "dump". */
{
    TkTextIndex index1, index2;
    TkTextBTree tree;
    TkTextTag *tagPtr, *tPtr;
    int lineno;			/* Current line number. */
    unsigned what;		/* bitfield to select segment types. */
    int lastArg;		/* Index of last argument. */
    TkTextLine *linePtr;
    TkTextIndex prevByteIndex;
    Tcl_Obj *command = NULL;	/* Script callback to apply to segments. */
    TkTextTag *prevTagPtr = NULL;
    int result;

    assert(textPtr);

    result = GetDumpFlags(textPtr, interp, objc, objv, TK_DUMP_DUMP_ALL|TK_DUMP_NODE, TK_DUMP_DUMP_ALL,
	    0, &what, &lastArg, &index1, &index2, &command);
    if (result != TCL_OK) {
	return result;
    }
    if (TkTextIndexCompare(&index1, &index2) >= 0) {
	return TCL_OK;
    }
    tree = textPtr->sharedTextPtr->tree;
    textPtr->sharedTextPtr->inspectEpoch += 1;
    lineno = TkBTreeLinesTo(tree, textPtr, TkTextIndexGetLine(&index1), NULL);
    prevByteIndex = index1;
    if (TkrTextIndexBackBytes(textPtr, &index1, 1, &prevByteIndex) == 0) {
	unsigned epoch = textPtr->sharedTextPtr->inspectEpoch + 1;
	tagPtr = TkBTreeGetTags(&prevByteIndex, TK_TEXT_SORT_NONE, NULL);
	for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) { tPtr->epoch = epoch; }
    } else {
	tagPtr = NULL;
    }
    if (TkTextIndexGetLine(&index1) == TkTextIndexGetLine(&index2)) {
	/* we are at the end, so we can ignore the return code of DumpLine */
	DumpLine(interp, textPtr, what, TkTextIndexGetLine(&index1),
		TkTextIndexGetByteIndex(&index1), TkTextIndexGetByteIndex(&index2),
		lineno, command, &prevTagPtr);
    } else {
	int lineend = TkBTreeLinesTo(tree, textPtr, TkTextIndexGetLine(&index2), NULL);
	int endByteIndex = TkTextIndexGetByteIndex(&index2);

	if (!DumpLine(interp, textPtr, what, TkTextIndexGetLine(&index1),
		TkTextIndexGetByteIndex(&index1), INT_MAX, lineno, command, &prevTagPtr)) {
	    if (textPtr->flags & DESTROYED) {
		return TCL_OK;
	    }
	    if (!(linePtr = TkBTreeFindLine(textPtr->sharedTextPtr->tree, textPtr, lineno))) {
		goto textChanged;
	    }
	} else {
	    linePtr = TkTextIndexGetLine(&index1);
	}
	while ((linePtr = TkBTreeNextLine(textPtr, linePtr))) {
	    if (++lineno == lineend) {
		break;
	    }
	    if (!DumpLine(interp, textPtr, what, linePtr, 0, INT_MAX, lineno, command, &prevTagPtr)) {
		if (textPtr->flags & DESTROYED) {
		    return TCL_OK;
		}
		if (!(linePtr = TkBTreeFindLine(textPtr->sharedTextPtr->tree, textPtr, lineno))) {
		    goto textChanged;
		}
	    }
	}
	if (linePtr) {
	    /* we are at the end, so we can ignore the return code of DumpLine */
	    DumpLine(interp, textPtr, what, linePtr, 0, endByteIndex, lineno, command, &prevTagPtr);
	}
    }

  textChanged:

    /*
     * Special case to get the leftovers hiding at the end mark.
     */

    if (!(textPtr->flags & DESTROYED)) {
	if (lastArg < objc
		&& strncmp(Tcl_GetString(objv[lastArg]), "end", GetByteLength(objv[lastArg])) == 0) {
	    /*
	     * Re-get the end index, in case it has changed.
	     */

	    if (!TkTextGetIndexFromObj(interp, textPtr, objv[lastArg], &index2)) {
		return TCL_ERROR;
	    }
	    if (!DumpLine(interp, textPtr, what & ~TK_DUMP_TEXT, TkTextIndexGetLine(&index2), 0, 1,
		    lineno, command, &prevTagPtr)) {
		prevTagPtr = NULL; /* the tags are no longer valid */
	    }
	}

	if (prevTagPtr && TkTextIndexIsEndOfText(&index2)) {
	    /*
	     * Finally print "tagoff" information, if at end of text.
	     */

	    for ( ; prevTagPtr; prevTagPtr = prevTagPtr->succPtr) {
		if (!DumpSegment(textPtr, interp, "tagoff", prevTagPtr->name, command, &index2, what)) {
		    break;
		}
	    }
	}
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DumpLine
 *
 *	Return information about a given text line from character position
 *	"start" up to, but not including, "end".
 *
 * Results:
 *	Returns false if the command callback made any changes to the text widget
 *	which will have invalidated internal structures such as TkTextSegment,
 *	TkTextIndex, pointers. Our caller can then take action to recompute
 *	such entities, or he aborts with an error. Returns true otherwise.
 *
 * Side effects:
 *	None, but see DumpSegment which can have arbitrary side-effects
 *
 *----------------------------------------------------------------------
 */

static int
DumpLine(
    Tcl_Interp *interp,
    TkText *textPtr,
    int what,			/* Bit flags to select segment types. */
    TkTextLine *linePtr,	/* The current line. */
    int startByte, int endByte,	/* Byte range to dump. */
    int lineno,			/* Line number for indices dump. */
    Tcl_Obj *command,		/* Script to apply to the segment. */
    TkTextTag **prevTagPtr)	/* Tag information from previous segment. */
{
    TkSharedText *sharedTextPtr;
    TkTextSegment *sPtr;
    TkTextSegment *segPtr;
    TkTextSegment *endPtr;
    TkTextSegment *newSegPtr;
    TkTextIndex index;
    int offset = 0;
    int currentSize = 0;
    int bufSize = 0;
    int textChanged = 0;
    char *buffer = NULL;
    int eol;

    sharedTextPtr = textPtr->sharedTextPtr;

    if (!*prevTagPtr && (startByte > 0 || linePtr != TkBTreeGetStartLine(textPtr))) {
	/*
	 * If this is the first line to dump, and we are not at start of line,
	 * then we need the preceding tag information.
	 */

	TkTextIndex index;
	TkTextTag *tagPtr, *tPtr;
	unsigned epoch = sharedTextPtr->inspectEpoch;

	TkTextIndexClear(&index, textPtr);
	TkTextIndexSetByteIndex2(&index, linePtr, startByte);
	TkBTreeMoveBackward(&index, 1);
	segPtr = TkTextIndexGetContentSegment(&index, NULL);
	assert(segPtr);
	tagPtr = TkBTreeGetSegmentTags(textPtr->sharedTextPtr, segPtr, textPtr, TK_TEXT_SORT_NONE, NULL);
	for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
	    tPtr->flag = epoch; /* mark as open */
	}
    }

    /*
     * Must loop through line looking at its segments: character, hyphen, mark, image, window.
     */

    segPtr = linePtr->segPtr;
    endPtr = textPtr->endMarker;
    eol = !segPtr->nextPtr;

    if ((what & TK_DUMP_NODE)
	    && startByte == 0
	    && (!linePtr->prevPtr || linePtr->prevPtr->parentPtr != linePtr->parentPtr)) {
	char buf[20];
	unsigned depth, number;

	TkTextIndexClear(&index, textPtr);
	TkTextIndexSetToStartOfLine2(&index, linePtr);
	number = TkBTreeChildNumber(sharedTextPtr->tree, linePtr, &depth);
	snprintf(buf, sizeof(buf), "%d:%d", number, depth);

	if (!DumpSegment(textPtr, interp, "node", buf, command, &index, what)) {
	    goto textChanged;
	}
    }

    while (segPtr && offset < endByte) {
	currentSize = segPtr->size;

	if (offset + MAX(1, currentSize) > startByte) {
	    if ((what & TK_DUMP_TAG) && segPtr->tagInfoPtr) {
		TkTextTag *tagPtr = TkBTreeGetSegmentTags(sharedTextPtr, segPtr, textPtr,
			TK_TEXT_SORT_ASCENDING, NULL);
		unsigned epoch = sharedTextPtr->inspectEpoch;
		unsigned nextEpoch = epoch + 1;
		TkTextTag *tPtr;

		for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
		    if (tPtr->flag == epoch) {
			tPtr->flag = nextEpoch; /* mark as still open */
		    }
		}

		if (*prevTagPtr) {
		    /*
		     * Print "tagoff" information.
		     */

		    for (tPtr = *prevTagPtr; tPtr; tPtr = tPtr->succPtr) {
			if (tPtr->flag == epoch) { /* should be closed? */
			    TkrTextMakeByteIndex(sharedTextPtr->tree, textPtr, lineno, offset, &index);
			    if (!DumpSegment(textPtr, interp, "tagoff",
				    tPtr->name, command, &index, what)) {
				goto textChanged;
			    }
			    tPtr->flag = 0; /* mark as closed */
			}
		    }
		}

		/*
		 * Print "tagon" information.
		 */

		sharedTextPtr->inspectEpoch = ++epoch;

		for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
		    if (tPtr->flag != epoch) {
			TkrTextMakeByteIndex(sharedTextPtr->tree, textPtr, lineno, offset, &index);
			if (!DumpSegment(textPtr, interp, "tagon", tPtr->name, command, &index, what)) {
			    goto textChanged;
			}
			tPtr->flag = epoch; /* mark as open */
		    }
		    tPtr->succPtr = tPtr->nextPtr;
		}

		*prevTagPtr = tagPtr;
	    }

	    if (what & segPtr->typePtr->group) {
		assert(segPtr->typePtr->group != SEG_GROUP_BRANCH);

		if (segPtr->typePtr->group == SEG_GROUP_CHAR) {
		    int last = currentSize;	/* Index of last char in seg. */
		    int first = 0;		/* Index of first char in seg. */

		    if (offset + currentSize > endByte) {
			last = endByte - offset;
		    }
		    if (startByte > offset) {
			first = startByte - offset;
		    }
		    if (last != currentSize) {
			/*
			 * To avoid modifying the string in place we copy over just
			 * the segment that we want. Since DumpSegment can modify the
			 * text, we could not confidently revert the modification here.
			 */

			int length = last - first;

			if (length >= bufSize) {
			    bufSize = MAX(length + 1, 2*length);
			    buffer = (char *)realloc(buffer, bufSize);
			}

			memcpy(buffer, segPtr->body.chars + first, length);
			buffer[length] = '\0';

			TkrTextMakeByteIndex(sharedTextPtr->tree, textPtr, lineno,
				offset + first, &index);
			if (!DumpSegment(textPtr, interp, "text", buffer, command, &index, what)) {
			    goto textChanged;
			}
		    } else {
			TkrTextMakeByteIndex(sharedTextPtr->tree, textPtr, lineno,
				offset + first, &index);
			if (!DumpSegment(textPtr, interp, "text",
				segPtr->body.chars + first, command, &index, what)) {
			    goto textChanged;
			}
		    }
		} else if (segPtr == endPtr) {
		    if (linePtr == TkBTreeGetLastLine(textPtr)) {
			break; /* finished */
		    }
		    /* print final newline in next iteration */
		    currentSize = linePtr->size - offset - 1;
		    startByte = offset + currentSize + linePtr->lastPtr->size - 1;
		    segPtr = linePtr->lastPtr->prevPtr;
		} else {
		    char const *value = NULL;

		    switch ((int) segPtr->typePtr->group) {
		    case SEG_GROUP_MARK:
			value = TkTextMarkName(sharedTextPtr, textPtr, segPtr);
			break;
		    case SEG_GROUP_IMAGE: {
			TkTextEmbImage *eiPtr = &segPtr->body.ei;
			value = eiPtr->name ? eiPtr->name : "";
			break;
		    }
		    case SEG_GROUP_WINDOW: {
			TkTextEmbWindow *ewPtr = &segPtr->body.ew;
			value = ewPtr->tkwin ? Tk_PathName(ewPtr->tkwin) : "";
			break;
		    }
		    case SEG_GROUP_HYPHEN:
			value = "";
			break;
		    }
		    if (value) {
			TkrTextMakeByteIndex(sharedTextPtr->tree, textPtr, lineno, offset, &index);
			if (!DumpSegment(textPtr, interp, segPtr->typePtr->name, value, command,
				&index, what)) {
			    goto textChanged;
			}
		    }
		}
	    }
	}

	offset += currentSize;
	segPtr = segPtr->nextPtr;
	continue;

  textChanged:

	/*
	 * Our indices, segments, and tag chains are no longer valid. It's a bad
	 * idea to do changes while the dump is running, it's impossible to
	 * synchronize in any case, but we will try the best.
	 */

	*prevTagPtr = NULL;
	textChanged = 1;

	if (eol || (textPtr->flags & DESTROYED)) {
	    break;
	}

	offset += currentSize;
	if (!(linePtr = TkBTreeFindLine(textPtr->sharedTextPtr->tree, textPtr, lineno))) {
	    break;
	}
	TkTextIndexClear(&index, textPtr);
	TkTextIndexSetByteIndex2(&index, linePtr, MIN(offset, linePtr->size - 1));

	sPtr = newSegPtr = TkTextIndexGetFirstSegment(&index, NULL);
	while (sPtr && sPtr != segPtr) {
	    sPtr = sPtr->nextPtr;
	}
	if (sPtr != segPtr) {
	    segPtr = newSegPtr;
	} else if (offset >= segPtr->size) {
	    segPtr = segPtr->nextPtr;
	}
    }

    free(buffer);
    return !textChanged;
}

/*
 *----------------------------------------------------------------------
 *
 * TextChecksumCmd --
 *
 *	Return the checksum over the whole content.
 *	About the format see documentation.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Memory is allocated for the result, if needed (standard Tcl result
 *	side effects).
 *
 *----------------------------------------------------------------------
 */

static uint32_t
ComputeChecksum(
    uint32_t crc,
    const char *buf,
    unsigned len)
{
    static const uint32_t crcTable[256] = {
      0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
      0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
      0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
      0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
      0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
      0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
      0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
      0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
      0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
      0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
      0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
      0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
      0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
      0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
      0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
      0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
      0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
      0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
      0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
      0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
      0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
      0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
      0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
      0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
      0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
      0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
      0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
      0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
      0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
      0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
      0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
      0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
    };

    assert(buf);

    /* basic algorithm stolen from zlib/crc32.c (public domain) */

#define DO1(buf) crc = crcTable[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8);
#define DO2(buf) DO1(buf); DO1(buf);
#define DO4(buf) DO2(buf); DO2(buf);
#define DO8(buf) DO4(buf); DO4(buf);

    crc = crc ^ 0xffffffff;

    if (len == 0) {
	while (*buf) {
	    DO1(buf);
	}
    } else {
	while (len >= 8) {
	    DO8(buf);
	    len -= 8;
	}
	while (len--) {
	    DO1(buf);
	}
    }
    return crc ^ 0xffffffff;
}

static int
TextChecksumCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. Someone else has already parsed this command
    				 * enough to know that objv[1] is "checksum". */
{
    const TkSharedText *sharedTextPtr;
    const TkTextSegment *segPtr;
    const TkTextSegment *endPtr;
    const TkTextLine *linePtr;
    TkTextTag **tagArrPtr = NULL; /* avoid compiler warning */
    unsigned what;
    unsigned crc;
    int result;

    assert(textPtr);

    result = GetDumpFlags(textPtr, interp, objc, objv, TK_DUMP_CRC_ALL, TK_DUMP_CRC_DFLT, 0,
	    &what, NULL, NULL, NULL, NULL);

    if (result != TCL_OK) {
	return result;
    }

    sharedTextPtr = textPtr->sharedTextPtr;
    segPtr = sharedTextPtr->startMarker;
    endPtr = sharedTextPtr->endMarker;
    linePtr = segPtr->sectionPtr->linePtr;
    if (endPtr->sectionPtr->linePtr != linePtr) {
	endPtr = NULL;
    }
    crc = 0;

    if ((what & SEG_GROUP_TAG)) {
	tagArrPtr = (TkTextTag **)malloc(sizeof(tagArrPtr[0])*sharedTextPtr->numTags);
    }

    /*
     * Note that 0xff cannot occur in UTF-8 strings, so we can use this value as a separator.
     */

    while (segPtr != endPtr) {
	if (segPtr->tagInfoPtr
		&& (what & SEG_GROUP_TAG)
		&& segPtr->tagInfoPtr != sharedTextPtr->emptyTagInfoPtr) {
	    unsigned i = TkTextTagSetFindFirst(segPtr->tagInfoPtr);
	    unsigned n = 0;

	    for ( ; i != TK_TEXT_TAG_SET_NPOS; i = TkTextTagSetFindNext(segPtr->tagInfoPtr, i)) {
		assert(sharedTextPtr->tagLookup[i]);
		tagArrPtr[n++] = sharedTextPtr->tagLookup[i];
	    }

	    TkTextSortTags(n, tagArrPtr);

	    for (i = 0; i < n; ++i) {
		crc = ComputeChecksum(crc, "\xff\x00", 2);
		crc = ComputeChecksum(crc, tagArrPtr[i]->name, 0);
	    }
	}
	switch ((int) segPtr->typePtr->group) {
	case SEG_GROUP_CHAR:
	    if (what & SEG_GROUP_CHAR) {
		crc = ComputeChecksum(crc, "\xff\x01", 2);
		crc = ComputeChecksum(crc, segPtr->body.chars, segPtr->size);
	    }
	    break;
	case SEG_GROUP_HYPHEN:
	    if (what & SEG_GROUP_HYPHEN) {
		crc = ComputeChecksum(crc, "\xff\x02", 2);
	    }
	    break;
	case SEG_GROUP_WINDOW:
	    if ((what & SEG_GROUP_WINDOW)) {
		crc = ComputeChecksum(crc, "\xff\x03", 2);
		crc = ComputeChecksum(crc, Tk_PathName(segPtr->body.ew.tkwin), 0);
	    }
	    break;
	case SEG_GROUP_IMAGE:
	    if ((what & SEG_GROUP_IMAGE) && segPtr->body.ei.name) {
		crc = ComputeChecksum(crc, "\xff\x04", 2);
		crc = ComputeChecksum(crc, segPtr->body.ei.name, 0);
	    }
	    break;
	case SEG_GROUP_MARK:
	    if ((what & SEG_GROUP_MARK) && TkTextIsNormalMark(segPtr)) {
		const char *name;
		const char *signature;

		name = TkTextMarkName(sharedTextPtr, NULL, segPtr);
		signature = (segPtr->typePtr == &tkTextRightMarkType) ? "\xff\x05" : "\xff\x06";
		crc = ComputeChecksum(crc, signature, 2);
		crc = ComputeChecksum(crc, name, 0);
	    }
	    break;
	case SEG_GROUP_BRANCH:
	    if (segPtr->typePtr == &tkTextBranchType && (what & TK_DUMP_DISPLAY)) {
		segPtr = segPtr->body.branch.nextPtr;
	    }
	    break;
	}
	if (!(segPtr = segPtr->nextPtr)) {
	    linePtr = linePtr->nextPtr;
	    segPtr = linePtr->segPtr;
	}
    }

    if ((what & SEG_GROUP_TAG)) {
	free(tagArrPtr);
    }
    Tcl_SetObjResult(interp, Tcl_NewWideIntObj(crc));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DumpSegment
 *
 *	Either append information about the current segment to the result, or
 *	make a script callback with that information as arguments.
 *
 * Results:
 *	Returns 'false' if the command callback made any changes to the text widget
 *	which will have invalidated internal structures such as TkTextSegment,
 *	TkTextIndex, pointers. Our caller can then take action to recompute
 *	such entities, or he aborts with an error. Returns 'true' otherwise.
 *
 * Side effects:
 *	Either evals the callback or appends elements to the result string.
 *	The callback can have arbitrary side-effects.
 *
 *----------------------------------------------------------------------
 */

static int
DumpSegment(
    TkText *textPtr,
    Tcl_Interp *interp,
    const char *key,		/* Segment type key. */
    const char *value,		/* Segment value. */
    Tcl_Obj *command,		/* Script callback. */
    const TkTextIndex *index,	/* index with line/byte position info. */
    int what)			/* Look for TK_DUMP_INDEX bit. */
{
    char buffer[TK_POS_CHARS];
    Tcl_Obj *values[3], *tuple;
    (void)what;

    TkrTextPrintIndex(textPtr, index, buffer);
    values[0] = Tcl_NewStringObj(key, -1);
    values[1] = Tcl_NewStringObj(value, -1);
    values[2] = Tcl_NewStringObj(buffer, -1);
    Tcl_IncrRefCount(tuple = Tcl_NewListObj(3, values));
    if (!command) {
	Tcl_ListObjAppendList(NULL, Tcl_GetObjResult(interp), tuple);
	Tcl_GuardedDecrRefCount(tuple);
	return 1;
    } else {
	TkSizeT oldStateEpoch = TkBTreeEpoch(textPtr->sharedTextPtr->tree);
	Tcl_DString buf;
	int code;

	Tcl_DStringInit(&buf);
	Tcl_DStringAppend(&buf, Tcl_GetString(command), -1);
	Tcl_DStringAppend(&buf, " ", -1);
	Tcl_DStringAppend(&buf, Tcl_GetString(tuple), -1);
	code = Tcl_EvalEx(interp, Tcl_DStringValue(&buf), -1, 0);
	Tcl_DStringFree(&buf);
	if (code != TCL_OK) {
	    Tcl_AddErrorInfo(interp, "\n    (segment dumping command executed by text)");
	    Tcl_BackgroundException(interp, code);
	}
	Tcl_GuardedDecrRefCount(tuple);
	return !(textPtr->flags & DESTROYED)
		&& TkBTreeEpoch(textPtr->sharedTextPtr->tree) == oldStateEpoch;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextInspectOptions --
 *
 *	Build information from option table for "inspect".
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Memory is allocated for the result, if needed (standard Tcl result
 *	side effects).
 *
 *----------------------------------------------------------------------
 */

static int
MatchColors(
    const char *name,
    int len,
    const char *hexColor,
    const char *colorName)
{
    assert(strlen(hexColor) == 13);
    assert(strlen(colorName) == 5);

    switch (len) {
    case 5:  return strncasecmp(name, colorName, 5) == 0;
    case 7:  return strncasecmp(name, hexColor,  7) == 0;
    case 13: return strncasecmp(name, hexColor, 13) == 0;
    }

    return 0;
}

static int
TestIfEqual(
    const char *opt1,
    int opt1Len,
    const char *opt2,
    int opt2Len)
{
    int i;

    if (MatchColors(opt1, opt1Len, "#ffffffffffff", "white")) {
	return MatchColors(opt2, opt2Len, "#ffffffffffff", "white");
    }
    if (MatchColors(opt1, opt1Len, "#000000000000", "black")) {
	return MatchColors(opt2, opt2Len, "#000000000000", "black");
    }
    if (opt1Len != opt2Len) {
	return 0;
    }
    for (i = 0; i < opt1Len; ++i) {
	if (opt1[i] != opt2[i]) {
	    return 0;
	}
    }
    return 1;
}

static int
IsPossibleColorOption(
    const char *s)
{
    unsigned len = strlen(s);

    assert(s[0] == '-');

    return (len >= 6 && strcmp(s + len - 5, "color") == 0)
	    || (len >= 7 && strcmp(s + len - 6, "ground") == 0);
}

void
TkTextInspectOptions(
    TkText *textPtr,
    const void *recordPtr,
    Tk_OptionTable optionTable,
    Tcl_DString *result,	/* should be already initialized */
    int flags)
{
    Tcl_Obj *objPtr;
    Tcl_Interp *interp = textPtr->interp;

    Tcl_DStringSetLength(result, 0);

    if ((objPtr = Tk_GetOptionInfo(interp, (char *) recordPtr, optionTable, NULL, textPtr->tkwin))) {
	Tcl_Obj **objv;
	int objc = 0;
	int i;

	Tcl_ListObjGetElements(interp, objPtr, &objc, &objv);


	for (i = 0; i < objc; ++i) {
	    Tcl_Obj **argv;
	    int argc = 0;

	    Tcl_ListObjGetElements(interp, objv[i], &argc, &argv);

	    if (argc >= 5) { /* only if this option has a non-default value */
		Tcl_Obj *valObj = argv[4];
		Tcl_Obj *myValObj;
		Tcl_Obj *nameObj;
		int myFlags = flags;

		if (GetByteLength(valObj) == 0) {
		    continue;
		}

		if (!(myFlags & INSPECT_INCLUDE_DATABASE_CONFIG)
			|| myFlags & (INSPECT_INCLUDE_SYSTEM_CONFIG|INSPECT_INCLUDE_DEFAULT_CONFIG)) {
		    const char *name = Tcl_GetString(argv[1]);
		    const char *cls = Tcl_GetString(argv[2]);
		    Tk_Uid dfltUid = Tk_GetOption(textPtr->tkwin, name, cls);

		    if (dfltUid) {
			const char *value = Tcl_GetString(valObj);
			int valueLen = GetByteLength(valObj);

			if (TestIfEqual(dfltUid, strlen(dfltUid), value, valueLen)) {
			    if (!(myFlags & INSPECT_INCLUDE_DATABASE_CONFIG)) {
				continue;
			    }
			    myFlags |= INSPECT_INCLUDE_SYSTEM_CONFIG|INSPECT_INCLUDE_DEFAULT_CONFIG;
			}
		    }
		}

		if (!(myFlags & INSPECT_INCLUDE_SYSTEM_CONFIG)
			|| myFlags & INSPECT_INCLUDE_DEFAULT_CONFIG) {
		    const char *name = Tcl_GetString(argv[1]);
		    const char *cls = Tcl_GetString(argv[2]);
		    Tcl_Obj *dfltObj;

		    dfltObj = TkpGetSystemDefault(textPtr->tkwin, name, cls);

		    if (dfltObj) {
			const char *dflt = Tcl_GetString(dfltObj);
			const char *value = Tcl_GetString(valObj);
			int dfltLen = GetByteLength(dfltObj);
			int valueLen = GetByteLength(valObj);

			if (TestIfEqual(dflt, dfltLen, value, valueLen)) {
			    if (!(myFlags & INSPECT_INCLUDE_SYSTEM_CONFIG)) {
				continue;
			    }
			    myFlags |= INSPECT_INCLUDE_DEFAULT_CONFIG;
			}
		    }
		}

		if (!(myFlags & INSPECT_INCLUDE_DEFAULT_CONFIG)) {
		    const char *dflt = Tcl_GetString(argv[3]);
		    const char *value = Tcl_GetString(valObj);
		    int dfltLen = GetByteLength(argv[3]);
		    int valueLen = GetByteLength(valObj);

		    if (TestIfEqual(dflt, dfltLen, value, valueLen)) {
			continue;
		    }
		}

		myValObj = valObj;
		nameObj = argv[0];
		if (Tcl_DStringLength(result) > 0) {
		    Tcl_DStringAppend(result, " ", 1);
		}
		Tcl_DStringAppend(result, Tcl_GetString(nameObj), GetByteLength(nameObj));
		Tcl_DStringAppend(result, " ", 1);

		if (!(flags & INSPECT_DONT_RESOLVE_FONTS)
			&& strcmp(Tcl_GetString(nameObj), "-font") == 0) {
		    const char *s = Tcl_GetString(valObj);
		    unsigned len = GetByteLength(valObj);

		    /*
		     * Don't resolve font names like TkFixedFont, TkTextFont, etc.
		     */

		    if (len < 7
			    || strncmp(s, "Tk", 2) != 0
			    || strncmp(s + len - 4, "Font", 4) != 0) {
			Tk_Font tkfont = Tk_AllocFontFromObj(interp, textPtr->tkwin, valObj);

			if (tkfont) {
			    Tcl_IncrRefCount(myValObj = Tk_FontGetDescription(tkfont));
			    Tk_FreeFont(tkfont);
			}
		    }
		} else if ((flags & (INSPECT_DONT_RESOLVE_COLORS|INSPECT_INCLUDE_SYSTEM_COLORS)) !=
			    (INSPECT_DONT_RESOLVE_COLORS|INSPECT_INCLUDE_SYSTEM_COLORS)
			&& IsPossibleColorOption(Tcl_GetString(nameObj))) {
		    const char *colorName = Tcl_GetString(valObj);

		    if (strncasecmp(colorName, "system", 6) == 0) {
			XColor *col;

			if (!(flags & INSPECT_INCLUDE_SYSTEM_COLORS)) {
			    continue;
			}

			/*
			 * The color lookup expects a lowercase "system", but the defaults
			 * are providing the uppercase form "System", so we need to build
			 * a lowercase form.
			 */

			col = Tk_GetColor(interp, textPtr->tkwin, colorName);

			if (col) {
			    myValObj = Tcl_ObjPrintf("#%02x%02x%02x", col->red, col->green, col->blue);
			    Tcl_IncrRefCount(myValObj);
			    Tk_FreeColor(col);
			} else {
			    /*
			     * This should not happen. We will clear the error result, and
			     * print a warning.
			     */
			    Tcl_SetObjResult(interp, Tcl_NewObj());
			    Tcl_SetObjErrorCode(interp, Tcl_NewObj());
			    fprintf(stderr, "tk::text: couldn't resolve system color '%s'\n", colorName);
			}
		    }
		}

		Tcl_DStringAppendElement(result, Tcl_GetString(myValObj));

		if (myValObj != valObj) {
		    Tcl_GuardedDecrRefCount(myValObj);
		}
	    }
	}

    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextInspectCmd --
 *
 *	Return information about text and the associated tags.
 *	About the format see documentation.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Memory is allocated for the result, if needed (standard Tcl result
 *	side effects).
 *
 *----------------------------------------------------------------------
 */

static void
GetBindings(
    TkText *textPtr,
    const char *name,
    Tk_BindingTable bindingTable,
    Tcl_DString *str)
{
    Tcl_Interp *interp = textPtr->interp;
    Tcl_DString str2;
    Tcl_Obj **argv;
    int argc, i;

    Tk_GetAllBindings(interp, bindingTable, (ClientData) name);
    Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp), &argc, &argv);
    Tcl_DStringInit(&str2);

    for (i = 0; i < argc; ++i) {
	const char *event = Tcl_GetString(argv[i]);
	const char *binding = Tk_GetBinding(interp, bindingTable, (ClientData) name, event);
	char *p;

	Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp), &argc, &argv);

	Tcl_DStringStartSublist(str);
	Tcl_DStringAppendElement(str, "bind");
	Tcl_DStringAppendElement(str, name);
	Tcl_DStringAppendElement(str, event);

	Tcl_DStringSetLength(&str2, 0);
	p = (char *)strchr(binding, '\n');
	while (p) {
	    Tcl_DStringAppend(&str2, binding, p - binding);
	    Tcl_DStringAppend(&str2, "; ", 2);
	    binding = p + 1;
	    p = (char *)strchr(binding, '\n');
	}
	Tcl_DStringAppend(&str2, binding, -1);

	Tcl_DStringAppendElement(str, Tcl_DStringValue(&str2));
	Tcl_DStringEndSublist(str);
    }

    Tcl_DStringFree(&str2);
    Tcl_ResetResult(interp);
}

static int
TextInspectCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    TkSharedText *sharedTextPtr;
    TkTextTag *prevTagPtr;
    TkTextSegment *nextPtr;
    TkTextSegment *prevPtr;
    Tcl_DString buf[2];
    Tcl_DString *str = &buf[0];
    Tcl_DString *opts = &buf[1];
    TkTextTag **tagArray;
    TkTextTag *tagPtr;
    TkTextTag *tPtr;
    unsigned tagArrSize;
    unsigned epoch;
    unsigned what;
    int closeSubList;
    int result;
    int flags;

    result = GetDumpFlags(textPtr, interp, objc, objv, TK_DUMP_INSPECT_ALL, TK_DUMP_INSPECT_DFLT,
	    TK_DUMP_INSPECT_COMPLETE, &what, NULL, NULL, NULL, NULL);
    if (result != TCL_OK) {
	return result;
    }

    Tcl_DStringInit(str);
    Tcl_DStringInit(opts);
    sharedTextPtr = textPtr->sharedTextPtr;
    epoch = sharedTextPtr->inspectEpoch;
    tagPtr = textPtr->selTagPtr; /* any non-null value */
    nextPtr = textPtr->startMarker;
    closeSubList = 0;
    prevTagPtr = NULL;
    prevPtr = NULL;
    tagArrSize = 128;
    tagArray = (TkTextTag **)malloc(tagArrSize * sizeof(tagArray[0]));
    flags = 0;

    if (what & TK_DUMP_DONT_RESOLVE_FONTS)      { flags |= INSPECT_DONT_RESOLVE_FONTS; }
    if (what & TK_DUMP_DONT_RESOLVE_COLORS)     { flags |= INSPECT_DONT_RESOLVE_COLORS; }
    if (what & TK_DUMP_INCLUDE_DATABASE_CONFIG) { flags |= INSPECT_INCLUDE_DATABASE_CONFIG; }
    if (what & TK_DUMP_INCLUDE_SYSTEM_CONFIG)   { flags |= INSPECT_INCLUDE_SYSTEM_CONFIG; }
    if (what & TK_DUMP_INCLUDE_DEFAULT_CONFIG)  { flags |= INSPECT_INCLUDE_DEFAULT_CONFIG; }
    if (what & TK_DUMP_INCLUDE_SYSTEM_COLORS)   { flags |= INSPECT_INCLUDE_SYSTEM_COLORS; }

    assert(textPtr->selTagPtr->textPtr == textPtr);

    if (!(what & TK_DUMP_INCLUDE_SEL)) {
	/* this little trick is discarding the "sel" tag */
	textPtr->selTagPtr->textPtr = (TkText *) textPtr->selTagPtr;
    }

    if (what & TK_DUMP_TEXT_CONFIGS) {
	assert(textPtr->optionTable);
	TkTextInspectOptions(textPtr, textPtr, textPtr->optionTable, opts, flags);
	Tcl_DStringStartSublist(str);
	Tcl_DStringAppendElement(str, "setup");
	Tcl_DStringAppendElement(str, Tk_PathName(textPtr->tkwin));
	Tcl_DStringAppendElement(str, Tcl_DStringValue(opts));
	Tcl_DStringEndSublist(str);
    }

    if (what & TK_DUMP_TAG_CONFIGS) {
	TkTextTag **tags = textPtr->sharedTextPtr->tagLookup;
	unsigned n = textPtr->sharedTextPtr->numTags;
	unsigned i;

	for (i = 0; i < n; ++i) {
	    TkTextTag *tagPtr = tags[i];

	    if (tagPtr && ((what & TK_DUMP_INCLUDE_SEL) || !tagPtr->isSelTag)) {
		assert(tagPtr->optionTable);
		TkTextInspectOptions(textPtr, tagPtr, tagPtr->optionTable, opts, flags);
		Tcl_DStringStartSublist(str);
		Tcl_DStringAppendElement(str, "configure");
		Tcl_DStringAppendElement(str, tagPtr->name);
		if (Tcl_DStringLength(opts) > 2) {
		    Tcl_DStringAppendElement(str, Tcl_DStringValue(opts));
		}
		Tcl_DStringEndSublist(str);
	    }
	}
    }

    if (what & TK_DUMP_TAG_BINDINGS) {
	TkTextTag **tags = textPtr->sharedTextPtr->tagLookup;
	unsigned n = textPtr->sharedTextPtr->numTags;
	unsigned i;

	for (i = 0; i < n; ++i) {
	    TkTextTag *tagPtr = tags[i];

	    if (tagPtr
		    && sharedTextPtr->tagBindingTable
		    && ((what & TK_DUMP_INCLUDE_SEL) || !tagPtr->isSelTag)) {
		GetBindings(textPtr, tagPtr->name, sharedTextPtr->tagBindingTable, str);
	    }
	}
    }

    do {
	TkTextSegment *segPtr = nextPtr;
	unsigned group = segPtr->typePtr->group;
	const char *value = NULL;
	const char *type = NULL;
	int printTags = 0;

	nextPtr = segPtr->nextPtr;

	switch (group) {
	case SEG_GROUP_BRANCH:
	    if (segPtr->typePtr == &tkTextBranchType && (what & TK_DUMP_DISPLAY)) {
		segPtr = segPtr->body.branch.nextPtr;
		nextPtr = segPtr->nextPtr;
	    }
	    if (!(what & SEG_GROUP_BRANCH)) {
		continue;
	    }
	    type = "elide";
	    value = (segPtr->typePtr == &tkTextBranchType) ? "on" : "off";
	    break;
	case SEG_GROUP_IMAGE:
	    if (!(what & SEG_GROUP_IMAGE) || !segPtr->body.ei.name) {
		continue;
	    }
	    type = "image";
	    assert(segPtr->body.ei.optionTable);
	    TkTextInspectOptions(textPtr, &segPtr->body.ei, segPtr->body.ei.optionTable, opts, 0);
	    value = Tcl_DStringValue(opts);
	    printTags = !!(what & TK_DUMP_TAG);
	    break;
	case SEG_GROUP_WINDOW:
	    if (!(what & SEG_GROUP_WINDOW)) {
		continue;
	    }
	    type = "window";
	    assert(segPtr->body.ew.optionTable);
	    TkTextInspectOptions(textPtr, &segPtr->body.ew, segPtr->body.ew.optionTable, opts, 0);
	    value = Tcl_DStringValue(opts);
	    printTags = !!(what & TK_DUMP_TAG);
	    break;
	case SEG_GROUP_MARK:
	    if (segPtr == textPtr->endMarker) {
		if (prevPtr != segPtr
		    	&& (what & SEG_GROUP_CHAR)
			&& segPtr->sectionPtr->linePtr != TkBTreeGetLastLine(textPtr)) {
		    /* print newline before finishing */
		    type = "break";
		    printTags = !!(what & TK_DUMP_TAG);
		    tagPtr = TkBTreeGetSegmentTags(sharedTextPtr, segPtr->sectionPtr->linePtr->lastPtr,
			    textPtr, TK_TEXT_SORT_ASCENDING, NULL);
		    nextPtr = segPtr; /* repeat this mark */
		} else {
		    nextPtr = NULL; /* finished */
		}
	    } else if (!(what & SEG_GROUP_MARK)) {
		continue;
	    } else if (!TkTextIsNormalMark(segPtr)
		    && (!(what & TK_DUMP_INSERT_MARK) || segPtr != textPtr->insertMarkPtr)) {
		continue;
	    } else {
		type = (segPtr->typePtr == &tkTextLeftMarkType ? "left" : "right");
		value = TkTextMarkName(sharedTextPtr, textPtr, segPtr);
	    }
	    break;
	case SEG_GROUP_HYPHEN:
	    if (!(what & SEG_GROUP_HYPHEN)) {
		continue;
	    }
	    printTags = !!(what & TK_DUMP_TAG);
	    type = "hyphen";
	    break;
	case SEG_GROUP_CHAR:
	    if (what & SEG_GROUP_CHAR) {
		printTags = !!(what & TK_DUMP_TAG);
		if (prevPtr == segPtr || *segPtr->body.chars == '\n') {
		    type = "break";
		    nextPtr = segPtr->sectionPtr->linePtr->nextPtr->segPtr;
		    if (prevPtr == segPtr) {
			tagPtr = prevTagPtr;
			segPtr->body.chars[segPtr->size - 1] = '\n';
		    } else if (type && printTags) {
			tagPtr = TkBTreeGetSegmentTags(sharedTextPtr, segPtr, textPtr,
				TK_TEXT_SORT_ASCENDING, NULL);
		    }
		} else {
		    type = "text";
		    if (segPtr->size > 1 && segPtr->body.chars[segPtr->size - 1] == '\n') {
			nextPtr = segPtr; /* repeat this char segment */
			segPtr->body.chars[segPtr->size - 1] = '\0';
		    }
		    value = segPtr->body.chars;
		    if (printTags) {
			tagPtr = TkBTreeGetSegmentTags(sharedTextPtr, segPtr, textPtr,
				TK_TEXT_SORT_ASCENDING, NULL);
		    }
		}
	    } else if (!nextPtr) {
		nextPtr = segPtr->sectionPtr->linePtr->nextPtr->segPtr;
	    }
	    break;
	default:
	    continue;
	}

	if (closeSubList) {
	    if (what & TK_DUMP_NESTED) {
		unsigned nextEpoch = epoch + 1;
		unsigned numTags = 0;
		unsigned i;

		for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
		    if (tPtr->flag == epoch) {
			tPtr->flag = nextEpoch; /* mark as still open */
		    }
		}

		for ( ; prevTagPtr; prevTagPtr = prevTagPtr->succPtr) {
		    if (prevTagPtr->flag == epoch) { /* should be closed? */
			if (numTags == tagArrSize) {
			    tagArrSize *= 2;
			    tagArray = (TkTextTag **)realloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			}
			tagArray[numTags++] = prevTagPtr;
			prevTagPtr->flag = 0; /* mark as closed */
		    }
		}

		Tcl_DStringStartSublist(str);
		for (i = 0; i < numTags; ++i) {
		    Tcl_DStringAppendElement(str, tagArray[i]->name);
		}
		Tcl_DStringEndSublist(str);
	    }

	    prevTagPtr = NULL;
	    closeSubList = 0;
	    Tcl_DStringEndSublist(str);
	}

	if (type) {
	    Tcl_DStringStartSublist(str);
	    Tcl_DStringAppendElement(str, type);
	    if (value) {
		Tcl_DStringAppendElement(str, value);
	    }
	    closeSubList = 1;

	    if (printTags) {
		unsigned numTags = 0;
		unsigned i;

		prevTagPtr = tagPtr;

		if (what & TK_DUMP_NESTED) {
		    epoch += 1;

		    for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
			if (tPtr->flag != epoch) { /* should be opened? */
			    if (numTags == tagArrSize) {
				tagArrSize *= 2;
				tagArray = (TkTextTag **)realloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			    }
			    tagArray[numTags++] = tPtr;
			    tPtr->flag = epoch; /* mark as open */
			}
			tPtr->succPtr = tPtr->nextPtr;
		    }
		} else {
		    for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
			if (numTags == tagArrSize) {
			    tagArrSize *= 2;
			    tagArray = (TkTextTag **)realloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			}
			tagArray[numTags++] = tPtr;
		    }
		}

		Tcl_DStringStartSublist(str);
		for (i = 0; i < numTags; ++i) {
		    Tcl_DStringAppendElement(str, tagArray[i]->name);
		}
		Tcl_DStringEndSublist(str);
	    }
	}

	prevPtr = segPtr;
    } while (nextPtr);

    Tcl_SetObjResult(interp, Tcl_NewStringObj(Tcl_DStringValue(str), Tcl_DStringLength(str)));
    Tcl_DStringFree(str);
    Tcl_DStringFree(opts);
    free(tagArray);

    textPtr->selTagPtr->textPtr = textPtr; /* restore */
    sharedTextPtr->inspectEpoch = epoch;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * InspectRetainedUndoItems --
 *
 *	Return information about content of retained undo items, these
 *	items are not yet pushed onto undo stack.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Memory is allocated for the result.
 *
 *----------------------------------------------------------------------
 */

static void
InspectRetainedUndoItems(
    const TkSharedText *sharedTextPtr,
    Tcl_Obj *objPtr)
{
    if (sharedTextPtr->undoTagListCount > 0 || sharedTextPtr->undoMarkListCount > 0) {
	Tcl_Obj *resultPtr = Tcl_NewObj();
	unsigned i;
	int len;

	for (i = 0; i < sharedTextPtr->undoTagListCount; ++i) {
	    TkTextInspectUndoTagItem(sharedTextPtr, sharedTextPtr->undoTagList[i], resultPtr);
	}

	for (i = 0; i < sharedTextPtr->undoMarkListCount; ++i) {
	    TkTextInspectUndoMarkItem(sharedTextPtr, &sharedTextPtr->undoMarkList[i], resultPtr);
	}

	Tcl_ListObjLength(NULL, resultPtr, &len);
	if (len == 0) {
	    Tcl_DecrRefCount(resultPtr);
	} else {
	    Tcl_ListObjAppendElement(NULL, objPtr, resultPtr);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * InspectUndoStack --
 *
 *	Return information about content of undo/redo stack.
 *
 * Results:
 *	A Tcl object.
 *
 * Side effects:
 *	Memory is allocated for the result.
 *
 *----------------------------------------------------------------------
 */

static void
InspectUndoStack(
    const TkSharedText *sharedTextPtr,
    InspectUndoStackProc firstAtomProc,
    InspectUndoStackProc nextAtomProc,
    Tcl_Obj *objPtr)
{
    TkTextUndoStack undoStack;
    const TkTextUndoAtom *atom;
    Tcl_Obj *atomPtr;
    unsigned i;

    assert(sharedTextPtr->undoStack);

    undoStack = sharedTextPtr->undoStack;

    for (atom = firstAtomProc(undoStack); atom; atom = nextAtomProc(undoStack)) {
	atomPtr = Tcl_NewObj();

	for (i = 0; i < atom->arraySize; ++i) {
	    const TkTextUndoToken *token = (const TkTextUndoToken *) atom->array[i].item;
	    Tcl_Obj *subAtomPtr = token->undoType->inspectProc(sharedTextPtr, token);
	    Tcl_ListObjAppendElement(NULL, atomPtr, subAtomPtr);
	}

	Tcl_ListObjAppendElement(NULL, objPtr, atomPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextEditCmd --
 *
 *	Handle the subcommands to "$text edit ...". See documentation for
 *	details.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj *
GetCommand(
    const TkSharedText *sharedTextPtr,
    const TkTextUndoToken *token)
{
    assert(token);
    assert(token->undoType->commandProc);

    return token->undoType->commandProc(sharedTextPtr, token);
}

static int
TextEditCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    int index;
    int setModified;
    int oldModified;
    TkSharedText *sharedTextPtr;
    static const char *const editOptionStrings[] = {
	"altered",
#if SUPPORT_DEPRECATED_CANUNDO_REDO
	"canredo", "canundo",
#endif /* SUPPORT_DEPRECATED_CANUNDO_REDO */
	"info", "inspect", "irreversible", "modified", "recover", "redo", "reset",
	"separator", "undo", NULL
    };
    enum editOptions {
	EDIT_ALTERED,
#if SUPPORT_DEPRECATED_CANUNDO_REDO
	EDIT_CANREDO, EDIT_CANUNDO,
#endif /* SUPPORT_DEPRECATED_CANUNDO_REDO */
	EDIT_INFO, EDIT_INSPECT, EDIT_IRREVERSIBLE, EDIT_MODIFIED, EDIT_RECOVER, EDIT_REDO, EDIT_RESET,
	EDIT_SEPARATOR, EDIT_UNDO
    };

    sharedTextPtr = textPtr->sharedTextPtr;

    if (objc < 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "option ?arg ...?");
	return TCL_ERROR;
    }
    if (Tcl_GetIndexFromObjStruct(interp, objv[2], editOptionStrings,
	    sizeof(char *), "edit option", 0, &index) != TCL_OK) {
	return TCL_ERROR;
    }

    switch ((enum editOptions) index) {
    case EDIT_ALTERED:
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, "?boolean?");
	    return TCL_ERROR;
	}
	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(sharedTextPtr->isAltered));
	return TCL_OK;
	break;
#if SUPPORT_DEPRECATED_CANUNDO_REDO
    case EDIT_CANREDO: {
	static int warnDeprecated = 1;
	int canRedo = 0;

	if (warnDeprecated) {
	    warnDeprecated = 0;
	    fprintf(stderr, "tk::text: Command \"edit canredo\" is deprecated, "
		    "please use \"edit info\".\n");
	}
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, NULL);
	     return TCL_ERROR;
	}
	if (textPtr->sharedTextPtr->undoStack) {
	    canRedo = TkTextUndoGetCurrentRedoStackDepth(textPtr->sharedTextPtr->undoStack) > 0;
	}
	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(canRedo));
	break;
    }
    case EDIT_CANUNDO: {
	static int warnDeprecated = 1;
	int canUndo = 0;

	if (warnDeprecated) {
	    warnDeprecated = 0;
	    fprintf(stderr, "tk::text: Command \"edit canundo\" is deprecated, "
		    "please use \"edit info\".\n");
	}
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, NULL);
	     return TCL_ERROR;
	}
	if (textPtr->sharedTextPtr->undo) {
	    canUndo = TkTextUndoGetCurrentUndoStackDepth(textPtr->sharedTextPtr->undoStack) > 0;
	}
	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(canUndo));
	break;
    }
#endif /* SUPPORT_DEPRECATED_CANUNDO_REDO */
    case EDIT_INFO:
	if (objc != 3 && objc != 4 && (objc != 5 || strcmp(Tcl_GetString(objv[3]), "--") != 0)) {
	    /* NOTE: avoid trigraph */
	    Tcl_WrongNumArgs(interp, 3, objv, "\?\?--\? array? | ?-option?");
	    return TCL_ERROR;
	} else if (objc == 4 && *Tcl_GetString(objv[3]) == '-') {
	    Tcl_Obj* infoObj = GetEditInfo(interp, textPtr, objv[3]);
	    if (!infoObj) {
		return TCL_ERROR;
	    }
	    Tcl_SetObjResult(textPtr->interp, infoObj);
	} else {
	    Tcl_Obj* arrObj = (objc == 5 ? objv[4] : (objc == 4 ? objv[3] : NULL));
	    Tcl_SetObjResult(textPtr->interp, MakeEditInfo(interp, textPtr, arrObj));
	}
    	break;
    case EDIT_INSPECT:
	if (objc != 3 && objc != 4) {
	    Tcl_WrongNumArgs(interp, 3, objv, "?stack?");
	    return TCL_ERROR;
	} else {
	    char const *stack = (objc == 4) ? Tcl_GetString(objv[3]) : NULL;

	    if (stack && strcmp(stack, "undo") != 0 && strcmp(stack, "redo") != 0) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"bad stack argument \"%s\": must be \"undo\" or \"redo\"", stack));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "STACK_VALUE", NULL);
		return TCL_ERROR;
	    }
	    if (sharedTextPtr->undoStack) {
		Tcl_Obj *undoResultPtr = NULL;
		Tcl_Obj *redoResultPtr = NULL;

		if (!stack || stack[0] == 'u') {
		    undoResultPtr = Tcl_NewObj();
		    InspectRetainedUndoItems(sharedTextPtr, undoResultPtr);
		    InspectUndoStack(sharedTextPtr, TkTextUndoFirstUndoAtom,
			    TkTextUndoNextUndoAtom, undoResultPtr);
		}
		if (!stack || stack[0] == 'r') {
		    redoResultPtr = Tcl_NewObj();
		    InspectUndoStack(sharedTextPtr, TkTextUndoFirstRedoAtom,
			    TkTextUndoNextRedoAtom, redoResultPtr);
		}
		if (!stack) {
		    Tcl_Obj *objPtr = Tcl_NewObj();
		    Tcl_ListObjAppendElement(NULL, objPtr, undoResultPtr);
		    Tcl_ListObjAppendElement(NULL, objPtr, redoResultPtr);
		    Tcl_SetObjResult(interp, objPtr);
		} else if (stack[0] == 'u') {
		    Tcl_SetObjResult(interp, undoResultPtr);
		} else {
		    Tcl_SetObjResult(interp, redoResultPtr);
		}
	    }
	}
	break;
    case EDIT_IRREVERSIBLE:
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, "?boolean?");
	    return TCL_ERROR;
	}
	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(sharedTextPtr->isIrreversible));
	break;
    case EDIT_MODIFIED:
	if (objc == 3) {
	    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(sharedTextPtr->isModified));
	    return TCL_OK;
	} else if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 3, objv, "?boolean?");
	    return TCL_ERROR;
	} else if (Tcl_GetBooleanFromObj(interp, objv[3], &setModified) != TCL_OK) {
	    return TCL_ERROR;
	}

	/*
	 * Set or reset the modified status, and trigger a <<Modified>> event.
	 */

	oldModified = sharedTextPtr->isModified;
	sharedTextPtr->isModified = setModified;

	/*
	 * Setting the flag to 'false' is clearing the user's decision.
	 */

	sharedTextPtr->userHasSetModifiedFlag = setModified;
	if (sharedTextPtr->undoStack) {
	    sharedTextPtr->undoLevel = TkTextUndoGetCurrentUndoStackDepth(sharedTextPtr->undoStack);
	}

	/*
	 * Only issue the <<Modified>> event if the flag actually changed.
	 * However, degree of modified-ness doesn't matter. [Bug 1799782]
	 */

	assert(setModified == 1 || setModified == 0);

	if (oldModified != setModified) {
	    GenerateEvent(textPtr->sharedTextPtr, "Modified");
	}
	break;
    case EDIT_RECOVER:
	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, NULL);
	    return TCL_ERROR;
	}
	if (sharedTextPtr->undoStack) {
	    int redoDepth;

	    if (TkTextUndoIsPerformingUndoRedo(sharedTextPtr->undoStack)) {
		ErrorNotAllowed(interp, "cannot recover inside undo/redo operation");
		return TCL_ERROR;
	    }

	    redoDepth = TkTextUndoGetMaxRedoDepth(sharedTextPtr->undoStack);
	    PushRetainedUndoTokens(sharedTextPtr);
	    TkTextUndoSetMaxStackDepth(sharedTextPtr->undoStack, textPtr->maxUndoDepth, 0);

	    while (TkTextUndoGetCurrentUndoStackDepth(sharedTextPtr->undoStack) > 0) {
		TkTextUndoDoUndo(sharedTextPtr->undoStack);
	    }

	    TkTextUndoSetMaxStackDepth(sharedTextPtr->undoStack, textPtr->maxUndoDepth, redoDepth);
	}
    	break;
    case EDIT_REDO: {
	int result;

	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, NULL);
	    return TCL_ERROR;
	}

	if (TestIfDisabled(interp, textPtr, &result))
	    return result;

	if (sharedTextPtr->undoStack) {
	    /*
	     * It's possible that this command command will be invoked inside the "watch" callback,
	     * but this is not allowed when performing undo/redo.
	     */

	    if (TestIfPerformingUndoRedo(interp, sharedTextPtr, NULL))
		return TCL_ERROR;

	    PushRetainedUndoTokens(sharedTextPtr);

	    if (TkTextUndoGetCurrentRedoStackDepth(sharedTextPtr->undoStack) == 0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("nothing to redo", -1));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "NO_REDO", NULL);
		return TCL_ERROR;
	    }

	    TkTextUndoDoRedo(sharedTextPtr->undoStack);
	}
	break;
    }
    case EDIT_RESET:
	if (objc == 3) {
	    if (sharedTextPtr->undoStack) {
		/*
		 * It's possible that this command command will be invoked inside the "watch" callback,
		 * but this is not allowed when performing undo/redo.
		 */
		if (TestIfPerformingUndoRedo(interp, sharedTextPtr, NULL))
		    return TCL_ERROR;

		TkTextUndoClearStack(sharedTextPtr->undoStack);
		sharedTextPtr->undoLevel = 0;
		sharedTextPtr->pushSeparator = 0;
		sharedTextPtr->isAltered = 0;
		sharedTextPtr->isIrreversible = 0;
		TkTextUpdateAlteredFlag(sharedTextPtr);
	    }
	    return TCL_OK;
	} else if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 3, objv, "?stack?");
	    return TCL_ERROR;
	} else {
	    char const *stack = Tcl_GetString(objv[3]);

	    if (strcmp(stack, "undo") != 0 && strcmp(stack, "redo") != 0) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"bad stack argument \"%s\": must be \"undo\" or \"redo\"", stack));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "STACK_VALUE", NULL);
		return TCL_ERROR;
	    }
	    if (sharedTextPtr->undoStack) {
		if (TestIfPerformingUndoRedo(interp, sharedTextPtr, NULL))
		    return TCL_ERROR;

		if (stack[0] == 'u') {
		    TkTextUndoClearUndoStack(sharedTextPtr->undoStack);
		    sharedTextPtr->undoLevel = 0;
		    sharedTextPtr->pushSeparator = 0;
		    sharedTextPtr->isAltered = 0;
		    sharedTextPtr->isIrreversible = 0;
		    TkTextUpdateAlteredFlag(sharedTextPtr);
		} else {
		    TkTextUndoClearRedoStack(sharedTextPtr->undoStack);
		}
	    }
	    return TCL_ERROR;
	}
	break;
    case EDIT_SEPARATOR: {
	int immediately = 0;

	if (objc == 4) {
	    if (strcmp(Tcl_GetString(objv[3]), "-immediately")) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf(
			"bad option \"%s\": must be -immediately", Tcl_GetString(objv[3])));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "INDEX_OPTION", NULL);
		return TCL_ERROR;
	    }
	    immediately = 1;
	} else if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, NULL);
	    return TCL_ERROR;
	}
	if (sharedTextPtr->undoStack) {
	    sharedTextPtr->pushSeparator = 1;
	    if (immediately) {
		/* last two args are meaningless here */
		PushUndoSeparatorIfNeeded(sharedTextPtr, sharedTextPtr->autoSeparators,
			TK_TEXT_EDIT_OTHER);
	    }
	}
	break;
    }
    case EDIT_UNDO: {
	int result;

	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 3, objv, NULL);
	    return TCL_ERROR;
	}

	if (TestIfDisabled(interp, textPtr, &result))
	    return result;

	if (sharedTextPtr->undoStack) {
	    /*
	     * It's possible that this command command will be invoked inside the "watch" callback,
	     * but this is not allowed when performing undo/redo.
	     */

	    if (TestIfPerformingUndoRedo(interp, sharedTextPtr, &result))
		return result;

	    PushRetainedUndoTokens(sharedTextPtr);

	    if (TkTextUndoGetCurrentUndoStackDepth(sharedTextPtr->undoStack) == 0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("nothing to undo", -1));
		Tcl_SetErrorCode(interp, "TK", "TEXT", "NO_UNDO", NULL);
		return TCL_ERROR;
	    }

	    TkTextUndoDoUndo(sharedTextPtr->undoStack);
	}
	break;
    }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetEditInfo --
 *
 *	Returns the value containing the "edit info -option" information.
 *
 * Results:
 *	Tcl_Obj containing the required information.
 *
 * Side effects:
 *	Some memory will be allocated.
 *
 *----------------------------------------------------------------------
 */
enum {
    INFO_BYTESIZE, INFO_GENERATEDMARKS, INFO_IMAGES, INFO_LINES, INFO_LINESPERNODE, INFO_MARKS,
    INFO_REDOBYTESIZE, INFO_REDOCOMMANDS, INFO_REDODEPTH, INFO_REDOSTACKSIZE, INFO_TAGS,
    INFO_TOTALBYTESIZE, INFO_TOTALLINES, INFO_UNDOBYTESIZE, INFO_UNDOCOMMANDS, INFO_UNDODEPTH,
    INFO_UNDOSTACKSIZE, INFO_USEDTAGS, INFO_VISIBLEIMAGES, INFO_VISIBLEWINDOWS, INFO_WINDOWS,
    INFO_LAST /* must be last item */
};
static const char *const editInfoStrings[] = {
    "-bytesize", "-generatedmarks", "-images", "-lines", "-linespernode", "-marks",
    "-redobytesize", "-redocommands", "-redodepth", "-redostacksize", "-tags",
    "-totalbytesize", "-totallines", "-undobytesize", "-undocommands", "-undodepth",
    "-undostacksize", "-usedtags", "-visibleimages", "-visiblewindows", "-windows", NULL
};

static void
MakeStackInfoValue(
    Tcl_Interp *interp,
    TkSharedText *sharedTextPtr,
    Tcl_Obj* resultPtr)
{
    TkTextUndoStack st = sharedTextPtr->undoStack;
    const TkTextUndoAtom *atom;
    int i;

    for (i = sharedTextPtr->undoTagListCount - 1; i >= 0; --i) {
	const TkTextTag *tagPtr = sharedTextPtr->undoTagList[i];

	if (tagPtr->recentTagAddRemoveToken && !tagPtr->recentTagAddRemoveTokenIsNull) {
	    Tcl_ListObjAppendElement(interp, resultPtr,
		    GetCommand(sharedTextPtr, tagPtr->recentTagAddRemoveToken));
	}
	if (tagPtr->recentChangePriorityToken && tagPtr->savedPriority != tagPtr->priority) {
	    Tcl_ListObjAppendElement(interp, resultPtr,
		    GetCommand(sharedTextPtr, tagPtr->recentChangePriorityToken));
	}
    }

    for (i = sharedTextPtr->undoMarkListCount - 1; i >= 0; --i) {
	const TkTextMarkChange *changePtr = &sharedTextPtr->undoMarkList[i];

	if (changePtr->setMark) {
	    Tcl_ListObjAppendElement(interp, resultPtr,
		    GetCommand(sharedTextPtr, changePtr->setMark));
	}
	if (changePtr->moveMark) {
	    Tcl_ListObjAppendElement(interp, resultPtr,
		    GetCommand(sharedTextPtr, changePtr->moveMark));
	}
	if (changePtr->toggleGravity) {
	    Tcl_ListObjAppendElement(interp, resultPtr,
		    GetCommand(sharedTextPtr, changePtr->toggleGravity));
	}
    }

    atom = TkTextUndoIsPerformingUndo(st) ?
	    TkTextUndoCurrentRedoAtom(st) : TkTextUndoCurrentUndoAtom(st);

    if (atom) {
	for (i = atom->arraySize - 1; i >= 0; --i) {
	    const TkTextUndoSubAtom *subAtom = atom->array + i;
	    TkTextUndoToken *token = (TkTextUndoToken *)subAtom->item;

	    Tcl_ListObjAppendElement(interp, resultPtr, GetCommand(sharedTextPtr, token));
	}
    }
}

static Tcl_Obj *
MakeEditInfoValue(
    Tcl_Interp *interp,
    TkText *textPtr,
    int optionIndex)
{
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    TkTextUndoStack st = sharedTextPtr->undoStack;

    assert(optionIndex >= 0);
    assert(optionIndex < INFO_LAST);

    switch (optionIndex) {
    case INFO_UNDOSTACKSIZE:
	return Tcl_NewIntObj(st ? TkTextUndoCountUndoItems(st) : 0);
    case INFO_REDOSTACKSIZE:
	return Tcl_NewIntObj(st ? TkTextUndoCountRedoItems(st) : 0);
    case INFO_UNDODEPTH:
	return Tcl_NewIntObj(st ? TkTextUndoGetCurrentUndoStackDepth(st) : 0);
    case INFO_REDODEPTH:
	return Tcl_NewIntObj(st ? TkTextUndoGetCurrentRedoStackDepth(st) : 0);
    case INFO_UNDOBYTESIZE:
	return Tcl_NewIntObj(st ? TkTextUndoGetCurrentUndoSize(st) : 0);
    case INFO_REDOBYTESIZE:
	return Tcl_NewIntObj(st ? TkTextUndoGetCurrentRedoSize(st) : 0);
    case INFO_BYTESIZE:
	return Tcl_NewIntObj(TkBTreeSize(sharedTextPtr->tree, textPtr));
    case INFO_TOTALBYTESIZE:
	return Tcl_NewIntObj(TkBTreeSize(sharedTextPtr->tree, NULL));
    case INFO_LINES:
	return Tcl_NewIntObj(TkrBTreeNumLines(sharedTextPtr->tree, textPtr));
    case INFO_TOTALLINES:
	return Tcl_NewIntObj(TkrBTreeNumLines(sharedTextPtr->tree, NULL));
    case INFO_IMAGES:
	return Tcl_NewIntObj(sharedTextPtr->numImages);
    case INFO_WINDOWS:
	return Tcl_NewIntObj(sharedTextPtr->numWindows);
    case INFO_VISIBLEIMAGES:
	return Tcl_NewIntObj(TkTextCountVisibleImages(textPtr));
    case INFO_VISIBLEWINDOWS:
	return Tcl_NewIntObj(TkTextCountVisibleWindows(textPtr));
    case INFO_TAGS:
	return Tcl_NewIntObj(sharedTextPtr->numTags);
    case INFO_USEDTAGS:
	return Tcl_NewIntObj(TkTextTagSetCount(TkBTreeRootTagInfo(sharedTextPtr->tree)));
    case INFO_MARKS:
	return Tcl_NewIntObj(sharedTextPtr->numMarks);
    case INFO_GENERATEDMARKS:
	return Tcl_NewIntObj(sharedTextPtr->numPrivateMarks);
    case INFO_LINESPERNODE:
	return Tcl_NewIntObj(TkBTreeLinesPerNode(sharedTextPtr->tree));
    case INFO_UNDOCOMMANDS: {
	Tcl_Obj* obj = Tcl_NewObj();
	if (st && !TkTextUndoIsPerformingUndo(st)) {
	    MakeStackInfoValue(interp, sharedTextPtr, obj);
	}
	return obj;
    }
    case INFO_REDOCOMMANDS: {
	Tcl_Obj* obj = Tcl_NewObj();
	if (st && TkTextUndoIsPerformingUndo(st)) {
	    MakeStackInfoValue(interp, sharedTextPtr, obj);
	}
	return obj;
    }
    }

    return NULL; /* never reached */
}

static Tcl_Obj *
GetEditInfo(
    Tcl_Interp *interp,		/* Current interpreter. */
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Obj *option)		/* Name of resource. */
{
    int optionIndex;

    if (Tcl_GetIndexFromObjStruct(interp, option, editInfoStrings,
	    sizeof(char *), "option", 0, &optionIndex) != TCL_OK) {
	return NULL;
    }

    return MakeEditInfoValue(interp, textPtr, optionIndex);
}

/*
 *----------------------------------------------------------------------
 *
 * MakeEditInfo --
 *
 *	Returns the array containing the "edit info" information.
 *
 * Results:
 *	Tcl_Obj of list type containing the required information.
 *
 * Side effects:
 *	Some memory will be allocated.
 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj *
MakeEditInfo(
    Tcl_Interp *interp,		/* Current interpreter. */
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Obj *arrayPtr)		/* Name of array, may be NULL. */
{
    Tcl_Obj *var = arrayPtr ? arrayPtr : Tcl_NewStringObj("", 0);
    int i;

    Tcl_UnsetVar(interp, Tcl_GetString(var), 0);
    for (i = 0; i < INFO_LAST; ++i) {
	Tcl_ObjSetVar2(interp, var, Tcl_NewStringObj(editInfoStrings[i] + 1, -1),
		MakeEditInfoValue(interp, textPtr, i), 0);
    }
    return var;
}

/*
 *----------------------------------------------------------------------
 *
 * TextGetText --
 *
 *	Returns the text from indexPtr1 to indexPtr2, placing that text in a
 *	string object which is returned with a refCount of zero.
 *
 *	Since the amount of text may potentially be several megabytes (e.g.
 *	in text editors built on the text widget), efficiency is very
 *	important. We may want to investigate the efficiency of the
 *	Tcl_AppendToObj more carefully (e.g. if we know we are going to be
 *	appending several thousand lines, we could attempt to pre-allocate a
 *	larger space).
 *
 * Results:
 *	Tcl_Obj of string type containing the specified text. If the
 *	visibleOnly flag is set to true, then only those characters which are not
 *	elided will be returned. Otherwise (flag is false) all characters in the
 *	given range are returned.
 *
 * Side effects:
 *	Memory will be allocated for the new object. Remember to free it if it
 *	isn't going to be stored appropriately.
 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj *
TextGetText(
    TkText *textPtr,		/* Information about text widget. */
    const TkTextIndex *indexPtr1,
				/* Get text from this index... */
    const TkTextIndex *indexPtr2,
				/* ...to this index. */
    TkTextIndex *lastIndexPtr,	/* Position before last character of the result, can be NULL. */
    Tcl_Obj *resultPtr,		/* Append text to this object, can be NULL. */
    unsigned maxBytes,		/* Maximal number of bytes. */
    int visibleOnly,		/* If true, then only return non-elided characters. */
    int includeHyphens)	/* If true, then also include soft hyphens. */
{
    TkTextSegment *segPtr, *lastPtr;
    TkTextIndex index;
    int offset1, offset2;

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

    if (!resultPtr) {
	resultPtr = Tcl_NewObj();
    }

    segPtr = TkTextIndexGetContentSegment(indexPtr1, &offset1);
    if (lastIndexPtr) {
	*lastIndexPtr = *indexPtr2;
    }

    if (visibleOnly && TkTextSegmentIsElided(textPtr, segPtr)) {
	index = *indexPtr1;
	if (!TkTextSkipElidedRegion(&index) || TkTextIndexCompare(&index, indexPtr2) >= 0) {
	    return resultPtr; /* end of text reached */
	}
	segPtr = TkTextIndexGetContentSegment(&index, &offset1);
    }

    lastPtr = TkTextIndexGetContentSegment(indexPtr2, &offset2);

    if (segPtr == lastPtr) {
	if (segPtr->typePtr == &tkTextCharType) {
	    Tcl_AppendToObj(resultPtr, segPtr->body.chars + offset1,
		    MIN(maxBytes, (unsigned) (offset2 - offset1)));
	}
    } else {
	TkTextLine *linePtr = segPtr->sectionPtr->linePtr;

	TkTextIndexClear(&index, textPtr);

	if (segPtr->typePtr == &tkTextCharType) {
	    unsigned nbytes = MIN(maxBytes, (unsigned) segPtr->size - offset1);
	    Tcl_AppendToObj(resultPtr, segPtr->body.chars + offset1, nbytes);
	    if ((maxBytes -= nbytes) == 0) {
		return resultPtr;
	    }
	} else if (segPtr->typePtr == &tkTextHyphenType) {
	    if (includeHyphens) {
		if (maxBytes < 2) {
		    return resultPtr;
		}
		Tcl_AppendToObj(resultPtr, "\xc2\xad", 2); /* U+00AD */
		if ((maxBytes -= 2u) == 0) {
		    return resultPtr;
		}
	    }
	} else if (segPtr->typePtr == &tkTextBranchType) {
	    if (visibleOnly) {
		TkTextIndexSetSegment(&index, segPtr = segPtr->body.branch.nextPtr);
		if (TkTextIndexRestrictToEndRange(&index) >= 0) {
		    return resultPtr; /* end of text reached */
		}
		linePtr = segPtr->sectionPtr->linePtr;
	    }
	}
	if (!(segPtr = segPtr->nextPtr)) {
	    assert(linePtr->nextPtr);
	    linePtr = linePtr->nextPtr;
	    segPtr = linePtr->segPtr;
	}
	while (segPtr != lastPtr) {
	    if (segPtr->typePtr == &tkTextCharType) {
		unsigned nbytes = MIN(maxBytes, (unsigned) segPtr->size);
		Tcl_AppendToObj(resultPtr, segPtr->body.chars, nbytes);
		if ((maxBytes -= nbytes) == 0) {
		    if (lastIndexPtr) {
			TkTextIndexSetSegment(lastIndexPtr, segPtr);
			TkTextIndexAddToByteIndex(lastIndexPtr, nbytes);
		    }
		    return resultPtr; /* end of text reached */
		}
	    } else if (segPtr->typePtr == &tkTextHyphenType) {
		if (includeHyphens) {
		    if (maxBytes < 2) {
			return resultPtr;
		    }
		    Tcl_AppendToObj(resultPtr, "\xc2\xad", 2); /* U+00AD */
		    if ((maxBytes -= 2) == 0) {
			return resultPtr;
		    }
		}
	    } else if (segPtr->typePtr == &tkTextBranchType) {
		if (visibleOnly) {
		    TkTextIndexSetSegment(&index, segPtr = segPtr->body.branch.nextPtr);
		    if (TkTextIndexRestrictToEndRange(&index) >= 0) {
			return resultPtr; /* end of text reached */
		    }
		    linePtr = segPtr->sectionPtr->linePtr;
		}
	    }
	    if (!(segPtr = segPtr->nextPtr)) {
		assert(linePtr->nextPtr);
		linePtr = linePtr->nextPtr;
		segPtr = linePtr->segPtr;
	    }
	}
	if (offset2 > 0) {
	    Tcl_AppendToObj(resultPtr, segPtr->body.chars, MIN(maxBytes, (unsigned) offset2));
	}
    }

    return resultPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TriggerWatchEdit --
 *
 *	Trigger the watch command for delete/insert operations, see the
 *	documentation for details on what it does.
 *
 * Results:
 *	Returns 'false' if the referenced widget has been destroyed, otherwise
 *	'true' will be returned.
 *
 * Side effects:
 *	It might happen that the receiver of the "watch" command is destroying the widget.
 *
 *----------------------------------------------------------------------
 */

static void
AppendTags(
    Tcl_DString *buf,
    TkTextTag *tagPtr)
{
    Tcl_DStringStartSublist(buf);
    for ( ; tagPtr; tagPtr = tagPtr->nextPtr) {
	Tcl_DStringAppendElement(buf, tagPtr->name);
    }
    Tcl_DStringEndSublist(buf);
}

static int
TriggerWatchEdit(
    TkText *textPtr,			/* Information about text widget. */
    int userFlag,			/* Trigger due to user modification? */
    const char *operation,		/* The triggering operation. */
    const TkTextIndex *indexPtr1,	/* Start index for deletion / insert. */
    const TkTextIndex *indexPtr2,	/* End index after insert / before deletion. */
    const char *string,			/* Deleted/inserted chars. */
    int final)				/* Flag indicating whether this is a final part. */
{
    TkSharedText *sharedTextPtr;
    TkText *peerArr[20];
    TkText **peers = peerArr;
    TkText *tPtr;
    unsigned i, n = 0;
    unsigned numPeers;
    int rc = 1;

    assert(textPtr->sharedTextPtr->triggerWatchCmd);
    assert(!indexPtr1 == !indexPtr2);
    assert(strcmp(operation, "insert") == 0 || strcmp(operation, "delete") == 0);

    sharedTextPtr = textPtr->sharedTextPtr;
    sharedTextPtr->triggerWatchCmd = 0; /* do not trigger recursively */
    numPeers = sharedTextPtr->numPeers;

    if (sharedTextPtr->numPeers > sizeof(peerArr) / sizeof(peerArr[0])) {
	peers = (TkText **)malloc(sharedTextPtr->numPeers * sizeof(peerArr[0]));
    }

    /*
     * Firstly save all peers, we have to take into account that the list of
     * peers is changing when executing the "watch" command.
     */

    peers[n++] = textPtr;
    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	if (tPtr != textPtr) {
	    peers[n++] = tPtr;
	}
	tPtr->refCount += 1;
    }

    for (i = 0; i < sharedTextPtr->numPeers; ++i) {
	TkText *tPtr = peers[i];

	if (tPtr->watchCmd && (userFlag || tPtr->triggerAlways) && !(tPtr->flags & DESTROYED)) {
	    TkTextIndex index[4];

	    if (indexPtr1) {
		TkTextSegment *startMarker;
		TkTextSegment *endMarker;
		int cmp;

		index[0] = *indexPtr1;
		index[1] = *indexPtr2;

		startMarker = tPtr->startMarker;
		endMarker = tPtr->endMarker;

		if (startMarker != sharedTextPtr->startMarker) {
		    TkTextIndex start;
		    TkTextIndexClear(&start, tPtr);
		    TkTextIndexSetSegment(&start, startMarker);
		    if (TkTextIndexCompare(&start, &index[0]) > 0) {
			index[0] = start;
		    }
		}
		if (endMarker != sharedTextPtr->endMarker) {
		    TkTextIndex end;
		    TkTextIndexClear(&end, tPtr);
		    TkTextIndexSetSegment(&end, endMarker);
		    if (TkTextIndexCompare(&end, &index[1]) < 0) {
			index[1] = end;
		    }
		}

		if ((cmp = TkTextIndexCompare(&index[0], &index[1])) <= 0) {
		    TkTextTag *tagPtr;
		    TkTextIndex myIndex;
		    Tcl_DString buf;
		    char idx[2][TK_POS_CHARS];
		    char const *arg;

		    TkrTextPrintIndex(tPtr, &index[0], idx[0]);
		    TkrTextPrintIndex(tPtr, &index[1], idx[1]);

		    Tcl_DStringInit(&buf);
		    Tcl_DStringAppendElement(&buf, string);

		    tagPtr = NULL;
		    if (TkTextIndexBackChars(tPtr, &index[0], 1, &myIndex, COUNT_CHARS)) {
			tagPtr = TkBTreeGetTags(&myIndex, TK_TEXT_SORT_ASCENDING, NULL);
		    }
		    AppendTags(&buf, tagPtr);
		    AppendTags(&buf, TkBTreeGetTags(&index[1], TK_TEXT_SORT_ASCENDING, NULL));
		    AppendTags(&buf, cmp == 0 ? NULL :
			    TkBTreeGetTags(&index[0], TK_TEXT_SORT_ASCENDING, NULL));
		    if (*operation == 'd') {
			tagPtr = NULL;
			if (cmp && TkTextIndexBackChars(tPtr, &index[1], 1, &myIndex, COUNT_CHARS)) {
			    tagPtr = TkBTreeGetTags(&myIndex, TK_TEXT_SORT_ASCENDING, NULL);
			}
			AppendTags(&buf, tagPtr);
		    }
		    Tcl_DStringAppendElement(&buf, final ? "yes" : "no");
		    arg = Tcl_DStringValue(&buf);

		    if (!TkTextTriggerWatchCmd(tPtr, operation, idx[0], idx[1],
				arg, NULL, NULL, userFlag)
			    && tPtr == textPtr) {
			rc = 0; /* this widget has been destroyed */
		    }

		    Tcl_DStringFree(&buf);
		}
	    } else {
		if (!TkTextTriggerWatchCmd(textPtr, operation, NULL, NULL, NULL, NULL, NULL, userFlag)
			&& tPtr == textPtr) {
		    rc = 0; /* this widget has been destroyed */
		}
	    }
	}

	if (TkTextDecrRefCountAndTestIfDestroyed(tPtr)) {
	    numPeers -= 1;
	}
    }

    if (peers != peerArr) {
	free(peers);
    }
    if (numPeers > 0) { /* otherwise sharedTextPtr is not valid anymore */
	sharedTextPtr->triggerWatchCmd = 1;
    }

    return rc;
}

/*
 *--------------------------------------------------------------
 *
 * TkTextPerformWatchCmd --
 *
 *	This function is performs triggering of the watch
 *	command for all peers.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	See function TkTextTriggerWatchCmd.
 *
 *--------------------------------------------------------------
 */

void
TkTextPerformWatchCmd(
    TkSharedText *sharedTextPtr,
    TkText *textPtr,			/* Firstly trigger watch command of this peer, can be NULL. */
    const char *operation,		/* The trigger operation. */
    TkTextWatchGetIndexProc index1Proc,	/* Function pointer for fst index, can be NULL. */
    ClientData index1ProcData,		/* Client data for index1Proc. */
    TkTextWatchGetIndexProc index2Proc,	/* Function pointer for snd index, can be NULL. */
    ClientData index2ProcData,		/* Client data for index2Proc. */
    const char *arg1,			/* 3rd argument for watch command, can be NULL. */
    const char *arg2,			/* 3rd argument for watch command, can be NULL. */
    const char *arg3,			/* 3rd argument for watch command, can be NULL. */
    int userFlag)			/* 4rd argument for watch command. */
{
    TkText *peerArr[20];
    TkText **peers = peerArr;
    TkText *tPtr;
    unsigned numPeers = 0;
    unsigned i;
    (void)userFlag;

    assert(sharedTextPtr);
    assert(sharedTextPtr->triggerWatchCmd);
    assert(operation);
    assert(!index2Proc || index1Proc);

    sharedTextPtr->triggerWatchCmd = 0; /* do not trigger recursively */

    if (sharedTextPtr->numPeers > sizeof(peerArr) / sizeof(peerArr[0])) {
	peers = (TkText **)malloc(sharedTextPtr->numPeers * sizeof(peerArr[0]));
    }
    if (textPtr) {
	peers[numPeers++] = textPtr;
	textPtr->refCount += 1;
    }
    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	if (tPtr != textPtr && tPtr->watchCmd) {
	    peers[numPeers++] = tPtr;
	    tPtr->refCount += 1;
	}
    }
    for (i = 0; i < numPeers; ++i) {
	tPtr = peers[i];

	if (!(tPtr->flags & DESTROYED)) {
	    char idx[2][TK_POS_CHARS];
	    TkTextIndex index[2];

	    if (index1Proc) {
		index1Proc(tPtr, &index[0], index1ProcData);
		TkrTextPrintIndex(tPtr, &index[0], idx[0]);

		if (index2Proc) {
		    index2Proc(tPtr, &index[1], index2ProcData);
		    TkrTextPrintIndex(tPtr, &index[1], idx[1]);
		} else {
		    memcpy(idx[1], idx[0], TK_POS_CHARS);
		}
	    }

	    TkTextTriggerWatchCmd(tPtr, operation, idx[0], idx[1], arg1, arg2, arg3, 0);
	}
    }

    sharedTextPtr->triggerWatchCmd = 1;

    for (i = 0; i < numPeers; ++i) {
	TkTextDecrRefCountAndTestIfDestroyed(peers[i]);
    }
    if (peers != peerArr) {
	free(peers);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextTriggerWatchCmd --
 *
 *	Trigger the watch command, see the documentation for details on
 *	what it does.
 *
 * Results:
 *	Returns 'false' if this peer has been destroyed, otherwise 'true'
 *	will be returned.
 *
 * Side effects:
 *	It might happen that the receiver of the "watch" command is destroying the widget.
 *
 *----------------------------------------------------------------------
 */

int
TkTextTriggerWatchCmd(
    TkText *textPtr,		/* Information about text widget. */
    const char *operation,	/* The trigger operation. */
    const char *index1,		/* 1st argument for watch command, can be NULL. */
    const char *index2,		/* 2nd argument for watch command, can be NULL. */
    const char *arg1,		/* 3rd argument for watch command, can be NULL. */
    const char *arg2,		/* 3rd argument for watch command, can be NULL. */
    const char *arg3,		/* 3rd argument for watch command, can be NULL. */
    int userFlag)		/* 4rd argument for watch command. */
{
    Tcl_DString cmd;

    assert(textPtr);
    assert(textPtr->watchCmd);
    assert(operation);

    Tcl_DStringInit(&cmd);
    Tcl_DStringAppend(&cmd, Tcl_GetString(textPtr->watchCmd), -1);
    Tcl_DStringAppendElement(&cmd, Tk_PathName(textPtr->tkwin));
    Tcl_DStringAppendElement(&cmd, operation);
    Tcl_DStringAppendElement(&cmd, index1 ? index1 : "");
    Tcl_DStringAppendElement(&cmd, index2 ? index2 : "");
    Tcl_DStringStartSublist(&cmd);
    if (arg1) { Tcl_DStringAppendElement(&cmd, arg1); }
    if (arg2) { Tcl_DStringAppendElement(&cmd, arg2); }
    if (arg3) { Tcl_DStringAppendElement(&cmd, arg3); }
    Tcl_DStringEndSublist(&cmd);
    Tcl_DStringAppendElement(&cmd, userFlag ? "yes" : "no");

    textPtr->refCount += 1;

    Tcl_Preserve((ClientData) textPtr->interp);
    if (Tcl_EvalEx(textPtr->interp, Tcl_DStringValue(&cmd), Tcl_DStringLength(&cmd), 0) != TCL_OK) {
	Tcl_AddErrorInfo(textPtr->interp, "\n    (triggering the \"watch\" command failed)");
	Tcl_BackgroundException(textPtr->interp, TCL_ERROR);
    }
    Tcl_Release((ClientData) textPtr->interp);

    Tcl_DStringFree(&cmd);
    return !TkTextDecrRefCountAndTestIfDestroyed(textPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * GenerateEvent --
 *
 *	Send an event about a new state. This is equivalent to:
 *	   event generate $textWidget <<TYPE>>
 *	for all peers of this text widget.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	May force the text window into existence.
 *
 *----------------------------------------------------------------------
 */

static void
GenerateEvent(
    TkSharedText *sharedTextPtr,
    const char *type)
{
    TkText *textPtr;

    for (textPtr = sharedTextPtr->peers; textPtr; textPtr = textPtr->next) {
	Tk_MakeWindowExist(textPtr->tkwin);
	Tk_SendVirtualEvent(textPtr->tkwin, type, NULL);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * UpdateModifiedFlag --
 *
 *	Updates the modified flag of the text widget.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
UpdateModifiedFlag(
    TkSharedText *sharedTextPtr,
    int flag)
{
    int oldModifiedFlag = sharedTextPtr->isModified;

    if (flag) {
	sharedTextPtr->isModified = 1;
    } else if (sharedTextPtr->undoStack && !sharedTextPtr->userHasSetModifiedFlag) {
	if (sharedTextPtr->insertDeleteUndoTokenCount > 0) {
	    sharedTextPtr->isModified = 1;
	} else {
	    unsigned undoDepth = TkTextUndoGetCurrentUndoStackDepth(sharedTextPtr->undoStack);
	    sharedTextPtr->isModified = (undoDepth > 0 && undoDepth == sharedTextPtr->undoLevel);
	}
    }

    if (oldModifiedFlag != sharedTextPtr->isModified) {
	sharedTextPtr->userHasSetModifiedFlag = 0;
	GenerateEvent(sharedTextPtr, "Modified");
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextUpdateAlteredFlag --
 *
 *	Updates the "altered" flag of the text widget.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextUpdateAlteredFlag(
    TkSharedText *sharedTextPtr)/* Information about text widget. */
{
    int oldIsAlteredFlag = sharedTextPtr->isAltered;
    int oldIsIrreversibleFlag = sharedTextPtr->isIrreversible;

    if (sharedTextPtr->undoStack) {
	if (TkTextUndoContentIsIrreversible(sharedTextPtr->undoStack)) {
	    sharedTextPtr->isIrreversible = 1;
	}
	if (!sharedTextPtr->isIrreversible) {
	    sharedTextPtr->isAltered = sharedTextPtr->undoTagListCount > 0
		    || sharedTextPtr->undoMarkListCount > 0
		    || TkTextUndoGetCurrentUndoStackDepth(sharedTextPtr->undoStack) > 0;
	}
    } else {
	sharedTextPtr->isIrreversible = 1;
    }
    if (sharedTextPtr->isIrreversible) {
	sharedTextPtr->isAltered = 1;
    }
    if (oldIsAlteredFlag != sharedTextPtr->isAltered) {
	GenerateEvent(sharedTextPtr, "Altered");
    }
    if (oldIsIrreversibleFlag != sharedTextPtr->isIrreversible) {
	GenerateEvent(sharedTextPtr, "Irreversible");
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextRunAfterSyncCmd --
 *
 *	This function executes the command scheduled by
 *	[.text sync -command $cmd], if any.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Anything may happen, depending on $cmd contents.
 *
 *----------------------------------------------------------------------
 */

void
TkTextRunAfterSyncCmd(
    TkText *textPtr)	/* Information about text widget. */
{
    int code;
    int error = 0;
    Tcl_Obj *afterSyncCmd;

    assert(!TkTextPendingSync(textPtr));

    textPtr->pendingAfterSync = 0;
    afterSyncCmd = textPtr->afterSyncCmd;

    if (!afterSyncCmd) {
	return;
    }

    /*
     * We have to expect nested calls, futhermore the receiver might destroy the widget.
     */

    textPtr->afterSyncCmd = NULL;
    textPtr->refCount += 1;

    Tcl_Preserve((ClientData) textPtr->interp);
    if (!(textPtr->flags & DESTROYED)) {
	code = Tcl_EvalObjEx(textPtr->interp, afterSyncCmd, TCL_EVAL_GLOBAL);
	if (code == TCL_ERROR && !error) {
	    Tcl_AddErrorInfo(textPtr->interp, "\n    (text sync)");
	    Tcl_BackgroundException(textPtr->interp, TCL_ERROR);
	    error = 1;
	}
    }
    Tcl_GuardedDecrRefCount(afterSyncCmd);
    Tcl_Release((ClientData) textPtr->interp);
    TkTextDecrRefCountAndTestIfDestroyed(textPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RunAfterSyncCmd --
 *
 *	This function is called by the event loop and executes the command
 *      scheduled by [.text sync -command $cmd].
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Anything may happen, depending on $cmd contents.
 *
 *----------------------------------------------------------------------
 */

static void
RunAfterSyncCmd(
    ClientData clientData)	/* Information about text widget. */
{
    TkText *textPtr = (TkText *) clientData;

    if (!(textPtr->flags & DESTROYED)) {
	if (TkTextPendingSync(textPtr)) {
	    /* Too late here, the widget is not in sync, so we have to wait. */
	} else {
	    TkTextRunAfterSyncCmd(textPtr);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGenerateWidgetViewSyncEvent --
 *
 *      Send the <<WidgetViewSync>> event related to the text widget
 *      line metrics asynchronous update.
 *      This is equivalent to:
 *         event generate $textWidget <<WidgetViewSync>> -detail $s
 *      where $s is the sync status: true (when the widget view is in
 *      sync with its internal data) or false (when it is not).
 *
 *	Note that this has to be done in the idle loop, otherwise vwait
 *	will not return.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      If corresponding bindings are present, they will trigger.
 *
 *----------------------------------------------------------------------
 */

static void
FireWidgetViewSyncEvent(
    ClientData clientData)	/* Information about text widget. */
{
    TkText *textPtr = (TkText *) clientData;
    Tcl_Interp *interp;
    int syncState;

    textPtr->pendingFireEvent = 0;

    if (textPtr->flags & DESTROYED) {
	return;
    }

    syncState = !TkTextPendingSync(textPtr);

    if (textPtr->sendSyncEvent && syncState) {
	/*
	 * The user is waiting for sync state 'true', so we must send it.
	 */

	textPtr->prevSyncState = 0;
    }

    if (textPtr->prevSyncState == syncState) {
	/*
	 * Do not send "WidgetViewSync" with same sync state as before
	 * (except if we must send it because the user is waiting for it).
	 */

	return;
    }

    if ((textPtr->sendSyncEvent || textPtr->pendingAfterSync) && !syncState) {
	/*
	 * Do not send "WidgetViewSync" with sync state "false" as long as
	 * we have a pending sync command.
	 */

	return;
    }

    if (syncState) {
	textPtr->sendSyncEvent = 0;
    }
    textPtr->prevSyncState = syncState;

    interp = textPtr->interp;
    Tcl_Preserve((ClientData) interp);
    /*
     * OSX 10.14 needs to be told to display the window when the Text Widget
     * is in sync.  (That is, to run DisplayText inside of the drawRect
     * method.)  Otherwise the screen might not get updated until an event
     * like a mouse click is received.  But that extra drawing corrupts the
     * data that the test suite is trying to collect.
     */

    if (!tkTextDebug) {
	FORCE_DISPLAY(textPtr->tkwin);
    }

    Tk_SendVirtualEvent(textPtr->tkwin, "WidgetViewSync", Tcl_NewBooleanObj(syncState));
    Tcl_Release((ClientData) interp);
}

void
TkTextGenerateWidgetViewSyncEvent(
    TkText *textPtr,		/* Information about text widget. */
    int sendImmediately)
{
    if (!textPtr->pendingFireEvent) {
	textPtr->pendingFireEvent = 1;
	if (sendImmediately) {
	    FireWidgetViewSyncEvent((ClientData) textPtr);
	} else {
	    Tcl_DoWhenIdle(FireWidgetViewSyncEvent, (ClientData) textPtr);
	}
    }
}

/*
 *---------------------------------------------------------------------------
 *
 * TkrTextPrintIndex --
 *
 *	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.
 *
 *---------------------------------------------------------------------------
 */

/*
 * NOTE: this function has external linkage (declared in a common header file)
 * and cannot be inlined.
 */

TkSizeT
TkrTextPrintIndex(
    const TkText *textPtr,
    const TkTextIndex *indexPtr,/* Pointer to index. */
    char *string)		/* Place to store the position. Must have at least TK_POS_CHARS
    				 * characters. */
{
    assert(textPtr);
    return TkTextIndexPrint(textPtr->sharedTextPtr, textPtr, indexPtr, string);
}

/*
 *----------------------------------------------------------------------
 *
 * SearchPerform --
 *
 *	Overall control of search process. Is given a pattern, a starting
 *	index and an ending index, and attempts to perform a search. This
 *	function is actually completely independent of Tk, and could in the
 *	future be split off.
 *
 * Results:
 *	Standard Tcl result code. In particular, if fromPtr or toPtr are not
 *	considered valid by the 'lineIndexProc', an error will be thrown and
 *	no search performed.
 *
 * Side effects:
 *	See 'SearchCore'.
 *
 *----------------------------------------------------------------------
 */

static int
SearchPerform(
    Tcl_Interp *interp,		/* For error messages. */
    SearchSpec *searchSpecPtr,	/* Search parameters. */
    Tcl_Obj *patObj,		/* Contains an exact string or a regexp
				 * pattern. Must have a refCount > 0. */
    Tcl_Obj *fromPtr,		/* Contains information describing the first index. */
    Tcl_Obj *toPtr)		/* NULL or information describing the last index. */
{
    TkText *textPtr = (TkText *)searchSpecPtr->clientData;

    if (TkTextIsDeadPeer(textPtr)) {
	return TCL_OK;
    }

    /*
     * Find the starting line and starting offset (measured in Unicode chars
     * for regexp search, utf-8 bytes for exact search).
     */

    if (searchSpecPtr->lineIndexProc(interp, fromPtr, searchSpecPtr,
	    &searchSpecPtr->startLine, &searchSpecPtr->startOffset) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     * Find the optional end location, similarly.
     */

    if (toPtr) {
	TkTextIndex indexTo, indexFrom;

	if (!TkTextGetIndexFromObj(interp, textPtr, toPtr, &indexTo)
		|| !TkTextGetIndexFromObj(interp, textPtr, fromPtr, &indexFrom)) {
	    return TCL_ERROR;
	}

	/*
	 * Check for any empty search range here. It might be better in the
	 * future to embed that in SearchCore (whose default behaviour is to
	 * wrap when given a negative search range).
	 */

	if (TkTextIndexCompare(&indexFrom, &indexTo) == (searchSpecPtr->backwards ? -1 : 1)) {
	    return TCL_OK;
	}

	if (searchSpecPtr->lineIndexProc(interp, toPtr, searchSpecPtr,
		&searchSpecPtr->stopLine, &searchSpecPtr->stopOffset) != TCL_OK) {
	    return TCL_ERROR;
	}
    } else {
	searchSpecPtr->stopLine = -1;
    }

    /*
     * Scan through all of the lines of the text circularly, starting at the
     * given index. 'patObj' is the pattern which may be an exact string or a
     * regexp pattern depending on the flags in searchSpecPtr.
     */

    return SearchCore(interp, searchSpecPtr, patObj);
}

/*
 *----------------------------------------------------------------------
 *
 * SearchCore --
 *
 *	The core of the search function. This function is actually completely
 *	independent of Tk, and could in the future be split off.
 *
 *	The function assumes regexp-based searches operate on Unicode strings,
 *	and exact searches on utf-8 strings. Therefore the 'foundMatchProc'
 *	and 'addLineProc' need to be aware of this distinction.
 *
 * Results:
 *	Standard Tcl result code.
 *
 * Side effects:
 *	Only those of the 'searchSpecPtr->foundMatchProc' which is called
 *	whenever a match is found.
 *
 *	Note that the way matching across multiple lines is implemented, we
 *	start afresh with each line we have available, even though we may
 *	already have examined the contents of that line (and further ones) if
 *	we were attempting a multi-line match using the previous line. This
 *	means there may be ways to speed this up a lot by not throwing away
 *	all the multi-line information one has accumulated. Profiling should
 *	be done to see where the bottlenecks lie before attempting this,
 *	however. We would also need to be very careful such optimisation keep
 *	within the specified search bounds.
 *
 *----------------------------------------------------------------------
 */

static int
SearchCore(
    Tcl_Interp *interp,		/* For error messages. */
    SearchSpec *searchSpecPtr,	/* Search parameters. */
    Tcl_Obj *patObj)		/* Contains an exact string or a regexp
				 * pattern. Must have a refCount > 0. */
{
    /*
     * For exact searches these are utf-8 char* offsets, for regexp searches
     * they are Unicode char offsets.
     */

    int firstOffset, lastOffset, matchOffset, matchLength;
    int passes;
    int lineNum = searchSpecPtr->startLine;
    int code = TCL_OK;
    Tcl_Obj *theLine;
    int alreadySearchOffset = -1;

    const char *pattern = NULL;	/* For exact searches only. */
    int firstNewLine = -1; 	/* For exact searches only. */
    Tcl_RegExp regexp = NULL;	/* For regexp searches only. */

    /*
     * These items are for backward regexp searches only. They are for two
     * purposes: to allow us to report backwards matches in the correct order,
     * even though the implementation uses repeated forward searches; and to
     * provide for overlap checking between backwards matches on different
     * text lines.
     */

#define LOTS_OF_MATCHES 20
    int matchNum = LOTS_OF_MATCHES;
    int32_t smArray[2 * LOTS_OF_MATCHES];
    int32_t *storeMatch = smArray;
    int32_t *storeLength = smArray + LOTS_OF_MATCHES;
    int lastBackwardsLineMatch = -1;
    int lastBackwardsMatchOffset = -1;

    if (searchSpecPtr->exact) {
	/*
	 * Convert the pattern to lower-case if we're supposed to ignore case.
	 */

	if (searchSpecPtr->noCase) {
	    patObj = Tcl_DuplicateObj(patObj);

	    /*
	     * This can change the length of the string behind the object's
	     * back, so ensure it is correctly synchronised.
	     */

	    Tcl_SetObjLength(patObj, Tcl_UtfToLower(Tcl_GetString(patObj)));
	}
    } else {
	/*
	 * Compile the regular expression. We want '^$' to match after and
	 * before \n respectively, so use the TCL_REG_NLANCH flag.
	 */

	regexp = Tcl_GetRegExpFromObj(interp, patObj,
		(searchSpecPtr->noCase ? TCL_REG_NOCASE : 0)
		| (searchSpecPtr->noLineStop ? 0 : TCL_REG_NLSTOP)
		| TCL_REG_ADVANCED | TCL_REG_CANMATCH | TCL_REG_NLANCH);
	if (!regexp) {
	    return TCL_ERROR;
	}
    }

    /*
     * For exact strings, we want to know where the first newline is, and we
     * will also use this as a flag to test whether it is even possible to
     * match the pattern on a single line. If not we will have to search
     * across multiple lines.
     */

    if (searchSpecPtr->exact) {
	const char *nl;

	/*
	 * We only need to set the matchLength once for exact searches, and we
	 * do it here. It is also used below as the actual pattern length, so
	 * it has dual purpose.
	 */

	pattern = Tcl_GetString(patObj);
	matchLength = GetByteLength(patObj);
	nl = strchr(pattern, '\n');

	/*
	 * If there is no newline, or it is the very end of the string, then
	 * we don't need any special treatment, since single-line matching
	 * will work fine.
	 */

	if (nl && nl[1] != '\0') {
	    firstNewLine = (nl - pattern);
	}
    } else {
	matchLength = 0;	/* Only needed to prevent compiler warnings. */
    }

    /*
     * Keep a reference here, so that we can be sure the object doesn't
     * disappear behind our backs and invalidate its contents which we are
     * using.
     */

    Tcl_IncrRefCount(patObj);

    /*
     * For building up the current line being checked.
     */

    theLine = Tcl_NewObj();
    Tcl_IncrRefCount(theLine);

    for (passes = 0; passes < 2; ) {
	ClientData lineInfo;
	int linesSearched = 1;
	int extraLinesSearched = 0;

	if (lineNum >= searchSpecPtr->numLines) {
	    /*
	     * Don't search the dummy last line of the text.
	     */

	    goto nextLine;
	}

	/*
	 * Extract the text from the line, storing its length in 'lastOffset'
	 * (in bytes if exact, chars if regexp), since obviously the length is
	 * the maximum offset at which it is possible to find something on
	 * this line, which is what 'lastOffset' represents.
	 */

	lineInfo = searchSpecPtr->addLineProc(lineNum, searchSpecPtr, theLine,
		&lastOffset, &linesSearched);

	if (!lineInfo) {
	    /*
	     * This should not happen, since 'lineNum' should be valid in the
	     * call above. However, let's try to be flexible and not cause a
	     * crash below.
	     */

	    goto nextLine;
	}

	if (lineNum == searchSpecPtr->stopLine && searchSpecPtr->backwards) {
	    firstOffset = searchSpecPtr->stopOffset;
	} else {
	    firstOffset = 0;
	}

	if (alreadySearchOffset >= 0) {
	    if (searchSpecPtr->backwards) {
		if (alreadySearchOffset < lastOffset) {
		    lastOffset = alreadySearchOffset;
		}
	    } else {
		if (alreadySearchOffset > firstOffset) {
		    firstOffset = alreadySearchOffset;
		}
	    }
	    alreadySearchOffset = -1;
	}

	if (lineNum == searchSpecPtr->startLine) {
	    /*
	     * The starting line is tricky: the first time we see it we check
	     * one part of the line, and the second pass through we check the
	     * other part of the line.
	     */

	    passes += 1;
	    if ((passes == 1) ^ searchSpecPtr->backwards) {
		/*
		 * Forward search and first pass, or backward search and
		 * second pass.
		 *
		 * Only use the last part of the line.
		 */

		if (searchSpecPtr->startOffset > firstOffset) {
		    firstOffset = searchSpecPtr->startOffset;
		}
		if (firstOffset >= lastOffset && (lastOffset != 0 || searchSpecPtr->exact)) {
		    goto nextLine;
		}
	    } else {
		/*
		 * Use only the first part of the line.
		 */

		if (searchSpecPtr->startOffset < lastOffset) {
		    lastOffset = searchSpecPtr->startOffset;
		}
	    }
	}

	/*
	 * Check for matches within the current line 'lineNum'. If so, and if
	 * we're searching backwards or for all matches, repeat the search
	 * until we find the last match in the line. The 'lastOffset' is one
	 * beyond the last position in the line at which a match is allowed to
	 * begin.
	 */

	matchOffset = -1;

	if (searchSpecPtr->exact) {
	    int maxExtraLines = 0;
	    const char *startOfLine = Tcl_GetString(theLine);

	    assert(pattern);
	    do {
		const char *p;
		int lastFullLine = lastOffset;

		if (firstNewLine == -1) {
		    if (searchSpecPtr->strictLimits && (firstOffset + matchLength > lastOffset)) {
			/*
			 * Not enough characters to match.
			 */

			break;
		    }

		    /*
		     * Single line matching. We want to scan forwards or
		     * backwards as appropriate.
		     */

		    if (searchSpecPtr->backwards) {
			/*
			 * Search back either from the previous match or from
			 * 'startOfLine + lastOffset - 1' until we find a
			 * match.
			 */

			const char c = matchLength ? pattern[0] : '\0';

			p = startOfLine;
			if (alreadySearchOffset >= 0) {
			    p += alreadySearchOffset;
			    alreadySearchOffset = -1;
			} else {
			    p += lastOffset - 1;
			}
			while (p >= startOfLine + firstOffset) {
			    if (matchLength == 0 || (p[0] == c && !strncmp(
				     p, pattern, (size_t) matchLength))) {
				goto backwardsMatch;
			    }
			    p -= 1;
			}
			break;
		    } else {
			p = strstr(startOfLine + firstOffset, pattern);
		    }
		    if (!p) {
			/*
			 * Single line match failed.
			 */

			break;
		    }
		} else if (firstNewLine >= lastOffset - firstOffset) {
		    /*
		     * Multi-line match, but not enough characters to match.
		     */

		    break;
		} else {
		    /*
		     * Multi-line match has only one possible match position,
		     * because we know where the '\n' is.
		     */

		    p = startOfLine + lastOffset - firstNewLine - 1;
		    if (strncmp(p, pattern, firstNewLine + 1) != 0) {
			/*
			 * No match.
			 */

			break;
		    } else {
			int extraLines = 1;

			/*
			 * If we find a match that overlaps more than one
			 * line, we will use this value to determine the first
			 * allowed starting offset for the following search
			 * (to avoid overlapping results).
			 */

			int lastTotal = lastOffset;
			int skipFirst = lastOffset - firstNewLine - 1;

			/*
			 * We may be able to match if given more text. The
			 * following 'while' block handles multi-line exact
			 * searches.
			 */

			while (1) {
			    lastFullLine = lastTotal;

			    if (lineNum + extraLines >= searchSpecPtr->numLines) {
				p = NULL;
				break;
			    }

			    /*
			     * Only add the line if we haven't already done so
			     * already.
			     */

			    if (extraLines > maxExtraLines) {
				if (!searchSpecPtr->addLineProc(lineNum + extraLines, searchSpecPtr,
					theLine, &lastTotal, &extraLines)) {
				    p = NULL;
				    if (!searchSpecPtr->backwards) {
					extraLinesSearched = extraLines;
				    }
				    break;
				}
				maxExtraLines = extraLines;
			    }

			    startOfLine = Tcl_GetString(theLine);
			    p = startOfLine + skipFirst;

			    /*
			     * Use the fact that 'matchLength = patLength' for
			     * exact searches.
			     */

			    if (lastTotal - skipFirst >= matchLength) {
				/*
				 * We now have enough text to match, so we
				 * make a final test and break whatever the
				 * result.
				 */

				if (strncmp(p, pattern, matchLength) != 0) {
				    p = NULL;
				}
				break;
			    } else {
				/*
				 * Not enough text yet, but check the prefix.
				 */

				if (strncmp(p, pattern, lastTotal - skipFirst) != 0) {
				    p = NULL;
				    break;
				}

				/*
				 * The prefix matches, so keep looking.
				 */
			    }
			    extraLines += 1;
			}
			/*
			 * If we reach here, with p != NULL, we've found a
			 * multi-line match, else we started a multi-match but
			 * didn't finish it off, so we go to the next line.
			 */

			if (!p) {
			    break;
			}

			/*
			 * We've found a multi-line match.
			 */

			if (extraLines > 0) {
			    extraLinesSearched = extraLines - 1;
			}
		    }
		}

	    backwardsMatch:
		if (p - startOfLine >= lastOffset) {
		    break;
		}

		/*
		 * Remember the match.
		 */

		matchOffset = p - startOfLine;

		if (searchSpecPtr->all &&
			!searchSpecPtr->foundMatchProc(lineNum, searchSpecPtr,
			lineInfo, theLine, matchOffset, matchLength)) {
		    /*
		     * We reached the end of the search.
		     */

		    goto searchDone;
		}

		if (!searchSpecPtr->overlap) {
		    if (searchSpecPtr->backwards) {
			alreadySearchOffset = p - startOfLine;
			if (firstNewLine != -1) {
			    break;
			} else {
			    alreadySearchOffset -= (matchLength ? matchLength : 1);
                            if (alreadySearchOffset < 0) {
                                break;
                            }
			}
		    } else {
                        firstOffset = matchLength ? p - startOfLine + matchLength
                                                  : p - startOfLine + 1;
			if (firstOffset >= lastOffset) {
			    /*
			     * Now, we have to be careful not to find
			     * overlapping matches either on the same or
			     * following lines. Assume that if we did find
			     * something, it goes until the last extra line we
			     * added.
			     *
			     * We can break out of the loop, since we know no
			     * more will be found.
			     */

			    if (!searchSpecPtr->backwards) {
				alreadySearchOffset = firstOffset - lastFullLine;
				break;
			    }
			}
		    }
		} else {
		    if (searchSpecPtr->backwards) {
			alreadySearchOffset = p - startOfLine - 1;
			if (alreadySearchOffset < 0) {
			    break;
			}
		    } else {
			int len;
			const char *s = startOfLine + matchOffset;

#if 0 && 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;
			len = TkUtfToUniChar(s, &ch);
#else
			/*
			 * Proper implementation for UTF-8 strings:
			 */

			Tcl_UniChar ch;
			len = Tcl_UtfToUniChar(s, &ch);
#endif
			firstOffset = (p - startOfLine) + len;
		    }
		}
	    } while (searchSpecPtr->all);
	} else {
	    int maxExtraLines = 0;
	    int matches = 0;
	    int lastNonOverlap = -1;

	    do {
		Tcl_RegExpInfo info;
		int match;
		int lastFullLine = lastOffset;

		match = Tcl_RegExpExecObj(interp, regexp, theLine,
			firstOffset, 1, firstOffset > 0 ? TCL_REG_NOTBOL : 0);
		if (match < 0) {
		    code = TCL_ERROR;
		    goto searchDone;
		}
		Tcl_RegExpGetInfo(regexp, &info);

		/*
		 * If we don't have a match, or if we do, but it extends to
		 * the end of the line, we must try to add more lines to get a
		 * full greedy match.
		 */

		if (!match
			|| (info.extendStart == info.matches[0].start
			    && info.matches[0].end == (TkSizeT)(lastOffset - firstOffset))) {
		    int extraLines = 0;
		    int prevFullLine;

		    /*
		     * If we find a match that overlaps more than one line, we
		     * will use this value to determine the first allowed
		     * starting offset for the following search (to avoid
		     * overlapping results).
		     */

		    int lastTotal = lastOffset;

		    if (lastBackwardsLineMatch != -1 && lastBackwardsLineMatch == lineNum + 1) {
			lastNonOverlap = lastTotal;
		    }

		    if (info.extendStart == TCL_INDEX_NONE) {
			/*
			 * No multi-line match is possible.
			 */

			break;
		    }

		    /*
		     * We may be able to match if given more text. The
		     * following 'while' block handles multi-line regexp
		     * searches.
		     */

		    while (1) {
			prevFullLine = lastTotal;

			/*
			 * Move firstOffset to first possible start.
			 */

			if (!match) {
			    firstOffset += info.extendStart;
			}
			if (firstOffset >= lastOffset) {
			    /*
			     * We're being told that the only possible new
			     * match is starting after the end of the line.
			     * But, that is the next line which we will handle
			     * when we look at that line.
			     */

			    if (!match && !searchSpecPtr->backwards && firstOffset == 0) {
				extraLinesSearched = extraLines;
			    }
			    break;
			}

			if (lineNum + extraLines >= searchSpecPtr->numLines) {
			    break;
			}

			/*
			 * Add next line, provided we haven't already done so.
			 */

			if (extraLines > maxExtraLines) {
			    if (!searchSpecPtr->addLineProc(lineNum + extraLines, searchSpecPtr,
				    theLine, &lastTotal, &extraLines)) {
				/*
				 * There are no more acceptable lines, so we
				 * can say we have searched all of these.
				 */

				if (!match && !searchSpecPtr->backwards) {
				    extraLinesSearched = extraLines;
				}
				break;
			    }

			    maxExtraLines = extraLines;
			    if (lastBackwardsLineMatch != -1
				    && lastBackwardsLineMatch == lineNum + extraLines + 1) {
				lastNonOverlap = lastTotal;
			    }
			}

			match = Tcl_RegExpExecObj(interp, regexp, theLine,
				firstOffset, 1, firstOffset > 0 ? TCL_REG_NOTBOL : 0);
			if (match < 0) {
			    code = TCL_ERROR;
			    goto searchDone;
			}
			Tcl_RegExpGetInfo(regexp, &info);

			/*
			 * Unfortunately there are bugs in Tcl's regexp
			 * library, which tells us that info.extendStart is
			 * zero when it should not be (should be -1), which
			 * makes our task a bit more complicated here. We
			 * check if there was a match, and the end of the
			 * match leaves an entire extra line unmatched, then
			 * we stop searching. Clearly it still might sometimes
			 * be possible to add more text and match again, but
			 * Tcl's regexp library doesn't tell us that.
			 *
			 * This means we often add and search one more line
			 * than might be necessary if Tcl were able to give us
			 * a correct value of info.extendStart under all
			 * circumstances.
			 */

			if ((match  && info.matches[0].end != (TkSizeT)(lastTotal - firstOffset)
				    && (info.matches[0].end + 1) < (TkSizeT)(prevFullLine - firstOffset + 1))
				|| info.extendStart == TCL_INDEX_NONE) {
			    break;
			}

			/*
			 * If there is a match, but that match starts after
			 * the end of the first line, then we'll handle that
			 * next time around, when we're actually looking at
			 * that line.
			 */

			if (match && info.matches[0].start + 1 >= (TkSizeT)(lastOffset + 1)) {
			    break;
			}
			if (match && (info.matches[0].end + 1) >= (TkSizeT)(prevFullLine - firstOffset + 1)) {
			    if (extraLines > 0) {
				extraLinesSearched = extraLines - 1;
			    }
			    lastFullLine = prevFullLine;
			}

			/*
			 * The prefix matches, so keep looking.
			 */

			extraLines += 1;
		    }

		    /*
		     * If we reach here with 'match == 1', we've found a
		     * multi-line match, which we will record in the code
		     * which follows directly else we started a multi-line
		     * match but didn't finish it off, so we go to the next
		     * line.
		     */

		    if (!match) {
			/*
			 * Here is where we could perform an optimisation,
			 * since we have already retrieved the contents of the
			 * next line (perhaps many more), so we shouldn't
			 * really throw it all away and start again. This
			 * could be particularly important for complex regexp
			 * searches.
			 *
			 * This 'break' will take us to just before the
			 * 'nextLine:' below.
			 */

			break;
		    }

		    if (lastBackwardsLineMatch != -1) {
			if (lineNum + linesSearched + extraLinesSearched == lastBackwardsLineMatch) {
			    /*
			     * Possible overlap or inclusion.
			     */

			    int thisOffset = firstOffset + info.matches[0].end - info.matches[0].start;

			    if (lastNonOverlap != -1) {
				/*
				 * Possible overlap or enclosure.
				 */

				if (thisOffset - lastNonOverlap >=
					lastBackwardsMatchOffset + matchLength) {
				    /*
				     * Totally encloses previous match, so
				     * forget the previous match.
				     */

				    lastBackwardsLineMatch = -1;
				} else if (thisOffset - lastNonOverlap > lastBackwardsMatchOffset) {
				    /*
				     * Overlap. Previous match is ok, and the
				     * current match is only ok if we are
				     * searching with -overlap.
				     */

				    if (searchSpecPtr->overlap) {
					goto recordBackwardsMatch;
				    } else {
					match = 0;
					break;
				    }
				} else {
				    /*
				     * No overlap, although the same line was
				     * reached.
				     */

				    goto recordBackwardsMatch;
				}
			    } else {
				/*
				 * No overlap.
				 */

				goto recordBackwardsMatch;
			    }
			} else if (lineNum + linesSearched + extraLinesSearched
				< lastBackwardsLineMatch) {
			    /*
			     * No overlap.
			     */

			    goto recordBackwardsMatch;
			} else {
			    /*
			     * Totally enclosed.
			     */

			    lastBackwardsLineMatch = -1;
			}
		    }

		} else {
		    /*
		     * Matched in a single line.
		     */

		    if (lastBackwardsLineMatch != -1) {
		    recordBackwardsMatch:
			searchSpecPtr->foundMatchProc(lastBackwardsLineMatch,
				searchSpecPtr, NULL, NULL, lastBackwardsMatchOffset, matchLength);
			lastBackwardsLineMatch = -1;
			if (!searchSpecPtr->all) {
			    goto searchDone;
			}
		    }
		}

		firstOffset += info.matches[0].start;
		if (firstOffset >= lastOffset) {
		    break;
		}

		/*
		 * Update our local variables with the match, if we haven't
		 * yet found anything, or if we're doing '-all' or
		 * '-backwards' _and_ this match isn't fully enclosed in the
		 * previous match.
		 */

		if (matchOffset == -1 ||
			((searchSpecPtr->all || searchSpecPtr->backwards)
			    && (firstOffset < matchOffset
				|| (info.matches[0].end - info.matches[0].start + 1)
				    > (TkSizeT)(matchOffset + matchLength - firstOffset + 1)))) {

		    matchOffset = firstOffset;
		    matchLength = info.matches[0].end - info.matches[0].start;

		    if (searchSpecPtr->backwards) {
			/*
			 * To get backwards searches in the correct order, we
			 * must store them away here.
			 */

			if (matches == matchNum) {
			    /*
			     * We've run out of space in our normal store, so
			     * we must allocate space for these backwards
			     * matches on the heap.
			     */

			    int matchNumSize = matchNum * sizeof(int32_t);
			    int32_t *newArray = (int32_t *)malloc(4*matchNumSize);
			    memcpy(newArray, storeMatch, matchNumSize);
			    memcpy(newArray + 2*matchNum, storeLength, matchNumSize);
			    if (storeMatch != smArray) {
				free((char *) storeMatch);
			    }
			    matchNum *= 2;
			    storeMatch = newArray;
			    storeLength = newArray + matchNum;
			}
			storeMatch[matches] = matchOffset;
			storeLength[matches] = matchLength;
			matches += 1;
		    } else {
			/*
			 * Now actually record the match, but only if we are
			 * doing an '-all' search.
			 */

			if (searchSpecPtr->all &&
				!searchSpecPtr->foundMatchProc(lineNum,
				    searchSpecPtr, lineInfo, theLine, matchOffset, matchLength)) {
			    /*
			     * We reached the end of the search.
			     */

			    goto searchDone;
			}
		    }

		    /*
		     * For forward matches, unless we allow overlaps, we move
		     * this on by the length of the current match so that we
		     * explicitly disallow overlapping matches.
		     */

		    if (matchLength > 0 && !searchSpecPtr->overlap && !searchSpecPtr->backwards) {
			firstOffset += matchLength;
			if (firstOffset >= lastOffset) {
			    /*
			     * Now, we have to be careful not to find
			     * overlapping matches either on the same or
			     * following lines. Assume that if we did find
			     * something, it goes until the last extra line we
			     * added.
			     *
			     * We can break out of the loop, since we know no
			     * more will be found.
			     */

			    alreadySearchOffset = firstOffset - lastFullLine;
			    break;
			}

			/*
			 * We'll add this on again just below.
			 */

			firstOffset -= 1;
		    }
		}

		/*
		 * Move the starting point on, in case we are doing repeated
		 * or backwards searches (for the latter, we actually do
		 * repeated forward searches).
		 */

		firstOffset += 1;
	    } while (searchSpecPtr->backwards || searchSpecPtr->all);

	    if (matches > 0) {
		/*
		 * Now we have all the matches in our array, but not stored
		 * with 'foundMatchProc' yet.
		 */

		matches -= 1;
		matchOffset = storeMatch[matches];
		matchLength = storeLength[matches];
		while (--matches >= 0) {
		    if (lineNum == searchSpecPtr->stopLine) {
			/*
			 * It appears as if a condition like:
			 *
			 * if (storeMatch[matches]<searchSpecPtr->stopOffset)
			 *	break;
			 *
			 * might be needed here, but no test case has been
			 * found which would exercise such a problem.
			 */
		    }
		    if (storeMatch[matches] + storeLength[matches] >= matchOffset + matchLength) {
			/*
			 * The new match totally encloses the previous one, so
			 * we overwrite the previous one.
			 */

			matchOffset = storeMatch[matches];
			matchLength = storeLength[matches];
			continue;
		    }
		    if (!searchSpecPtr->overlap) {
			if (storeMatch[matches] + storeLength[matches] > matchOffset) {
			    continue;
			}
		    }
		    searchSpecPtr->foundMatchProc(lineNum, searchSpecPtr,
			    lineInfo, theLine, matchOffset, matchLength);
		    if (!searchSpecPtr->all) {
			goto searchDone;
		    }
		    matchOffset = storeMatch[matches];
		    matchLength = storeLength[matches];
		}
		if (searchSpecPtr->all && matches > 0) {
		    /*
		     * We only need to do this for the '-all' case, because
		     * just below we will call the foundMatchProc for the
		     * non-all case.
		     */

		    searchSpecPtr->foundMatchProc(lineNum, searchSpecPtr,
			    lineInfo, theLine, matchOffset, matchLength);
		} else {
		    lastBackwardsLineMatch = lineNum;
		    lastBackwardsMatchOffset = matchOffset;
		}
	    }
	}

	/*
	 * If the 'all' flag is set, we will already have stored all matches,
	 * so we just proceed to the next line.
	 *
	 * If not, and there is a match we need to store that information and
	 * we are done.
	 */

	if (lastBackwardsLineMatch == -1 && matchOffset >= 0 && !searchSpecPtr->all) {
	    searchSpecPtr->foundMatchProc(lineNum, searchSpecPtr, lineInfo,
		    theLine, matchOffset, matchLength);
	    goto searchDone;
	}

	/*
	 * Go to the next (or previous) line;
	 */

    nextLine:
	linesSearched += extraLinesSearched;

	while (linesSearched-- > 0) {
	    /*
	     * If we have just completed the 'stopLine', we are done.
	     */

	    if (lineNum == searchSpecPtr->stopLine) {
		goto searchDone;
	    }

	    if (searchSpecPtr->backwards) {
		lineNum -= 1;

		if (lastBackwardsLineMatch != -1
			&& (lineNum < 0 || lineNum + 2 < lastBackwardsLineMatch)) {
		    searchSpecPtr->foundMatchProc(lastBackwardsLineMatch,
			    searchSpecPtr, NULL, NULL, lastBackwardsMatchOffset, matchLength);
		    lastBackwardsLineMatch = -1;
		    if (!searchSpecPtr->all) {
			goto searchDone;
		    }
		}

		if (lineNum < 0) {
		    lineNum = searchSpecPtr->numLines - 1;
		}
		if (!searchSpecPtr->exact) {
		    /*
		     * The 'exact' search loops above are designed to give us
		     * an accurate picture of the number of lines which we can
		     * skip here. For 'regexp' searches, on the other hand,
		     * which can match potentially variable lengths, we cannot
		     * skip multiple lines when searching backwards. Therefore
		     * we only allow one line to be skipped here.
		     */

		    break;
		}
	    } else {
		lineNum += 1;
		if (lineNum >= searchSpecPtr->numLines) {
		    lineNum = 0;
		}
	    }
	    if (lineNum == searchSpecPtr->startLine && linesSearched > 0) {
		/*
		 * We've just searched all the way round and have gone right
		 * through the start line without finding anything in the last
		 * attempt.
		 */

		break;
	    }
	}

	Tcl_SetObjLength(theLine, 0);
    }
  searchDone:

    if (lastBackwardsLineMatch != -1) {
	searchSpecPtr->foundMatchProc(lastBackwardsLineMatch, searchSpecPtr,
		NULL, NULL, lastBackwardsMatchOffset, matchLength);
    }

    /*
     * Free up the cached line and pattern.
     */

    Tcl_GuardedDecrRefCount(theLine);
    Tcl_GuardedDecrRefCount(patObj);

    /*
     * Free up any extra space we allocated.
     */

    if (storeMatch != smArray) {
	free((char *) storeMatch);
    }

    return code;
}

/*
 *----------------------------------------------------------------------
 *
 * GetTextStartEnd -
 *
 *	Converts an internal TkTextSegment ptr into a Tcl string obj containing
 *	the representation of the index. (Handler for the 'startEndMark' configuration
 *	option type.)
 *
 * Results:
 *	Tcl_Obj containing the string representation of the index position.
 *
 * Side effects:
 *	Creates a new Tcl_Obj.
 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj *
GetTextStartEnd(
    ClientData dummy,
    Tk_Window tkwin,
    char *recordPtr,		/* Pointer to widget record. */
    TkSizeT internalOffset)		/* Offset within *recordPtr containing the start object. */
{
    TkTextIndex index;
    char buf[TK_POS_CHARS] = { '\0' };
    const TkText *textPtr = (const TkText *) recordPtr;
    const TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    Tcl_Obj **objPtr = (Tcl_Obj **) (recordPtr + internalOffset);
    const TkTextSegment *sharedMarker;
    TkTextSegment *marker;
    (void)dummy;
    (void)tkwin;

    if (objPtr == &textPtr->newStartIndex) {
	marker = textPtr->startMarker;
	sharedMarker = sharedTextPtr->startMarker;
    } else {
	marker = textPtr->endMarker;
	sharedMarker = sharedTextPtr->endMarker;
    }
    if (marker != sharedMarker) {
	TkTextIndexClear2(&index, NULL, sharedTextPtr->tree);
	TkTextIndexSetSegment(&index, marker);
	TkTextIndexPrint(sharedTextPtr, NULL, &index, buf);
    }
    return Tcl_NewStringObj(buf, -1);
}

/*
 *----------------------------------------------------------------------
 *
 * SetTextStartEnd --
 *
 *	Converts a Tcl_Obj representing a widget's (start or end) index into a
 *	TkTextSegment* value. (Handler for the 'startEndMark' configuration option type.)
 *
 * Results:
 *	Standard Tcl result.
 *
 * Side effects:
 *	May store the TkTextSegment* value into the internal representation
 *	pointer. May change the pointer to the Tcl_Obj to NULL to indicate
 *	that the specified string was empty and that is acceptable.
 *
 *----------------------------------------------------------------------
 */

static int
ObjectIsEmpty(
    Tcl_Obj *objPtr)		/* Object to test. May be NULL. */
{
    return objPtr ? GetByteLength(objPtr) == 0 : 1;
}

static int
SetTextStartEnd(
    ClientData dummy,
    Tcl_Interp *interp,		/* Current interp; may be used for errors. */
    Tk_Window tkwin,		/* Window for which option is being set. */
    Tcl_Obj **value,		/* Pointer to the pointer to the value object.
				 * We use a pointer to the pointer because we
				 * may need to return a value (NULL). */
    char *recordPtr,		/* Pointer to storage for the widget record. */
    TkSizeT internalOffset,		/* Offset within *recordPtr at which the
				 * internal value is to be stored. */
    char *oldInternalPtr,	/* Pointer to storage for the old value. */
    int flags)			/* Flags for the option, set Tk_SetOptions. */
{
    Tcl_Obj **objPtr = (Tcl_Obj **) (recordPtr + internalOffset);
    Tcl_Obj **oldObjPtr = (Tcl_Obj **) oldInternalPtr;
    const TkText *textPtr = (const TkText *) recordPtr;
    (void)dummy;
    (void)interp;
    (void)tkwin;

    assert(!*objPtr);
    *oldObjPtr = NULL;

    if ((flags & TK_OPTION_NULL_OK) && ObjectIsEmpty(*value)) {
	*value = NULL;
	*objPtr = Tcl_NewStringObj((objPtr == &textPtr->newStartIndex) ? "begin" : "end", -1);
    } else {
	*objPtr = *value;
    }
    Tcl_IncrRefCount(*objPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RestoreTextStartEnd --
 *
 *	Restore an index option value from a saved value. (Handler for the
 *	'index' configuration option type.)
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Restores the old value.
 *
 *----------------------------------------------------------------------
 */

static void
RestoreTextStartEnd(
    ClientData dummy,
    Tk_Window tkwin,
    char *internalPtr,		/* Pointer to storage for value. */
    char *oldInternalPtr)	/* Pointer to old value. */
{
    Tcl_Obj **newValue = (Tcl_Obj **) internalPtr;
    Tcl_Obj **oldValue = (Tcl_Obj **) oldInternalPtr;
    (void)dummy;
    (void)tkwin;

    if (*oldValue) {
	Tcl_IncrRefCount(*oldValue);
    }
    *newValue = *oldValue;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeTextStartEnd --
 *
 *	Free an index option value from a saved value. (Handler for the
 *	'index' configuration option type.)
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Releases some memory.
 *
 *----------------------------------------------------------------------
 */

static void
FreeTextStartEnd(
    ClientData dummy,
    Tk_Window tkwin,
    char *internalPtr)
{
    Tcl_Obj *objPtr = *(Tcl_Obj **) internalPtr;
    (void)dummy;
    (void)tkwin;

    if (objPtr) {
	Tcl_GuardedDecrRefCount(objPtr);
    }
}

#if SUPPORT_DEPRECATED_STARTLINE_ENDLINE
/*
 *----------------------------------------------------------------------
 *
 * GetLineStartEnd -
 *
 *	Converts an internal TkTextLine ptr into a Tcl string obj containing
 *	the line number. (Handler for the 'line' configuration option type.)
 *
 * Results:
 *	Tcl_Obj containing the string representation of the line value.
 *
 * Side effects:
 *	Creates a new Tcl_Obj.
 *
 *----------------------------------------------------------------------
 */

static Tcl_Obj *
GetLineStartEnd(
    ClientData dummy,
    Tk_Window tkwin,
    char *recordPtr,		/* Pointer to widget record. */
    TkSizeT internalOffset)		/* Offset within *recordPtr containing the line value. */
{
    TkText *textPtr;
    TkTextLine *linePtr = *(TkTextLine **)(recordPtr + internalOffset);
    (void)dummy;
    (void)tkwin;

    if (!linePtr) {
	return Tcl_NewObj();
    }
    textPtr = (TkText *) recordPtr;
    return Tcl_NewIntObj(1 + TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, linePtr, NULL));
}

/*
 *----------------------------------------------------------------------
 *
 * SetLineStartEnd --
 *
 *	Converts a Tcl_Obj representing a widget's (start or end) line into a
 *	TkTextLine* value. (Handler for the 'line' configuration option type.)
 *
 * Results:
 *	Standard Tcl result.
 *
 * Side effects:
 *	May store the TkTextLine* value into the internal representation
 *	pointer. May change the pointer to the Tcl_Obj to NULL to indicate
 *	that the specified string was empty and that is acceptable.
 *
 *----------------------------------------------------------------------
 */

static int
SetLineStartEnd(
    ClientData dummy,
    Tcl_Interp *interp,		/* Current interp; may be used for errors. */
    Tk_Window tkwin,		/* Window for which option is being set. */
    Tcl_Obj **value,		/* Pointer to the pointer to the value object.
				 * We use a pointer to the pointer because we
				 * may need to return a value (NULL). */
    char *recordPtr,		/* Pointer to storage for the widget record. */
    TkSizeT internalOffset,		/* Offset within *recordPtr at which the
				 * internal value is to be stored. */
    char *oldInternalPtr,	/* Pointer to storage for the old value. */
    int flags)			/* Flags for the option, set Tk_SetOptions. */
{
    TkTextLine *linePtr = NULL;
    char *internalPtr;
    TkText *textPtr = (TkText *) recordPtr;
    (void)dummy;
    (void)tkwin;

    internalPtr = internalOffset >= 0 ? recordPtr + internalOffset : NULL;

    if ((flags & TK_OPTION_NULL_OK) && ObjectIsEmpty(*value)) {
	*value = NULL;
    } else {
	int line;

	if (Tcl_GetIntFromObj(interp, *value, &line) != TCL_OK) {
	    return TCL_ERROR;
	}
	linePtr = TkBTreeFindLine(textPtr->sharedTextPtr->tree, NULL, line - 1);
    }

    if (internalPtr) {
	*((TkTextLine **) oldInternalPtr) = *((TkTextLine **) internalPtr);
	*((TkTextLine **) internalPtr) = linePtr;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RestoreLineStartEnd --
 *
 *	Restore a line option value from a saved value. (Handler for the
 *	'line' configuration option type.)
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Restores the old value.
 *
 *----------------------------------------------------------------------
 */

static void
RestoreLineStartEnd(
    ClientData dummy,
    Tk_Window tkwin,
    char *internalPtr,		/* Pointer to storage for value. */
    char *oldInternalPtr)	/* Pointer to old value. */
{
    (void)dummy;
    (void)tkwin;

    *(TkTextLine **) internalPtr = *(TkTextLine **) oldInternalPtr;
}

#endif /* SUPPORT_DEPRECATED_STARTLINE_ENDLINE */

/*
 *----------------------------------------------------------------------
 *
 * TkrTesttextCmd --
 *
 *	This function implements the "testtext" command. It provides a set of
 *	functions for testing text widgets and the associated functions in
 *	tkText*.c.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Depends on option; see below.
 *
 *----------------------------------------------------------------------
 */

#if TK_MAJOR_VERSION > 8 || (TK_MAJOR_VERSION == 8 && TK_MINOR_VERSION > 5)

int
TkrTesttextCmd(
    ClientData dummy,	/* Main window for application. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument strings. */
{
    TkText *textPtr;
    size_t len;
    int lineIndex, byteIndex, byteOffset;
    TkTextIndex index, insIndex;
    char buf[TK_POS_CHARS];
    Tcl_CmdInfo info;
    Tcl_Obj *watchCmd;
    (void)dummy;

    if (objc < 3) {
	return TCL_ERROR;
    }

    if (Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &info) == 0) {
	return TCL_ERROR;
    }
    textPtr = (TkText *)info.objClientData;
    len = strlen(Tcl_GetString(objv[2]));
    if (strncmp(Tcl_GetString(objv[2]), "byteindex", len) == 0) {
	if (objc != 5) {
	    return TCL_ERROR;
	}
	lineIndex = atoi(Tcl_GetString(objv[3])) - 1;
	byteIndex = atoi(Tcl_GetString(objv[4]));

	TkrTextMakeByteIndex(textPtr->sharedTextPtr->tree, textPtr, lineIndex, byteIndex, &index);
    } else if (strncmp(Tcl_GetString(objv[2]), "forwbytes", len) == 0) {
	if (objc != 5) {
	    return TCL_ERROR;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[3], &index)) {
	    return TCL_ERROR;
	}
	byteOffset = atoi(Tcl_GetString(objv[4]));
	TkrTextIndexForwBytes(textPtr, &index, byteOffset, &index);
    } else if (strncmp(Tcl_GetString(objv[2]), "backbytes", len) == 0) {
	if (objc != 5) {
	    return TCL_ERROR;
	}
	if (!TkTextGetIndexFromObj(interp, textPtr, objv[3], &index)) {
	    return TCL_ERROR;
	}
	byteOffset = atoi(Tcl_GetString(objv[4]));
	TkrTextIndexBackBytes(textPtr, &index, byteOffset, &index);
    } else {
	return TCL_ERROR;
    }

    /*
     * Avoid triggering of the "watch" command.
     */

    watchCmd = textPtr->watchCmd;
    textPtr->watchCmd = NULL;
    insIndex = index; /* because TkrTextSetMark may modify position */
    TkrTextSetMark(textPtr, "insert", &insIndex);
    textPtr->watchCmd = watchCmd;

    TkrTextPrintIndex(textPtr, &index, buf);
    Tcl_SetObjResult(interp, Tcl_ObjPrintf("%s %d", buf, TkTextIndexGetByteIndex(&index)));
    return TCL_OK;
}

#else /* backport to Tk 8.5 */

int
TkrTesttextCmd(
    ClientData clientData,	/* Main window for application. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int argc,			/* Number of arguments. */
    const char **argv)		/* Argument strings. */
{
    TkText *textPtr;
    size_t len;
    int lineIndex, byteIndex, byteOffset;
    TkTextIndex index;
    char buf[64];
    unsigned offs;
    Tcl_CmdInfo info;

    if (argc < 3) {
	return TCL_ERROR;
    }

    if (Tcl_GetCommandInfo(interp, argv[1], &info) == 0) {
	return TCL_ERROR;
    }
    if (info.isNativeObjectProc) {
	textPtr = (TkText *) info.objClientData;
    } else {
	textPtr = (TkText *) info.clientData;
    }
    len = strlen(argv[2]);
    if (strncmp(argv[2], "byteindex", len) == 0) {
	if (argc != 5) {
	    return TCL_ERROR;
	}
	lineIndex = atoi(argv[3]) - 1;
	byteIndex = atoi(argv[4]);

	TkrTextMakeByteIndex(textPtr->sharedTextPtr->tree, textPtr, lineIndex, byteIndex, &index);
    } else if (strncmp(argv[2], "forwbytes", len) == 0) {
	if (argc != 5) {
	    return TCL_ERROR;
	}
	if (TkrTextGetIndex(interp, textPtr, argv[3], &index) != TCL_OK) {
	    return TCL_ERROR;
	}
	byteOffset = atoi(argv[4]);
	TkrTextIndexForwBytes(textPtr, &index, byteOffset, &index);
    } else if (strncmp(argv[2], "backbytes", len) == 0) {
	if (argc != 5) {
	    return TCL_ERROR;
	}
	if (TkrTextGetIndex(interp, textPtr, argv[3], &index) != TCL_OK) {
	    return TCL_ERROR;
	}
	byteOffset = atoi(argv[4]);
	TkrTextIndexBackBytes(textPtr, &index, byteOffset, &index);
    } else {
	return TCL_ERROR;
    }

    TkrTextSetMark(textPtr, "insert", &index);
    TkrTextPrintIndex(textPtr, &index, buf);
    offs = strlen(buf);
    snprintf(buf + offs, sizeof(buf) - offs, " %d", TkTextIndexGetByteIndex(&index));
    Tcl_AppendResult(interp, buf, NULL);

    return TCL_OK;
}

#endif /* TK_MAJOR_VERSION > 8 || (TK_MAJOR_VERSION == 8 && TK_MINOR_VERSION > 5) */

#ifndef NDEBUG
/*
 *----------------------------------------------------------------------
 *
 * TkpTextInspect --
 *
 *	This function is for debugging only, printing the text content
 *	on stdout.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkpTextInspect(
    TkText *textPtr)
{
    Tcl_Obj *resultPtr;
    Tcl_Obj *objv[8];
    Tcl_Obj **argv;
    int argc, i;

    Tcl_IncrRefCount(resultPtr = Tcl_GetObjResult(textPtr->interp));
    Tcl_ResetResult(textPtr->interp);
    Tcl_IncrRefCount(objv[0] = Tcl_NewStringObj(Tk_PathName(textPtr->tkwin), -1));
    Tcl_IncrRefCount(objv[1] = Tcl_NewStringObj("inspect", -1));
    Tcl_IncrRefCount(objv[2] = Tcl_NewStringObj("-elide", -1));
    Tcl_IncrRefCount(objv[3] = Tcl_NewStringObj("-chars", -1));
    Tcl_IncrRefCount(objv[4] = Tcl_NewStringObj("-image", -1));
    Tcl_IncrRefCount(objv[5] = Tcl_NewStringObj("-window", -1));
    Tcl_IncrRefCount(objv[6] = Tcl_NewStringObj("-mark", -1));
    Tcl_IncrRefCount(objv[7] = Tcl_NewStringObj("-tag", -1));
    TextInspectCmd(textPtr, textPtr->interp, sizeof(objv)/sizeof(objv[0]), objv);
    for (i = 0; i < (int) (sizeof(objv)/sizeof(objv[0])); ++i) {
	Tcl_GuardedDecrRefCount(objv[i]);
    }
    Tcl_ListObjGetElements(textPtr->interp, Tcl_GetObjResult(textPtr->interp), &argc, &argv);
    for (i = 0; i < argc; ++i) {
	fprintf(stdout, "%s\n", Tcl_GetString(argv[i]));
    }
    Tcl_SetObjResult(textPtr->interp, resultPtr);
    Tcl_GuardedDecrRefCount(resultPtr);
}

#endif /* NDEBUG */

/*
 *----------------------------------------------------------------------
 *
 * TkpTextDump --
 *
 *	This function is for debugging only, printing the text content
 *	on stdout.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
#ifndef NDEBUG

void
TkpTextDump(
    TkText *textPtr)
{
    Tcl_Obj *resultPtr;
    Tcl_Obj *objv[4];
    Tcl_Obj **argv;
    int argc, i;

    Tcl_IncrRefCount(resultPtr = Tcl_GetObjResult(textPtr->interp));
    Tcl_ResetResult(textPtr->interp);

    Tcl_IncrRefCount(objv[0] = Tcl_NewStringObj(Tk_PathName(textPtr->tkwin), -1));
    Tcl_IncrRefCount(objv[1] = Tcl_NewStringObj("dump", -1));
    Tcl_IncrRefCount(objv[2] = Tcl_NewStringObj("begin", -1));
    Tcl_IncrRefCount(objv[3] = Tcl_NewStringObj("end", -1));
    TextDumpCmd(textPtr, textPtr->interp, sizeof(objv)/sizeof(objv[0]), objv);
    for (i = 0; i < (int) (sizeof(objv)/sizeof(objv[0])); ++i) {
	Tcl_GuardedDecrRefCount(objv[i]);
    }

    Tcl_ListObjGetElements(textPtr->interp, Tcl_GetObjResult(textPtr->interp), &argc, &argv);
    for (i = 0; i < argc; i += 3) {
	char const *type = Tcl_GetString(argv[i]);
	char const *text = Tcl_GetString(argv[i + 1]);
	char const *indx = Tcl_GetString(argv[i + 2]);

	fprintf(stdout, "%s ", indx);
	fprintf(stdout, "%s ", type);

	if (strcmp(type, "text") == 0) {
	    int len = strlen(text), i;

	    fprintf(stdout, "\"");
	    for (i = 0; i < len; ++i) {
		char c = text[i];

		switch (c) {
		case '\t': fprintf(stdout, "\\t"); break;
		case '\n': fprintf(stdout, "\\n"); break;
		case '\v': fprintf(stdout, "\\v"); break;
		case '\f': fprintf(stdout, "\\f"); break;
		case '\r': fprintf(stdout, "\\r"); break;

		default:
		    if (UCHAR(c) < 0x80 && isprint(c)) {
			fprintf(stdout, "%c", c);
		    } else {
			fprintf(stdout, "\\x%02u", (unsigned) UCHAR(c));
		    }
		    break;
		}
	    }
	    fprintf(stdout, "\"\n");
	} else if (strcmp(type, "mark") == 0) {
	    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(&textPtr->sharedTextPtr->markTable, text);
	    const TkTextSegment *markPtr = NULL;

	    if (hPtr) {
		markPtr = Tcl_GetHashValue(hPtr);
	    } else {
		if (strcmp(text, "insert") == 0)  { markPtr = textPtr->insertMarkPtr; }
		if (strcmp(text, "current") == 0) { markPtr = textPtr->currentMarkPtr; }
	    }
	    if (markPtr) {
		fprintf(stdout, "%s (%s)\n", text,
			markPtr->typePtr == &tkTextLeftMarkType ? "left" : "right");
	    }
	} else {
	    fprintf(stdout, "%s\n", text);
	}
    }

    Tcl_SetObjResult(textPtr->interp, resultPtr);
    Tcl_GuardedDecrRefCount(resultPtr);
}

#endif /* NDEBUG */


#ifdef TK_C99_INLINE_SUPPORT
/* Additionally we need stand-alone object code. */
extern TkSharedText *	TkBTreeGetShared(TkTextBTree tree);
extern int		TkBTreeGetNumberOfDisplayLines(const TkTextPixelInfo *pixelInfo);
extern TkTextPixelInfo *TkBTreeLinePixelInfo(const TkText *textPtr, TkTextLine *linePtr);
extern TkSizeT		TkBTreeEpoch(TkTextBTree tree);
extern TkSizeT		TkBTreeIncrEpoch(TkTextBTree tree);
extern struct Node	*TkBTreeGetRoot(TkTextBTree tree);
extern TkTextLine *	TkBTreePrevLogicalLine(const TkSharedText *sharedTextPtr,
			    const TkText *textPtr, TkTextLine *linePtr);
extern TkTextTag *	TkBTreeGetTags(const TkTextIndex *indexPtr, TkTextSortMethod sortMeth,
			    int *flags);
extern TkTextLine *	TkBTreeGetStartLine(const TkText *textPtr);
extern TkTextLine *	TkBTreeGetLastLine(const TkText *textPtr);
extern TkTextLine *	TkBTreeNextLine(const TkText *textPtr, TkTextLine *linePtr);
extern TkTextLine *	TkBTreePrevLine(const TkText *textPtr, TkTextLine *linePtr);
extern unsigned		TkBTreeCountLines(const TkTextBTree tree, const TkTextLine *linePtr1,
			    const TkTextLine *linePtr2);
extern int		TkTextGetIndexFromObj(Tcl_Interp *interp, TkText *textPtr, Tcl_Obj *objPtr,
			    TkTextIndex *indexPtr);
extern int		TkTextIsDeadPeer(const TkText *textPtr);
extern int		TkTextIsMark(const TkTextSegment *segPtr);
extern int		TkTextIsStartEndMarker(const TkTextSegment *segPtr);
extern int		TkTextIsSpecialMark(const TkTextSegment *segPtr);
extern int		TkTextIsPrivateMark(const TkTextSegment *segPtr);
extern int		TkTextIsSpecialOrPrivateMark(const TkTextSegment *segPtr);
extern int		TkTextIsNormalOrSpecialMark(const TkTextSegment *segPtr);
extern int		TkTextIsNormalMark(const TkTextSegment *segPtr);
extern int		TkTextIsStableMark(const TkTextSegment *segPtr);
extern const TkTextDispChunk *TkTextGetFirstChunkOfNextDispLine(const TkTextDispChunk *chunkPtr);
extern const TkTextDispChunk *TkTextGetLastChunkOfPrevDispLine(const TkTextDispChunk *chunkPtr);
extern void		TkTextIndexSetEpoch(TkTextIndex *indexPtr, TkSizeT epoch);
extern void		TkTextIndexSetPeer(TkTextIndex *indexPtr, TkText *textPtr);
extern void		TkTextIndexSetToLastChar2(TkTextIndex *indexPtr, TkTextLine *linePtr);
extern void		TkTextIndexInvalidate(TkTextIndex *indexPtr);
extern void		TkTextIndexMakePersistent(TkTextIndex *indexPtr);
extern TkTextLine *	TkTextIndexGetLine(const TkTextIndex *indexPtr);
extern TkTextSegment *	TkTextIndexGetSegment(const TkTextIndex *indexPtr);
extern TkSharedText *	TkTextIndexGetShared(const TkTextIndex *indexPtr);
extern int		TkTextIndexSameLines(const TkTextIndex *indexPtr1, const TkTextIndex *indexPtr2);
extern void		TkTextIndexSave(TkTextIndex *indexPtr);
# if TK_MAJOR_VERSION == 8 && TK_MINOR_VERSION < 7 && TCL_UTF_MAX <= 4
extern int		TkUtfToUniChar(const char *src, int *chPtr);
# endif
#endif /* TK_C99_INLINE_SUPPORT */


/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 105
 * End:
 * vi:set ts=8 sw=4:
 */