Tk Source Code

Artifact [4e07fcce]
Login

Artifact 4e07fcce31a2c7d3109e37ced67a4243b7590edfd9b16d16d7cd1ab9a0aa154c:


     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
 11990
 11991
 11992
 11993
 11994
 11995
 11996
 11997
 11998
 11999
 12000
 12001
 12002
 12003
 12004
 12005
 12006
 12007
 12008
 12009
 12010
 12011
 12012
 12013
 12014
 12015
 12016
 12017
 12018
 12019
 12020
 12021
 12022
 12023
 12024
 12025
 12026
 12027
 12028
 12029
 12030
 12031
 12032
 12033
 12034
 12035
 12036
 12037
 12038
 12039
 12040
 12041
 12042
 12043
 12044
 12045
 12046
 12047
 12048
 12049
 12050
 12051
 12052
 12053
 12054
 12055
 12056
 12057
 12058
 12059
 12060
 12061
 12062
 12063
 12064
 12065
 12066
 12067
 12068
 12069
 12070
 12071
 12072
 12073
 12074
 12075
 12076
 12077
 12078
 12079
 12080
 12081
 12082
 12083
 12084
 12085
 12086
 12087
 12088
 12089
 12090
 12091
 12092
 12093
 12094
 12095
 12096
 12097
 12098
 12099
 12100
 12101
 12102
 12103
 12104
 12105
 12106
 12107
 12108
 12109
 12110
 12111
 12112
 12113
 12114
 12115
 12116
 12117
 12118
 12119
 12120
 12121
 12122
 12123
 12124
 12125
 12126
 12127
 12128
 12129
 12130
 12131
 12132
 12133
 12134
 12135
 12136
 12137
 12138
 12139
 12140
 12141
 12142
 12143
 12144
 12145
 12146
 12147
 12148
 12149
 12150
 12151
 12152
 12153
 12154
 12155
 12156
 12157
 12158
 12159
 12160
 12161
 12162
 12163
 12164
 12165
 12166
 12167
 12168
 12169
 12170
 12171
 12172
 12173
 12174
 12175
 12176
 12177
 12178
 12179
 12180
 12181
 12182
 12183
 12184
 12185
 12186
 12187
 12188
 12189
 12190
 12191
 12192
 12193
 12194
 12195
 12196
 12197
 12198
 12199
 12200
 12201
 12202
 12203
 12204
 12205
 12206
 12207
 12208
 12209
 12210
 12211
 12212
 12213
 12214
 12215
 12216
 12217
 12218
 12219
 12220
 12221
 12222
 12223
 12224
 12225
 12226
 12227
 12228
 12229
 12230
 12231
 12232
 12233
 12234
 12235
 12236
 12237
 12238
 12239
 12240
 12241
 12242
 12243
 12244
 12245
 12246
 12247
 12248
 12249
 12250
 12251
 12252
 12253
 12254
 12255
 12256
 12257
 12258
 12259
 12260
 12261
 12262
 12263
 12264
 12265
 12266
 12267
 12268
 12269
 12270
 12271
 12272
 12273
 12274
 12275
 12276
 12277
 12278
 12279
 12280
 12281
 12282
 12283
 12284
 12285
 12286
 12287
 12288
 12289
 12290
 12291
 12292
 12293
 12294
 12295
 12296
 12297
 12298
 12299
 12300
 12301
 12302
 12303
 12304
 12305
 12306
 12307
 12308
 12309
 12310
 12311
 12312
 12313
 12314
 12315
 12316
 12317
 12318
 12319
 12320
 12321
 12322
 12323
 12324
 12325
 12326
 12327
 12328
 12329
 12330
 12331
 12332
 12333
 12334
 12335
 12336
 12337
 12338
 12339
 12340
 12341
 12342
 12343
 12344
 12345
 12346
 12347
 12348
 12349
 12350
 12351
 12352
 12353
 12354
 12355
 12356
 12357
 12358
 12359
 12360
 12361
 12362
 12363
 12364
 12365
 12366
 12367
 12368
 12369
 12370
 12371
 12372
 12373
 12374
 12375
 12376
 12377
 12378
 12379
 12380
 12381
 12382
 12383
 12384
 12385
 12386
 12387
 12388
 12389
 12390
 12391
 12392
 12393
 12394
 12395
 12396
 12397
 12398
 12399
 12400
 12401
 12402
 12403
 12404
 12405
 12406
 12407
 12408
 12409
 12410
 12411
 12412
 12413
 12414
 12415
 12416
 12417
 12418
 12419
 12420
 12421
 12422
 12423
 12424
 12425
 12426
 12427
 12428
 12429
 12430
 12431
 12432
 12433
 12434
 12435
 12436
 12437
 12438
 12439
 12440
 12441
 12442
 12443
 12444
 12445
 12446
 12447
 12448
 12449
 12450
 12451
 12452
 12453
 12454
 12455
 12456
 12457
 12458
 12459
 12460
 12461
 12462
 12463
 12464
 12465
 12466
 12467
 12468
 12469
 12470
 12471
 12472
 12473
 12474
 12475
 12476
 12477
 12478
 12479
 12480
 12481
 12482
 12483
 12484
 12485
 12486
 12487
 12488
 12489
 12490
 12491
 12492
 12493
 12494
 12495
 12496
 12497
 12498
 12499
 12500
 12501
 12502
 12503
 12504
 12505
 12506
 12507
 12508
 12509
 12510
 12511
 12512
 12513
 12514
 12515
 12516
 12517
 12518
 12519
 12520
 12521
 12522
 12523
 12524
 12525
 12526
 12527
 12528
 12529
 12530
 12531
 12532
 12533
 12534
 12535
 12536
 12537
 12538
 12539
 12540
 12541
 12542
 12543
 12544
 12545
 12546
 12547
 12548
 12549
 12550
 12551
 12552
 12553
 12554
 12555
 12556
 12557
 12558
 12559
 12560
 12561
 12562
 12563
 12564
 12565
 12566
 12567
 12568
 12569
 12570
 12571
 12572
 12573
 12574
 12575
 12576
 12577
 12578
 12579
 12580
 12581
 12582
 12583
 12584
 12585
 12586
 12587
 12588
 12589
 12590
 12591
 12592
 12593
 12594
 12595
 12596
 12597
 12598
 12599
 12600
 12601
 12602
 12603
 12604
 12605
 12606
 12607
 12608
 12609
 12610
 12611
 12612
 12613
 12614
 12615
 12616
 12617
 12618
 12619
 12620
 12621
 12622
 12623
 12624
 12625
 12626
 12627
 12628
 12629
 12630
 12631
 12632
 12633
 12634
 12635
 12636
 12637
 12638
 12639
 12640
 12641
 12642
 12643
 12644
 12645
 12646
 12647
 12648
 12649
 12650
 12651
 12652
 12653
 12654
 12655
 12656
 12657
 12658
 12659
 12660
 12661
 12662
 12663
 12664
 12665
 12666
 12667
 12668
 12669
 12670
 12671
 12672
 12673
 12674
 12675
 12676
 12677
 12678
 12679
 12680
 12681
 12682
 12683
 12684
 12685
 12686
 12687
 12688
 12689
 12690
 12691
 12692
 12693
 12694
 12695
 12696
 12697
 12698
 12699
 12700
 12701
 12702
 12703
 12704
 12705
 12706
 12707
 12708
 12709
 12710
 12711
 12712
 12713
 12714
 12715
 12716
 12717
 12718
 12719
 12720
 12721
 12722
 12723
 12724
 12725
 12726
 12727
 12728
 12729
 12730
 12731
 12732
 12733
 12734
 12735
 12736
 12737
 12738
 12739
 12740
 12741
 12742
 12743
 12744
 12745
 12746
 12747
 12748
 12749
 12750
 12751
 12752
 12753
 12754
 12755
 12756
 12757
 12758
 12759
 12760
 12761
 12762
 12763
 12764
 12765
 12766
 12767
 12768
 12769
 12770
 12771
 12772
 12773
 12774
 12775
 12776
 12777
 12778
 12779
 12780
 12781
 12782
 12783
 12784
 12785
 12786
 12787
 12788
 12789
 12790
 12791
 12792
 12793
 12794
 12795
 12796
 12797
 12798
 12799
 12800
 12801
 12802
 12803
 12804
 12805
 12806
 12807
 12808
 12809
 12810
 12811
 12812
 12813
 12814
 12815
 12816
 12817
 12818
 12819
 12820
 12821
 12822
 12823
 12824
 12825
 12826
 12827
 12828
 12829
 12830
 12831
 12832
 12833
 12834
 12835
 12836
 12837
 12838
 12839
 12840
 12841
 12842
 12843
 12844
 12845
 12846
 12847
 12848
 12849
 12850
 12851
 12852
 12853
 12854
 12855
 12856
 12857
 12858
 12859
 12860
 12861
 12862
 12863
 12864
 12865
 12866
 12867
 12868
 12869
 12870
 12871
 12872
 12873
 12874
 12875
 12876
 12877
 12878
 12879
 12880
 12881
 12882
 12883
 12884
 12885
 12886
 12887
 12888
 12889
 12890
 12891
 12892
 12893
 12894
 12895
 12896
 12897
 12898
 12899
 12900
 12901
 12902
 12903
 12904
 12905
 12906
 12907
 12908
 12909
 12910
 12911
 12912
 12913
 12914
 12915
 12916
 12917
 12918
 12919
 12920
 12921
 12922
 12923
 12924
 12925
 12926
 12927
 12928
 12929
 12930
 12931
 12932
 12933
 12934
 12935
 12936
 12937
 12938
 12939
 12940
 12941
 12942
 12943
 12944
 12945
 12946
 12947
 12948
 12949
 12950
 12951
 12952
 12953
 12954
 12955
 12956
 12957
 12958
 12959
 12960
 12961
 12962
 12963
 12964
 12965
 12966
 12967
 12968
 12969
 12970
 12971
 12972
 12973
 12974
 12975
 12976
 12977
 12978
 12979
 12980
 12981
 12982
 12983
 12984
 12985
 12986
 12987
 12988
 12989
 12990
 12991
 12992
 12993
 12994
 12995
 12996
 12997
 12998
 12999
 13000
 13001
 13002
 13003
 13004
 13005
 13006
 13007
 13008
 13009
 13010
 13011
 13012
 13013
 13014
 13015
 13016
 13017
 13018
 13019
 13020
 13021
 13022
 13023
 13024
 13025
 13026
 13027
 13028
 13029
 13030
 13031
 13032
 13033
 13034
 13035
 13036
 13037
 13038
 13039
 13040
 13041
 13042
 13043
 13044
 13045
 13046
 13047
 13048
 13049
 13050
 13051
 13052
 13053
 13054
 13055
 13056
 13057
 13058
 13059
 13060
 13061
 13062
 13063
 13064
 13065
 13066
 13067
 13068
 13069
 13070
 13071
 13072
 13073
 13074
 13075
 13076
 13077
 13078
 13079
 13080
 13081
 13082
 13083
 13084
 13085
 13086
 13087
 13088
 13089
 13090
 13091
 13092
 13093
 13094
 13095
 13096
 13097
 13098
 13099
 13100
 13101
 13102
 13103
 13104
 13105
 13106
 13107
 13108
 13109
 13110
 13111
 13112
 13113
 13114
 13115
 13116
 13117
 13118
 13119
 13120
 13121
 13122
 13123
 13124
 13125
 13126
 13127
 13128
 13129
 13130
 13131
 13132
 13133
 13134
 13135
 13136
 13137
 13138
 13139
 13140
 13141
 13142
 13143
 13144
 13145
 13146
 13147
 13148
 13149
 13150
 13151
 13152
 13153
 13154
 13155
 13156
 13157
 13158
 13159
 13160
 13161
 13162
 13163
 13164
 13165
 13166
 13167
 13168
 13169
 13170
 13171
 13172
 13173
 13174
 13175
 13176
 13177
 13178
 13179
 13180
 13181
 13182
 13183
 13184
 13185
 13186
 13187
 13188
 13189
 13190
 13191
 13192
 13193
 13194
 13195
 13196
 13197
 13198
 13199
 13200
 13201
 13202
 13203
 13204
 13205
 13206
 13207
 13208
 13209
 13210
 13211
 13212
 13213
 13214
 13215
 13216
 13217
 13218
 13219
 13220
 13221
 13222
 13223
 13224
 13225
 13226
 13227
 13228
 13229
 13230
 13231
 13232
 13233
 13234
 13235
 13236
 13237
 13238
 13239
 13240
 13241
 13242
 13243
 13244
 13245
 13246
 13247
 13248
 13249
 13250
 13251
 13252
 13253
 13254
 13255
 13256
 13257
 13258
 13259
 13260
 13261
 13262
 13263
 13264
 13265
 13266
 13267
 13268
 13269
 13270
 13271
 13272
 13273
 13274
 13275
 13276
 13277
 13278
 13279
 13280
 13281
 13282
 13283
 13284
 13285
 13286
 13287
 13288
 13289
 13290
 13291
 13292
 13293
 13294
 13295
 13296
 13297
 13298
 13299
 13300
 13301
 13302
 13303
 13304
 13305
 13306
 13307
 13308
 13309
 13310
 13311
 13312
 13313
 13314
 13315
 13316
 13317
 13318
 13319
 13320
 13321
 13322
 13323
 13324
 13325
 13326
 13327
 13328
 13329
 13330
 13331
 13332
 13333
 13334
 13335
 13336
 13337
 13338
 13339
 13340
 13341
 13342
 13343
 13344
 13345
 13346
 13347
 13348
 13349
 13350
 13351
 13352
 13353
 13354
 13355
 13356
 13357
 13358
 13359
 13360
 13361
 13362
 13363
 13364
 13365
 13366
 13367
 13368
 13369
 13370
 13371
 13372
 13373
 13374
 13375
 13376
 13377
 13378
 13379
 13380
 13381
 13382
 13383
 13384
 13385
 13386
 13387
 13388
 13389
 13390
 13391
 13392
 13393
 13394
 13395
 13396
 13397
 13398
 13399
 13400
 13401
 13402
 13403
 13404
 13405
 13406
 13407
 13408
 13409
 13410
 13411
 13412
 13413
 13414
 13415
 13416
 13417
 13418
 13419
 13420
 13421
 13422
 13423
 13424
 13425
 13426
 13427
 13428
 13429
 13430
 13431
 13432
 13433
 13434
 13435
 13436
 13437
 13438
 13439
 13440
 13441
 13442
 13443
 13444
 13445
 13446
 13447
 13448
 13449
 13450
 13451
 13452
 13453
 13454
 13455
 13456
 13457
 13458
 13459
 13460
 13461
 13462
 13463
 13464
 13465
 13466
 13467
 13468
 13469
 13470
 13471
 13472
 13473
 13474
 13475
 13476
 13477
 13478
 13479
 13480
 13481
 13482
 13483
 13484
 13485
 13486
 13487
 13488
 13489
 13490
 13491
 13492
 13493
 13494
 13495
 13496
 13497
 13498
 13499
 13500
 13501
 13502
 13503
 13504
 13505
 13506
 13507
 13508
 13509
 13510
 13511
 13512
 13513
 13514
 13515
 13516
 13517
 13518
 13519
 13520
 13521
 13522
 13523
 13524
 13525
 13526
 13527
 13528
 13529
 13530
 13531
 13532
 13533
 13534
 13535
 13536
 13537
 13538
 13539
 13540
 13541
 13542
 13543
 13544
 13545
 13546
 13547
 13548
 13549
 13550
 13551
 13552
 13553
 13554
 13555
 13556
 13557
 13558
 13559
 13560
 13561
 13562
 13563
 13564
 13565
 13566
 13567
 13568
 13569
 13570
 13571
 13572
 13573
 13574
 13575
 13576
 13577
 13578
 13579
 13580
 13581
 13582
 13583
 13584
 13585
 13586
 13587
 13588
 13589
 13590
 13591
 13592
 13593
 13594
 13595
 13596
 13597
 13598
 13599
 13600
 13601
 13602
 13603
 13604
 13605
 13606
 13607
 13608
 13609
 13610
 13611
 13612
 13613
 13614
 13615
 13616
 13617
 13618
 13619
 13620
 13621
 13622
 13623
 13624
 13625
 13626
 13627
 13628
 13629
 13630
 13631
 13632
 13633
 13634
 13635
 13636
 13637
 13638
 13639
 13640
 13641
 13642
 13643
 13644
 13645
 13646
 13647
 13648
 13649
 13650
 13651
 13652
 13653
 13654
 13655
 13656
 13657
 13658
 13659
 13660
 13661
 13662
 13663
 13664
 13665
 13666
 13667
 13668
 13669
 13670
 13671
 13672
 13673
 13674
 13675
 13676
 13677
 13678
 13679
 13680
 13681
 13682
 13683
 13684
 13685
 13686
 13687
 13688
 13689
 13690
 13691
 13692
 13693
 13694
 13695
 13696
 13697
 13698
 13699
 13700
 13701
 13702
 13703
 13704
 13705
 13706
 13707
 13708
 13709
 13710
 13711
 13712
 13713
 13714
 13715
 13716
 13717
 13718
 13719
 13720
 13721
 13722
 13723
 13724
 13725
 13726
 13727
 13728
 13729
 13730
 13731
 13732
 13733
 13734
 13735
 13736
 13737
 13738
 13739
 13740
 13741
 13742
 13743
 13744
 13745
 13746
 13747
 13748
 13749
 13750
 13751
 13752
 13753
 13754
 13755
 13756
 13757
 13758
 13759
 13760
 13761
 13762
 13763
 13764
 13765
 13766
 13767
 13768
 13769
 13770
 13771
 13772
 13773
 13774
 13775
 13776
 13777
 13778
 13779
 13780
 13781
 13782
 13783
 13784
 13785
 13786
 13787
 13788
 13789
 13790
 13791
 13792
 13793
 13794
 13795
 13796
 13797
 13798
 13799
 13800
 13801
 13802
 13803
 13804
 13805
 13806
 13807
 13808
 13809
 13810
 13811
 13812
 13813
 13814
 13815
 13816
 13817
 13818
 13819
 13820
 13821
 13822
 13823
 13824
 13825
 13826
 13827
 13828
 13829
 13830
 13831
 13832
 13833
 13834
 13835
 13836
 13837
 13838
 13839
 13840
 13841
 13842
 13843
 13844
 13845
 13846
 13847
 13848
 13849
 13850
 13851
 13852
 13853
 13854
 13855
 13856
 13857
 13858
 13859
 13860
 13861
 13862
 13863
 13864
 13865
 13866
 13867
 13868
 13869
 13870
 13871
 13872
 13873
 13874
 13875
 13876
 13877
 13878
 13879
 13880
 13881
 13882
 13883
 13884
 13885
 13886
 13887
 13888
 13889
 13890
 13891
 13892
 13893
 13894
 13895
 13896
 13897
 13898
 13899
 13900
 13901
 13902
 13903
 13904
 13905
 13906
 13907
 13908
 13909
 13910
 13911
 13912
 13913
 13914
 13915
 13916
 13917
 13918
 13919
 13920
 13921
 13922
 13923
 13924
 13925
 13926
 13927
 13928
 13929
 13930
 13931
 13932
 13933
 13934
 13935
 13936
 13937
 13938
 13939
 13940
 13941
 13942
 13943
 13944
 13945
 13946
 13947
 13948
 13949
 13950
 13951
 13952
 13953
 13954
 13955
 13956
 13957
 13958
 13959
 13960
 13961
 13962
 13963
 13964
 13965
 13966
 13967
 13968
 13969
 13970
 13971
 13972
 13973
 13974
 13975
 13976
 13977
 13978
 13979
 13980
 13981
 13982
 13983
 13984
 13985
 13986
 13987
 13988
 13989
 13990
 13991
 13992
 13993
 13994
 13995
 13996
 13997
 13998
 13999
 14000
 14001
 14002
 14003
 14004
 14005
 14006
 14007
 14008
 14009
 14010
 14011
 14012
 14013
 14014
 14015
 14016
 14017
 14018
 14019
 14020
 14021
 14022
 14023
 14024
 14025
 14026
 14027
 14028
 14029
 14030
 14031
 14032
 14033
 14034
 14035
 14036
 14037
 14038
 14039
 14040
 14041
 14042
 14043
 14044
 14045
 14046
 14047
 14048
 14049
 14050
 14051
 14052
 14053
 14054
 14055
 14056
 14057
 14058
 14059
 14060
 14061
 14062
 14063
 14064
 14065
 14066
 14067
 14068
 14069
 14070
 14071
 14072
 14073
 14074
 14075
 14076
 14077
 14078
 14079
 14080
 14081
 14082
 14083
 14084
 14085
 14086
 14087
 14088
 14089
 14090
 14091
 14092
 14093
 14094
 14095
 14096
 14097
 14098
 14099
 14100
 14101
 14102
 14103
 14104
 14105
 14106
 14107
 14108
 14109
 14110
 14111
 14112
 14113
 14114
 14115
 14116
 14117
 14118
 14119
 14120
 14121
 14122
 14123
 14124
 14125
 14126
 14127
 14128
 14129
 14130
 14131
 14132
 14133
 14134
 14135
 14136
 14137
 14138
 14139
 14140
 14141
 14142
 14143
 14144
 14145
 14146
 14147
 14148
 14149
 14150
 14151
 14152
 14153
 14154
 14155
 14156
 14157
 14158
 14159
 14160
 14161
 14162
 14163
 14164
 14165
 14166
 14167
 14168
 14169
 14170
 14171
 14172
 14173
 14174
 14175
 14176
 14177
 14178
 14179
 14180
 14181
 14182
 14183
 14184
 14185
 14186
 14187
 14188
 14189
 14190
 14191
 14192
 14193
 14194
 14195
 14196
 14197
 14198
 14199
 14200
 14201
 14202
 14203
 14204
 14205
 14206
 14207
 14208
 14209
 14210
 14211
 14212
 14213
 14214
 14215
 14216
 14217
 14218
 14219
 14220
 14221
 14222
 14223
 14224
 14225
 14226
 14227
 14228
 14229
 14230
 14231
 14232
 14233
 14234
 14235
 14236
 14237
 14238
 14239
 14240
 14241
 14242
 14243
 14244
 14245
 14246
 14247
 14248
 14249
 14250
 14251
 14252
 14253
 14254
 14255
 14256
 14257
 14258
 14259
 14260
 14261
 14262
 14263
 14264
 14265
 14266
 14267
 14268
 14269
 14270
 14271
 14272
 14273
 14274
 14275
 14276
 14277
 14278
 14279
 14280
 14281
 14282
 14283
 14284
 14285
 14286
 14287
 14288
 14289
 14290
 14291
 14292
 14293
 14294
 14295
 14296
 14297
 14298
 14299
 14300
 14301
 14302
 14303
 14304
 14305
 14306
 14307
 14308
 14309
 14310
 14311
 14312
 14313
 14314
 14315
 14316
 14317
 14318
 14319
 14320
 14321
 14322
 14323
 14324
 14325
 14326
 14327
 14328
 14329
 14330
 14331
 14332
 14333
 14334
 14335
 14336
 14337
 14338
 14339
 14340
 14341
 14342
 14343
 14344
 14345
 14346
 14347
 14348
 14349
 14350
 14351
 14352
 14353
 14354
 14355
 14356
 14357
 14358
 14359
 14360
 14361
 14362
 14363
 14364
 14365
 14366
 14367
 14368
 14369
 14370
 14371
 14372
 14373
 14374
 14375
 14376
 14377
 14378
 14379
 14380
 14381
 14382
 14383
 14384
 14385
 14386
 14387
 14388
 14389
 14390
 14391
 14392
 14393
 14394
 14395
 14396
 14397
 14398
 14399
 14400
 14401
 14402
 14403
 14404
 14405
 14406
 14407
 14408
 14409
 14410
 14411
 14412
 14413
 14414
 14415
 14416
 14417
 14418
 14419
 14420
 14421
 14422
 14423
 14424
 14425
 14426
 14427
 14428
 14429
 14430
 14431
 14432
 14433
 14434
 14435
 14436
 14437
 14438
 14439
 14440
 14441
 14442
 14443
 14444
 14445
 14446
 14447
 14448
 14449
 14450
 14451
 14452
 14453
 14454
 14455
 14456
 14457
 14458
 14459
 14460
 14461
 14462
 14463
 14464
 14465
 14466
 14467
 14468
 14469
 14470
 14471
 14472
 14473
 14474
 14475
 14476
 14477
 14478
 14479
 14480
 14481
 14482
 14483
 14484
 14485
 14486
 14487
 14488
 14489
 14490
 14491
 14492
 14493
 14494
 14495
 14496
 14497
 14498
 14499
 14500
 14501
 14502
 14503
 14504
 14505
 14506
 14507
 14508
 14509
 14510
 14511
 14512
 14513
 14514
 14515
 14516
 14517
 14518
 14519
 14520
 14521
 14522
 14523
 14524
 14525
 14526
 14527
 14528
 14529
 14530
 14531
 14532
 14533
 14534
 14535
 14536
 14537
 14538
 14539
 14540
 14541
 14542
 14543
 14544
 14545
 14546
 14547
 14548
 14549
 14550
 14551
 14552
 14553
 14554
 14555
 14556
 14557
 14558
 14559
 14560
 14561
 14562
 14563
 14564
 14565
 14566
 14567
 14568
 14569
 14570
 14571
 14572
 14573
 14574
 14575
 14576
 14577
 14578
 14579
 14580
 14581
 14582
 14583
 14584
 14585
 14586
 14587
 14588
 14589
 14590
 14591
 14592
 14593
 14594
 14595
 14596
 14597
 14598
 14599
 14600
 14601
 14602
 14603
 14604
 14605
 14606
 14607
 14608
 14609
 14610
 14611
 14612
 14613
 14614
 14615
 14616
 14617
 14618
 14619
 14620
 14621
 14622
 14623
 14624
 14625
 14626
 14627
 14628
 14629
 14630
 14631
 14632
 14633
 14634
 14635
 14636
 14637
 14638
 14639
 14640
 14641
 14642
 14643
 14644
 14645
 14646
 14647
 14648
 14649
 14650
 14651
 14652
 14653
 14654
 14655
 14656
 14657
 14658
 14659
 14660
 14661
 14662
 14663
 14664
 14665
 14666
 14667
 14668
 14669
 14670
 14671
 14672
 14673
 14674
 14675
 14676
 14677
 14678
 14679
 14680
 14681
 14682
 14683
 14684
 14685
 14686
 14687
 14688
 14689
 14690
 14691
 14692
 14693
 14694
 14695
 14696
 14697
 14698
 14699
 14700
 14701
 14702
 14703
 14704
 14705
 14706
 14707
 14708
 14709
 14710
 14711
 14712
 14713
 14714
 14715
 14716
 14717
 14718
 14719
 14720
 14721
 14722
 14723
 14724
 14725
 14726
 14727
 14728
 14729
 14730
 14731
 14732
 14733
 14734
 14735
 14736
 14737
 14738
 14739
 14740
 14741
 14742
 14743
 14744
 14745
 14746
 14747
 14748
 14749
 14750
 14751
 14752
 14753
 14754
 14755
 14756
 14757
 14758
 14759
 14760
 14761
 14762
 14763
 14764
 14765
 14766
 14767
 14768
 14769
 14770
 14771
 14772
 14773
 14774
 14775
 14776
 14777
 14778
 14779
 14780
 14781
 14782
 14783
 14784
 14785
 14786
 14787
 14788
 14789
 14790
 14791
 14792
 14793
 14794
 14795
 14796
 14797
 14798
 14799
 14800
 14801
 14802
 14803
 14804
 14805
 14806
 14807
 14808
 14809
 14810
 14811
 14812
 14813
 14814
 14815
 14816
 14817
 14818
 14819
 14820
 14821
 14822
 14823
 14824
 14825
 14826
 14827
 14828
 14829
 14830
 14831
 14832
 14833
 14834
 14835
 14836
 14837
 14838
 14839
 14840
 14841
 14842
 14843
 14844
 14845
 14846
 14847
 14848
 14849
 14850
 14851
 14852
 14853
 14854
 14855
 14856
 14857
 14858
 14859
 14860
 14861
 14862
 14863
 14864
 14865
 14866
 14867
 14868
 14869
 14870
 14871
 14872
 14873
 14874
 14875
 14876
 14877
 14878
 14879
 14880
 14881
 14882
 14883
 14884
 14885
 14886
 14887
 14888
 14889
 14890
 14891
 14892
 14893
 14894
 14895
 14896
 14897
 14898
 14899
 14900
 14901
 14902
 14903
 14904
 14905
 14906
 14907
 14908
 14909
 14910
 14911
 14912
 14913
 14914
 14915
 14916
 14917
 14918
 14919
 14920
 14921
 14922
 14923
 14924
 14925
 14926
 14927
 14928
 14929
 14930
 14931
 14932
 14933
 14934
 14935
 14936
 14937
 14938
 14939
 14940
 14941
 14942
 14943
 14944
 14945
 14946
 14947
 14948
 14949
 14950
 14951
 14952
 14953
 14954
 14955
 14956
 14957
 14958
 14959
 14960
 14961
 14962
 14963
 14964
 14965
 14966
 14967
 14968
 14969
 14970
 14971
 14972
 14973
 14974
 14975
 14976
 14977
 14978
 14979
 14980
 14981
 14982
 14983
 14984
 14985
 14986
 14987
 14988
 14989
 14990
 14991
 14992
 14993
 14994
/*
 * tkTextDisp.c --
 *
 *	This module provides facilities to display text widgets. It is the
 *	only place where information is kept about the screen layout of text
 *	widgets. (Well, strictly, each TkTextLine and B-tree node caches its
 *	last observed pixel height, but that information originates here).
 *
 * Copyright © 1992-1994 The Regents of the University of California.
 * Copyright © 1994-1997 Sun Microsystems, Inc.
 * Copyright © 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 "tkTextTagSet.h"
#include "tkRangeList.h"

#ifdef _WIN32
# include "tkWinInt.h"
#elif defined(__CYGWIN__)
# include "tkUnixInt.h"
#endif

#ifdef MAC_OSX_TK
# include "tkMacOSXInt.h"
#endif

#include <stdlib.h>
#include <assert.h>

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

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

/*
 * "Calculations of line pixel heights and the size of the vertical
 * scrollbar."
 *
 * Given that tag, font and elide changes can happen to large numbers of
 * diverse chunks in a text widget containing megabytes of text, it is not
 * possible to recalculate all affected height information immediately any
 * such change takes place and maintain a responsive user-experience. Yet, for
 * an accurate vertical scrollbar to be drawn, we must know the total number
 * of vertical pixels shown on display versus the number available to be
 * displayed.
 *
 * The way the text widget solves this problem is by maintaining cached line
 * pixel heights (in the BTree for each logical line), and having asynchronous
 * timer callbacks (i) to iterate through the logical lines recalculating
 * their heights, and (ii) to recalculate the vertical scrollbar's position
 * and size.
 *
 * Typically this works well but there are some situations where the overall
 * functional design of this file causes some problems. These problems can
 * only arise because the calculations used to display lines on screen are not
 * connected to those in the iterating-line- recalculation-process.
 *
 * The reason for this disconnect is that the display calculations operate in
 * display lines, and the iteration and cache operates in logical lines.
 * Given that the display calculations both need not contain complete logical
 * lines (at top or bottom of display), and that they do not actually keep
 * track of logical lines (for simplicity of code and historical design), this
 * means a line may be known and drawn with a different pixel height to that
 * which is cached in the BTree, and this might cause some temporary
 * undesirable mismatch between display and the vertical scrollbar.
 *
 * All such mismatches should be temporary, however, since the asynchronous
 * height calculations will always catch up eventually.
 *
 * For further details see the comments before and within the following
 * functions below: LayoutDLine, AsyncUpdateLineMetrics, GetYView,
 * GetYPixelCount, UpdateOneLine, UpdateLineMetrics.
 *
 * For details of the way in which the BTree keeps track of pixel heights, see
 * tkTextBTree.c. Basically the BTree maintains two pieces of information: the
 * logical line indices and the pixel height cache.
 */

/*
 * TK_LAYOUT_WITH_BASE_CHUNKS:
 *
 *	With this macro set, collect all char chunks that have no holes
 *	between them, that are on the same line and use the same font and font
 *	size. Allocate the chars of all these chunks, the so-called "stretch",
 *	in a DString in the first chunk, the so-called "base chunk". Use the
 *	base chunk string for measuring and drawing, so that these actions are
 *	always performed with maximum context.
 *
 *	This is necessary for text rendering engines that provide ligatures
 *	and sub-pixel layout, like ATSU on Mac. If we don't do this, the
 *	measuring will change all the time, leading to an ugly "tremble and
 *	shiver" effect. This is because of the continuous splitting and
 *	re-merging of chunks that goes on in a text widget, when the cursor or
 *	the selection move.
 *
 * Side effects:
 *
 *	Memory management changes. Instead of attaching the character data to
 *	the clientData structures of the char chunks, an additional DString is
 *	used. The collection process will even lead to resizing this DString
 *	for large stretches (> TCL_DSTRING_STATIC_SIZE == 200). We could
 *	reduce the overall memory footprint by copying the result to a plain
 *	char array after the line breaking process, but that would complicate
 *	the code and make performance even worse speedwise.
 */

/*
 * The following macro is used to compare two floating-point numbers to within
 * a certain degree of scale. Direct comparison fails on processors where the
 * processor and memory representations of FP numbers of a particular
 * precision is different (e.g. Intel)
 */

#define FP_EQUAL_SCALE(double1, double2, scaleFactor) \
    (fabs((double1) - (double2))*((scaleFactor) + 1.0) < 0.3)

/*
 * Macros to make debugging/testing logging a little easier.
 */

#define LOG(toVar,what) \
    Tcl_SetVar2(textPtr->interp, toVar, NULL, what, TCL_GLOBAL_ONLY|TCL_APPEND_VALUE|TCL_LIST_ELEMENT)
#define CLEAR(var) \
    Tcl_SetVar2(interp, var, NULL, "", TCL_GLOBAL_ONLY)

/*
 * Speed up if the text content only contains monospaced line heights, and line wrapping
 * is disabled.
 *
 * But this speed-up trial seems not to have any effect which is worth the effort,
 * especially because it can be used only if no line wrapping will be done.
 */

#define SPEEDUP_MONOSPACED_LINE_HEIGHTS 0

/*
 * Structure for line break information:
 */

typedef struct TkTextBreakInfo {
    uint32_t refCount;	/* Reference counter, destroy if this counter is going to zero. */
#ifndef NDEBUG
    uint32_t brksSize;	/* Size of break info array, only needed for debugging. */
#endif
    char *brks;		/* Array of break info, has exactly the char length of the logical line,
			 * each cell is one of LINEBREAK_NOBREAK, LINEBREAK_ALLOWBREAK,
			 * LINEBREAK_MUSTBREAK, or LINEBREAK_INSIDEACHAR. */
    struct TkTextBreakInfo *nextPtr;
			/* Pointer to break information of successor line. Will only be used
			 * when caching the break information while redrawing tags. */
} TkTextBreakInfo;

typedef struct TkTextDispLine DLine;

/*
 * Flag bits for DLine structures:
 *
 * HAS_3D_BORDER -		Non-zero means that at least one of the chunks in this line has
 *				a 3D border, so itpotentially interacts with 3D borders in
 *				neighboring lines (see DisplayLineBackground).
 * NEW_LAYOUT -			Non-zero means that the line has been re-layed out since the last
 *				time the display was updated.
 * TOP_LINE -			Non-zero means that this was the top line in in the window the last
 *				time that the window was laid out. This is important because a line
 *				may be displayed differently if it's at the top or bottom than if
 *				it's in the middle (e.g. beveled edges aren't displayed for middle
 *				lines if the adjacent line has a similar background).
 * BOTTOM_LINE -		Non-zero means that this was the bottom line in the window the last
 *				time that the window was laid out.
 * OLD_Y_INVALID -		The value of oldY in the structure is not valid or useful and should
 *				not be examined. 'oldY' is only useful when the DLine is currently
 *				displayed at a different position and we wish to re-display it via
 *				scrolling, so this means the DLine needs redrawing.
 * PARAGRAPH_START -		We are on the first line of a paragraph (used to choose between
 *				lmargin1, lmargin2).
 * CURSOR -			This display line is displaying the cursor.
 */

#define HAS_3D_BORDER	(1 << 0)
#define NEW_LAYOUT	(1 << 1)
#define TOP_LINE	(1 << 2)
#define BOTTOM_LINE	(1 << 3)
#define OLD_Y_INVALID	(1 << 4)
#define PARAGRAPH_START	(1 << 5)
#define DELETED		(1 << 6) /* for debugging */
#define LINKED		(1 << 7) /* for debugging */
#define CACHED		(1 << 8) /* for debugging */

/*
 * The following structure describes how to display a range of characters.
 * The information is generated by scanning all of the tags associated with
 * the characters and combining that with default information for the overall
 * widget. These structures form the hash keys for dInfoPtr->styleTable.
 */

typedef struct StyleValues {
    Tk_3DBorder border;		/* Used for drawing background under text.
				 * NULL means use widget background. */
    Pixmap bgStipple;		/* Stipple bitmap for background. None means
				 * draw solid. */
    XColor *fgColor;		/* Foreground color for text. */
    XColor *eolColor;		/* Foreground color for end of line symbol, can be NULL. */
    XColor *eotColor;		/* Foreground color for end of text symbol, can be NULL. */
    XColor *hyphenColor;	/* Foreground color for soft hyphens, can be NULL. */
    Tk_Font tkfont;		/* Font for displaying text. */
    Pixmap fgStipple;		/* Stipple bitmap for text and other foreground stuff. None means
				 * draw solid.*/
    TkTextTabArray *tabArrayPtr;/* Locations and types of tab stops (may be NULL). */
    Tk_3DBorder lMarginColor;	/* Color of left margins (1 and 2). */
    Tk_3DBorder rMarginColor;	/* Color of right margin. */
    XColor *overstrikeColor;	/* Foreground color for overstrike through text. */
    XColor *underlineColor;	/* Foreground color for underline underneath text. */
    char const *lang;		/* Language support (may be NULL). */
    int hyphenRules;		/* Hyphenation rules for spelling changes. */
    int32_t borderWidth;	/* Width of 3-D border for background. */
    int32_t lMargin1;		/* Left margin, in pixels, for first display line of each text line. */
    int32_t lMargin2;		/* Left margin, in pixels, for second and later display lines of
				 * each text line. */
    int32_t offset;		/* Offset in pixels of baseline, relative to baseline of line. */
    int32_t rMargin;		/* Right margin, in pixels. */
    int32_t spacing1;		/* Spacing above first dline in text line. */
    int32_t spacing2;		/* Spacing between lines of dline. */
    int32_t spacing3;		/* Spacing below last dline in text line. */
    uint32_t wrapMode:3;	/* How to handle wrap-around for this tag. One of TEXT_WRAPMODE_CHAR,
				 * TEXT_WRAPMODE_NONE, TEXT_WRAPMODE_WORD, or TEXT_WRAPMODE_CODEPOINT.*/
    uint32_t tabStyle:3;	/* One of TABULAR or WORDPROCESSOR. */
    uint32_t justify:3;		/* Justification style for text. */
    uint32_t relief:3;		/* 3-D relief for background. */
    uint32_t indentBg:1;	/* Background will be indented accordingly to the -lmargin1,
				 * and -lmargin2 options. */
    uint32_t overstrike:1;	/* Non-zero means draw overstrike through text. */
    uint32_t underline:1;	/* Non-zero means draw underline underneath text. */
    uint32_t elide:1;		/* Zero means draw text, otherwise not. */
} StyleValues;

/*
 * The following structure extends the StyleValues structure above with
 * graphics contexts used to actually draw the characters. The entries in
 * dInfoPtr->styleTable point to structures of this type.
 */

typedef struct TextStyle {
    StyleValues *sValuePtr;	/* Raw information from which GCs were derived. */
    Tcl_HashEntry *hPtr;	/* Pointer to entry in styleTable. Used to delete entry. */
    GC bgGC;			/* Graphics context for background. None means use widget background. */
    GC fgGC;			/* Graphics context for foreground. */
    GC ulGC;			/* Graphics context for underline. */
    GC ovGC;			/* Graphics context for overstrike. */
    GC eolGC;			/* Graphics context for end of line symbol. */
    GC eotGC;			/* Graphics context for end of text symbol. */
    GC hyphenGC;		/* Graphics context for soft hyphen character. */
    uint32_t refCount;		/* Number of times this structure is referenced in Chunks. */
} TextStyle;

/*
 * In TkTextDispChunk structures for character segments, the clientData field
 * points to one of the following structures:
 */

typedef struct CharInfo {
    union {
	const char *chars;	/* UTF characters to display. Actually points into the baseChars of
				 * the base chunk. */
	struct CharInfo *next;	/* Pointer to next free info struct. */
    } u;
    Tcl_Size numBytes;		/* Number of bytes that belong to this chunk. */
    Tcl_Size baseOffset;		/* Starting offset in baseChars of base chunk; always zero if
				 * context drawing is not used. */
    TkTextSegment *segPtr;	/* Pointer to char segment containing the chars. */
} CharInfo;

typedef struct PixelPos {
    int32_t xFirst, xLast;	/* Horizontal pixel position. */
    int32_t yFirst, yLast;	/* Vertical pixel position. */
} PixelPos;

typedef struct DRegion {
    int y1;
    int y2;
} DRegion;

/*
 * Overall display information for a text widget:
 */

typedef struct TextDInfo {
    Tcl_HashTable styleTable;	/* Hash table that maps from StyleValues to TextStyles for this
				 * widget. */
    DLine *dLinePtr;		/* First in list of all display lines for this widget, in order
				 * from top to bottom. */
    DLine *lastDLinePtr;	/* Pointer to last display line in this widget. */
    TextStyle *defaultStyle;	/* Default style. */
    GC copyGC;			/* Graphics context for copying from off-screen pixmaps onto screen. */
    GC scrollGC;		/* Graphics context for copying from one place in the window to
				 * another (scrolling): differs from copyGC in that we need to get
				 * GraphicsExpose events. */
    GC insertFgGC;		/* Graphics context for drawing text "behind" the insert cursor. */
    double xScrollFirst, xScrollLast;
				/* Most recent values reported to horizontal scrollbar; used to
				 * eliminate unnecessary reports. */
    double yScrollFirst, yScrollLast;
				/* Most recent values reported to vertical scrollbar; used to
				 * eliminate unnecessary reports. */
    uint32_t firstLineNo;	/* Line number of first line in text widget, needed for re-layout. */
    uint32_t lastLineNo;	/* Line number of last line in text widget, needed for re-layout. */
    int32_t topPixelOffset;	/* Identifies first pixel in top display line to display in window. */
    int32_t newTopPixelOffset;	/* Desired first pixel in top display line to display in window. */
    int32_t x;			/* First x-coordinate that may be used for actually displaying line
				 * information. Leaves space for border, etc. */
    int32_t y;			/* First y-coordinate that may be used for actually displaying line
				 * information. Leaves space for border, etc. */
    int32_t maxX;		/* First x-coordinate to right of available space for displaying
				 * lines. */
    int32_t maxY;		/* First y-coordinate below available space for displaying lines. */
    int32_t topOfEof;		/* Top-most pixel (lowest y-value) that has been drawn in the
				 * appropriate fashion for the portion of the window after the last
				 * line of the text. This field is used to figure out when to redraw
				 * part or all of the eof field. */
    int32_t curYPixelOffset;	/* Y offset of the current view. */
    TkTextSegment *endOfLineSegPtr;
				/* Holds the end of line symbol (option -showendOfline). */
    TkTextSegment *endOfTextSegPtr;
				/* Holds the end of text symbol (option -showendOftext). */
    DRegion invalidRegion;	/* This regions contains the invalidated regions, because these
				 * regions cannot be scrolled. */

    /*
     * Cache for single lines:
     */

    DLine *cachedDLinePtr;	/* We are caching some computed display lines for speed enhancements. */
    DLine *lastCachedDLinePtr;	/* Pointer to last cached display line. */
    unsigned numCachedLines;	/* Number of cached display lines. */
    DLine *lastMetricDLinePtr;	/* We are caching the last computed display line in metric computation,
				 * one reason is speed up, but the main reason is to avoid that some
				 * cached data (i.e. brks) will be released to early. */

    /*
     * Storage for saved display lines. These lines has been computed for line metric information,
     * and will be used for displaying afterwards.
     */

    DLine *savedDLinePtr;	/* First in list of saved display lines, in order from top to bottom. */
    DLine *lastSavedDLinePtr;/* Pointer to last saved display line. */
    int32_t savedDisplayLinesHeight;
				/* Sum of saved display line heights. */

    /*
     * Additional buffers:
     */

    char *strBuffer;		/* We need a string buffer for the line break algorithm. */
    unsigned strBufferSize;	/* Size of the line break string buffer. */

    /*
     * Information used for scrolling:
     */

    int32_t newXPixelOffset;	/* Desired x scroll position, measured as the number of pixels
				 * off-screen to the left for a line with no left margin. */
    int32_t curXPixelOffset;	/* Actual x scroll position, measured as the number of pixels
				 * off-screen to the left. */
    uint32_t maxLength;		/* Length in pixels of longest line that's visible in window
				 * (length may exceed window size). If there's no wrapping, this
				 * will be zero. */
    PixelPos curPixelPos;	/* Most recent pixel position, used for the "watch" command. */
    PixelPos prevPixelPos;	/* Previous pixel position, used for the "watch" command. */

    /*
     * The following information is used to implement scanning:
     */

    int32_t scanMarkXPixel;	/* Pixel index of left edge of the window when the scan started. */
    int32_t scanMarkX;		/* X-position of mouse at time scan started. */
    int32_t scanTotalYScroll;	/* Total scrolling (in screen pixels) that has occurred since
				 * scanMarkY was set. */
    int32_t scanMarkY;		/* Y-position of mouse at time scan started. */

    /*
     * The following is caching the current chunk information:
     */

    TkTextIndex currChunkIndex;	/* Index position of current chunk. */
    TkTextDispChunk *currChunkPtr;
				/* This is the chunk currently hovered by mouse. */
    DLine *currDLinePtr;	/* The DLine which contains the current chunk. */

    /*
     * Cache current y-view position:
     */

    int32_t topLineNo;
    int32_t topByteIndex;

    /*
     * Pools for lines, chunks, char infos, and break infos:
     */

    DLine *dLinePoolPtr;	/* Pointer to first free display line. */
    TkTextDispChunk *chunkPoolPtr;
				/* Pointer to first free chunk. */
    struct TkTextDispChunkSection *sectionPoolPtr;
				/* Pointer to first free section. */
    CharInfo *charInfoPoolPtr;	/* Pointer to first free char info. */
    unsigned chunkCounter;	/* Used for the unique chunk ID. */

    /*
     * Miscellaneous information:
     */

    int dLinesInvalidated;	/* This value is set to true whenever something happens that
				 * invalidates information in DLine structures; if a redisplay
				 * is in progress, it will see this and abort the redisplay. This
				 * is needed because, for example, an embedded window could change
				 * its size when it is first displayed, invalidating the DLine that
				 * is currently being displayed. If redisplay continues, it will
				 * use freed memory and could dump core. */
    int pendingUpdateLineMetricsFinished;
				/* Did we add RunUpdateLineMetricsFinished to the idle loop? */
    int32_t flags;		/* Various flag values: see below for definitions. */
    uint32_t countImages;	/* Number of displayed images (currently unused except if
				 * SPEEDUP_MONOSPACED_LINE_HEIGHTS is set). */
    uint32_t countWindows;	/* Number of displayed windows. */
    int insideLineMetricUpdate;/* Line metric update is currently in progress. */

    /*
     * Information used to handle the asynchronous updating of the y-scrollbar
     * and the vertical height calculations:
     */

    int lineHeight;		/* TkTextRelayoutWindow is using this value: the line height of
				 * monospaced lines, is zero of the line heights are not monospaced
				 * in last call of TkTextRelayoutWindow. */
    uint32_t lineMetricUpdateEpoch;
				/* Stores a number which is incremented each time the text widget
				 * changes in a significant way (e.g. resizing or geometry-influencing
				 * tag changes). */
    uint32_t lineMetricUpdateCounter;
				/* Count updates of line metric information. */
    TkRangeList *lineMetricUpdateRanges;
				/* Stores the range of line numbers which are not yet up-to-date. */
    TkTextIndex metricIndex;	/* If the current metric update line wraps into very many display
				 * lines, then this is used to keep track of what index we've got
				 * to so far... */
    Tcl_TimerToken lineUpdateTimer;
				/* A token pointing to the current line metric update callback. */
    Tcl_TimerToken scrollbarTimer;
				/* A token pointing to the current scrollbar update callback. */
    Tcl_TimerToken repickTimer;
				/* A token pointing to the current repick callback. */
} TextDInfo;

typedef struct TkTextDispChunkSection {
    struct TkTextDispChunkSection *nextPtr;
				/* Next section in chain of display sections. */
    TkTextDispChunk *chunkPtr;	/* First display chunk in this section. */
    uint32_t numBytes;		/* Number of bytes in this section. */
} TkTextDispChunkSection;

/*
 * Flag values for TextDInfo structures:
 *
 * DINFO_OUT_OF_DATE:	Means that the DLine structures for this window are partially or
 *			completely out of date and need to be recomputed.
 *
 * REDRAW_PENDING:	Means that a when-idle handler has been scheduled to update the display.
 *
 * REDRAW_BORDERS:	Means window border or pad area has potentially been damaged and must
 *			be redrawn.
 *
 * ASYNC_UPDATE:	Means that the asynchronous pixel-height calculation is still working.
 *
 * ASYNC_PENDING:	Means that the asynchronous pixel-height calculation is pending until
 *			the display update (DisplayText) has been finished.
 *
 * REPICK_NEEDED:	Means that the widget has been modified in a way that could change
 *			the current character (a different character might be under the mouse
 *			cursor now). Need to recompute the current character before the next
 *			redisplay.
 */

#define DINFO_OUT_OF_DATE	(1 << 0)
#define REDRAW_PENDING		(1 << 1)
#define REDRAW_BORDERS		(1 << 2)
#define ASYNC_UPDATE		(1 << 3)
#define ASYNC_PENDING		(1 << 4)
#define REPICK_NEEDED		(1 << 5)

typedef struct LayoutPos {
    TkTextSegment *segPtr;
    int offset;
} LayoutPos;

typedef struct LayoutData {
    TkText *textPtr;
    DLine *dlPtr;		/* Current display line. */
    TkTextDispChunk *chunkPtr;	/* Start of chunk chain. */
    TkTextDispChunk *tabChunkPtr;
				/* Pointer to the chunk containing the previous tab stop. */
    TkTextDispChunk *firstChunkPtr;
				/* Pointer to the first chunk. */
    TkTextDispChunk *lastChunkPtr;
				/* Pointer to the current chunk. */
    TkTextDispChunk *firstCharChunkPtr;
				/* Pointer to the first char/hyphen/window/image chunk in chain. */
    TkTextDispChunk *lastCharChunkPtr;
				/* Pointer to the last char/hyphen/window/image chunk in chain. */
    TkTextDispChunk *breakChunkPtr;
				/* Chunk containing best word break point, if any. */
    TkTextDispChunk *cursorChunkPtr;
				/* Pointer to the insert cursor chunk. */
    TkTextLine *logicalLinePtr;	/* Pointer to the logical line. */
    TkTextBreakInfo *breakInfo;	/* Line break information of logical line. */
    LayoutPos decimalPointPos;	/* This character segment contains the decimal point. */
    LayoutPos lastNumericalPos; /* This character segment contains the last part of a numerical tab. */
    LayoutPos shiftToNextLinePos;
				/* Shift characters starting with this position to next line. */
    const char *brks;		/* Buffer for line break information (for TEXT_WRAPMODE_CODEPOINT). */
    TkTextIndex index;		/* Current index. */
    unsigned countChunks;	/* Number of chunks in current display line. */
    unsigned countVisibleChunks;/* Number of visible (width > 0) chunks in current display line. */
    unsigned numBytesSoFar;	/* The number of processed bytes (so far). */
    unsigned byteOffset;	/* The byte offset to start of logical line. */
    unsigned dispLineOffset;	/* The byte offset to start of display line. */
    int increaseNumBytes;	/* Increase number of consumed bytes to realize spelling changes. */
    unsigned decreaseNumBytes;	/* Decrease number of displayable bytes to realize spelling changes. */
    unsigned displayLineNo;	/* Current display line number. */
    int rMargin;		/* Right margin width for line. */
    int hyphenRule;		/* Hyphenation rule applied to last char chunk (only in hyphenation
				 * has been applied). */
    TkTextTabArray *tabArrayPtr;/* Tab stops for line; taken from style for the first character
				 * on line. */
    int tabStyle;		/* One of TABULAR or WORDPROCESSOR. */
    int tabSize;		/* Number of pixels consumed by current tab stop. */
    int tabX;			/* Position of next tab, needed for alignment of numerical tabs. */
    int tabShift;		/* Position of first tab in display line, if first tab is LEFT,
				 * zero otherwise. */
    int tabIndex;		/* Index of the current tab stop. */
    int tabOverhang;		/* Overhang from computed line break. */
    TkTextTabAlign tabAlignment;/* Alignment of current active tab. */
    unsigned tabWidth;		/* Default tab width of this widget. */
    unsigned numSpaces;		/* Number of expandable space (needed for full justification). */
    unsigned shiftToNextLine;	/* Shift this number of characters to next line for adjustment of
				 * numeric tabs, starting with shiftToNextLinePos. */
    unsigned lengthOfFractional;/* Length of fractional part in numerical tabs, including decimal
				 * point. */
    TkTextJustify justify;	/* How to justify line: taken from style for the first character
				 * in this display line. */
    TkWrapMode wrapMode;	/* Wrap mode to use for this chunk. */
    int maxX;			/* Maximal x coord in current line. */
    int width;			/* Maximal x coord in widget. */
    int x;			/* Current x coord. */
    int paragraphStart;	/* 'true' means that we are on the first line of a paragraph
				 * (used to choose between lmargin1, lmargin2). */
    int skipSpaces;		/* 'true' means that we have to gobble spaces at start of next
				 * segment. */
    int trimSpaces;		/* 'true' iff space mode is TEXT_SPACEMODE_TRIM. */
    int isNumericTab;		/* We are processing the integral part of a numeric tab. */
    int isRightTab;		/* We are processing a right tab. */
    int adjustFirstChunk;	/* Start adjustment of chunks with first chunk, needed for line wrapping
				 * with right tabs. */
    int tabApplied;		/* Current tab has been already applied? */

#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
    /*
     * Support for context drawing.
     */

    TkTextDispChunk *baseChunkPtr;
				/* The chunk which contains the actual context data. */
#endif
} LayoutData;

typedef struct DisplayInfo {
    int byteOffset;		/* Byte offset to start of display line (subtract this offset to
				 * get the index of display line start). */
    int nextByteOffset;		/* Byte offset to start of next display line (add this offset to
				 * get the index of next display line start). */
    unsigned displayLineNo;	/* Number of display line. */
    unsigned numDispLines;	/* Total number of display lines belonging to corresponding logical
				 * line (so far). */
    int pixels;			/* Total height of logical line (so far). */
    int isComplete;		/* The display line metric is complete for this logical line? */
    const TkTextDispLineEntry *entry;
				/* Pointer to entry in display pixel info for displayLineNo. Note
				 * that the predecessing entries can be accessed, but not the successing
				 * entries. */
    DLine *dLinePtr;		/* Cached display lines, produced while ComputeDisplayLineInfo is
				 * computing the line metrics. */
    DLine *lastDLinePtr;	/* Pointer to last cached display line. */
    unsigned numCachedLines;	/* Number of cached lines. */
    unsigned heightOfCachedLines;
				/* Sum of cached display line heights. */
    TkTextIndex index;		/* Index where the computation has finished. */
    TkTextLine *linePtr;	/* Logical line, where computation has started. */
    const TkTextPixelInfo *pixelInfo;
				/* Pixel information of logical line. */
    TkTextBreakInfo *lineBreakInfo;
				/* We have to cache the line break information (for
				 * TEXT_WRAPMODE_CODEPOINT), to avoid repeated computations when
				 * scrolling. */

    /*
     * This attribute is private.
     */

    TkTextDispLineEntry entryBuffer[2];
				/* This buffer will be used if the logical line has no entries
				 * (single display line). */
} DisplayInfo;

/*
 * Action values for FreeDLines:
 *
 * DLINE_UNLINK:	Free, unlink from current display, and set 'dLinesInvalidated'.
 *
 * DLINE_UNLINK_KEEP_BRKS:
 *			Same as DLINE_UNLINK, but do not destroy break info (except if
 *			now outside of peer).
 *
 * DLINE_FREE_TEMP:	Free, but don't unlink, and also don't set 'dLinesInvalidated'.
 *
 * DLINE_CACHE:		Don't free, don't unlink, cache this line, and don't set 'dLinesInvalidated'.
 *
 * DLINE_METRIC:	Don't free, don't unlink, cache this line temporarily, and don't set
 *			'dLinesInvalidated'.
 *
 * DLINE_SAVE:		Don't free, unlink, and save this line for displaying later.
 */

typedef enum {
    DLINE_UNLINK, DLINE_UNLINK_KEEP_BRKS, DLINE_FREE_TEMP, DLINE_CACHE, DLINE_METRIC, DLINE_SAVE
} FreeDLineAction;

/*
 * Maximal number of cached display lines.
 */

#define MAX_CACHED_DISPLAY_LINES 8

/*
 * Macro that determines how much space to allocate for TkTextDispLineInfo:
 */

#define TEXT_DISPLINEINFO_SIZE(numDispLines) (offsetof(TkTextDispLineInfo, entry) + \
	(numDispLines)*sizeof(((TkTextDispLineInfo *) 0)->entry[0]))

/*
 * We will also mark logical lines with current line metric epoch even if the computation
 * has been done only partial. In this case we add a special bit to mark it as partially
 * computed.
 */

#define EPOCH_MASK		0x7fffffff
#define PARTIAL_COMPUTED_BIT	0x80000000

/*
 * Result values returned by TextGetScrollInfoObj:
 */

typedef enum {
    SCROLL_MOVETO,
    SCROLL_PAGES,
    SCROLL_UNITS,
    SCROLL_ERROR,
    SCROLL_PIXELS
} ScrollMethod;

/*
 * Threshold type for ComputeMissingMetric:
 */

typedef enum {
    THRESHOLD_BYTE_OFFSET,	/* compute until byte offset has been reached */
    THRESHOLD_LINE_OFFSET,	/* compute until display line offset has been reached */
    THRESHOLD_PIXEL_DISTANCE	/* compute until pixel distance has been reached */
} Threshold;

/*
 * We don't want less than 10 chunks per display section.
 */
#define MIN_CHUNKS_PER_SECTION 10u

/*
 * We don't want more than 20 sections per display line.
 */
#define MAX_SECTIONS_PER_LINE 20

/*
 * Use U+2010 for hyphen code point.
 */

#define HYPHEN_LENGTH 3
#define HYPHEN_STRING "\xe2\x80\x90"

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

static void		AdjustForTab(LayoutData *data);
static void		ComputeSizeOfTab(LayoutData *data, TkTextSegment *segPtr, int offset);
static void		ComputeShiftForNumericTab(LayoutData *data, TkTextSegment *firstSegPtr,
			    int offset);
static void		ComputeShiftForRightTab(LayoutData *data, TkTextSegment *segPtr, int offset);
static int		IsStartOfTab(TkTextSegment *segPtr, int offset);
static void		ElideBboxProc(TkText *textPtr, TkTextDispChunk *chunkPtr, Tcl_Size index, int y,
			    int lineHeight, int baseline, int *xPtr, int *yPtr, int *widthPtr,
			    int *heightPtr);
static Tcl_Size	ElideMeasureProc(TkTextDispChunk *chunkPtr, int x);
static void		DisplayDLine(TkText *textPtr, DLine *dlPtr, DLine *prevPtr, Pixmap pixmap);
static void		DisplayLineBackground(TkText *textPtr, DLine *dlPtr, DLine *prevPtr,
			    Pixmap pixmap);
static void		DisplayText(void *clientData);
static DLine *		FindCachedDLine(TkText *textPtr, const TkTextIndex *indexPtr);
static DLine *		FindDLine(TkText *textPtr, DLine *dlPtr, const TkTextIndex *indexPtr);
static DLine *		FreeDLines(TkText *textPtr, DLine *firstPtr, DLine *lastPtr,
			    FreeDLineAction action);
static void		FreeStyle(TkText *textPtr, TextStyle *stylePtr);
static TextStyle *	GetStyle(TkText *textPtr, TkTextSegment *segPtr);
static void		UpdateDefaultStyle(TkText *textPtr);
static int		GetBbox(TkText *textPtr, const DLine *dlPtr, const TkTextIndex *indexPtr,
			    int *xPtr, int *yPtr, int *widthPtr, int *heightPtr, int *isLastCharInLine,
			    Tcl_UniChar *thisChar);
static void		GetXView(Tcl_Interp *interp, const TkText *textPtr, int report);
static void		GetYView(Tcl_Interp *interp, TkText *textPtr, int report);
static unsigned		GetYPixelCount(TkText *textPtr, DLine *dlPtr);
static DLine *		LayoutDLine(const TkTextIndex *indexPtr, unsigned displayLineNo);
static int		UpdateOneLine(TkText *textPtr, TkTextLine *linePtr, TkTextIndex *indexPtr,
			    unsigned maxDispLines);
static int		MeasureUp(TkText *textPtr, const TkTextIndex *srcPtr, int distance,
			    TkTextIndex *dstPtr, int32_t *overlap);
static int		MeasureDown(TkText *textPtr, TkTextIndex *srcPtr, int distance,
			    int32_t *overlap, int saveDisplayLines);
static int		NextTabStop(unsigned tabWidth, int x, int tabOrigin);
static void		UpdateDisplayInfo(TkText *textPtr);
static void		YScrollByLines(TkText *textPtr, int offset);
static void		YScrollByPixels(TkText *textPtr, int offset);
static void		TextInvalidateRegion(TkText *textPtr, TkRegion region);
static void		TextInvalidateLineMetrics(TkText *textPtr, TkTextLine *linePtr,
			    unsigned lineCount, TkTextInvalidateAction action);
static int		CalculateDisplayLineHeight(TkText *textPtr, const TkTextIndex *indexPtr,
			    unsigned *byteCountPtr);
static TkTextDispChunk * DLineChunkOfX(TkText *textPtr, DLine *dlPtr, int x, TkTextIndex *indexPtr,
			    int *nearby);
static void		DLineIndexOfX(TkText *textPtr, TkTextDispChunk *chunkPtr, int x,
			    TkTextIndex *indexPtr);
static int		DLineXOfIndex(TkText *textPtr, DLine *dlPtr, unsigned byteIndex);
static ScrollMethod	TextGetScrollInfoObj(Tcl_Interp *interp, TkText *textPtr, int objc,
			    Tcl_Obj *const objv[], double *dblPtr, int *intPtr);
static void		InvokeAsyncUpdateLineMetrics(TkText *textPtr);
static void		InvokeAsyncUpdateYScrollbar(TkText *textPtr);
static void		AsyncUpdateYScrollbar(void *clientData);
static void		AsyncUpdateLineMetrics(void *clientData);
static void		UpdateLineMetrics(TkText *textPtr, unsigned doThisMuch);
static int		TestIfLinesUpToDate(const TkTextIndex *indexPtr);
static void		SaveDisplayLines(TkText *textPtr, DisplayInfo *info, int append);
static TkTextLine *	ComputeDisplayLineInfo(TkText *textPtr, const TkTextIndex *indexPtr,
			    DisplayInfo *info);
static void		ComputeMissingMetric(TkText *textPtr, DisplayInfo *info,
			    Threshold threshold, int offset);
static unsigned		GetPixelsTo(TkText *textPtr, const TkTextIndex *indexPtr,
			    int inclusiveLastLine, DisplayInfo *info);
static unsigned		FindDisplayLineOffset(TkText *textPtr, TkTextLine *linePtr, int32_t *distance);
static void		FindDisplayLineStartEnd(TkText *textPtr, TkTextIndex *indexPtr, int end,
			    int cacheType);
static void		CheckIfLineMetricIsUpToDate(TkText *textPtr);
static void		RunUpdateLineMetricsFinished(void *clientData);
static void		CheckLineMetricConsistency(const TkText *textPtr);
static int		ComputeBreakIndex(TkText *textPtr, const TkTextDispChunk *chunkPtr,
			    TkTextSegment *segPtr, int byteOffset, TkWrapMode wrapMode,
			    TkTextSpaceMode spaceMode);
static Tcl_Size	CharChunkMeasureChars(TkTextDispChunk *chunkPtr, const char *chars, int charsLen,
			    int start, int end, int startX, int maxX, TkTextSpaceMode spaceMode,
			    int flags, int *nextXPtr);
static void		CharDisplayProc(TkText *textPtr, TkTextDispChunk *chunkPtr, int x, int y,
			    int height, int baseline, Display *display, Drawable dst, int screenY);
static void		CharUndisplayProc(TkText *textPtr, TkTextDispChunk *chunkPtr);
static void		HyphenUndisplayProc(TkText *textPtr, TkTextDispChunk *chunkPtr);
static void		DisplayChars(TkText *textPtr, TkTextDispChunk *chunkPtr, int x, int y,
			    int baseline, Display *display, Drawable dst);
static Tcl_Size	CharMeasureProc(TkTextDispChunk *chunkPtr, int x);
static void		CharBboxProc(TkText *textPtr, TkTextDispChunk *chunkPtr, Tcl_Size index, int y,
			    int lineHeight, int baseline, int *xPtr, int *yPtr, int *widthPtr,
			    int *heightPtr);
static int		MeasureChars(Tk_Font tkfont, const char *source, Tcl_Size maxBytes, Tcl_Size rangeStart,
			    Tcl_Size rangeLength, int startX, int maxX, int flags, int *nextXPtr);
static CharInfo *	AllocCharInfo(TkText *textPtr);
static void		FreeCharInfo(TkText *textPtr, CharInfo *ciPtr);
#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
static int		IsSameFGStyle(TextStyle *style1, TextStyle *style2);
#endif /* TK_LAYOUT_WITH_BASE_CHUNKS */

static const TkTextDispChunkProcs layoutCharProcs = {
    TEXT_DISP_CHAR,		/* type */
    CharDisplayProc,		/* displayProc */
    CharUndisplayProc,		/* undisplayProc */
    CharMeasureProc,		/* measureProc */
    CharBboxProc,		/* bboxProc */
};

#define CHAR_CHUNK_GET_SEGMENT(chunkPtr) (((const CharInfo *) chunkPtr->clientData)->segPtr)

static const TkTextDispChunkProcs layoutHyphenProcs = {
    TEXT_DISP_HYPHEN,		/* type */
    CharDisplayProc,		/* displayProc */
    HyphenUndisplayProc,	/* undisplayProc */
    CharMeasureProc,		/* measureProc */
    CharBboxProc,		/* bboxProc */
};

static const TkTextDispChunkProcs layoutElideProcs = {
    TEXT_DISP_ELIDED,	/* type */
    NULL,		/* displayProc */
    NULL,		/* undisplayProc */
    ElideMeasureProc,	/* measureProc */
    ElideBboxProc,	/* bboxProc */
};

#ifndef NDEBUG
/*
 * The following counters keep statistics about redisplay that can be checked
 * to see how clever this code is at reducing redisplays.
 */

typedef struct Statistic {
    unsigned numRedisplays;	/* Number of calls to DisplayText. */
    unsigned linesRedrawn;	/* Number of calls to DisplayDLine. */
    unsigned numLayouted;	/* Number of calls to LayoutDLine. */
    unsigned numCopies;		/* Number of calls to XCopyArea to copy part of the screen. */
    unsigned lineHeightsRecalculated;
				/* Number of line layouts purely for height calculation purposes. */
    unsigned breakInfo;		/* Number of line break computations. */
    unsigned numCached;		/* Number of computed cached lines. */
    unsigned numHits;		/* Number of found cached lines. */
    unsigned numReused;		/* Number of re-used display lines. */

    int perfFuncIsHooked;
} Statistic;

static Statistic stats;

static void
PerfStatistic()
{
    if (!tkBTreeDebug) {
	return;
    }

    fprintf(stderr, "PERFORMANCE -------------------\n");
    fprintf(stderr, "Calls to DisplayText:    %6u\n", stats.numRedisplays);
    fprintf(stderr, "Calls to DisplayDLine:   %6u\n", stats.linesRedrawn);
    fprintf(stderr, "Calls to LayoutDLine:    %6u\n", stats.numLayouted);
    fprintf(stderr, "Calls to XCopyArea:      %6u\n", stats.numCopies);
    fprintf(stderr, "Re-used display lines:   %6u\n", stats.numReused);
    fprintf(stderr, "Cached display lines:    %6u\n", stats.numCached);
    fprintf(stderr, "Found in cache:          %6u\n", stats.numHits);
    fprintf(stderr, "Line metric calculation: %6u\n", stats.lineHeightsRecalculated);
    fprintf(stderr, "Break info computation:  %6u\n", stats.breakInfo);
}
#endif /* NDEBUG */

#ifdef TK_CHECK_ALLOCS

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

static unsigned tkTextCountNewStyle = 0;
static unsigned tkTextCountDestroyStyle = 0;
static unsigned tkTextCountNewChunk = 0;
static unsigned tkTextCountDestroyChunk = 0;
static unsigned tkTextCountNewSection = 0;
static unsigned tkTextCountDestroySection = 0;
static unsigned tkTextCountNewCharInfo = 0;
static unsigned tkTextCountDestroyCharInfo = 0;
static unsigned tkTextCountNewBreakInfo = 0;
static unsigned tkTextCountDestroyBreakInfo = 0;
static unsigned tkTextCountNewDLine = 0;
static unsigned tkTextCountDestroyDLine = 0;
static unsigned tkTextCountNewDispInfo = 0;
unsigned tkTextCountDestroyDispInfo = 0; /* referenced in tkTextBTree.c */
#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
unsigned tkTextCountNewBaseChars = 0;
unsigned tkTextCountDestroyBaseChars = 0;
#endif

extern unsigned tkRangeListCountNew;
extern unsigned tkRangeListCountDestroy;

static int hookStatFunc = 1;

static void
AllocStatistic()
{
    if (!tkBTreeDebug) {
	return;
    }

    fprintf(stderr, "--------------------------------\n");
    fprintf(stderr, "ALLOCATION:       new    destroy\n");
    fprintf(stderr, "--------------------------------\n");
    fprintf(stderr, "DLine:       %8u - %8u\n", tkTextCountNewDLine, tkTextCountDestroyDLine);
    fprintf(stderr, "Chunk:       %8u - %8u\n", tkTextCountNewChunk, tkTextCountDestroyChunk);
    fprintf(stderr, "Section:     %8u - %8u\n", tkTextCountNewSection, tkTextCountDestroySection);
    fprintf(stderr, "CharInfo:    %8u - %8u\n", tkTextCountNewCharInfo, tkTextCountDestroyCharInfo);
    fprintf(stderr, "DispInfo:    %8u - %8u\n", tkTextCountNewDispInfo, tkTextCountDestroyDispInfo);
    fprintf(stderr, "BreakInfo:   %8u - %8u\n", tkTextCountNewBreakInfo, tkTextCountDestroyBreakInfo);
#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
    fprintf(stderr, "BaseChars:   %8u - %8u\n", tkTextCountNewBaseChars, tkTextCountDestroyBaseChars);
#endif
    fprintf(stderr, "Style:       %8u - %8u\n", tkTextCountNewStyle, tkTextCountDestroyStyle);
    fprintf(stderr, "RangeList:   %8u - %8u\n", tkRangeListCountNew, tkRangeListCountDestroy);

    if (tkTextCountNewDLine != tkTextCountDestroyDLine
	    || tkTextCountNewChunk != tkTextCountDestroyChunk
	    || tkTextCountNewSection != tkTextCountDestroySection
	    || tkTextCountNewCharInfo != tkTextCountDestroyCharInfo
	    || tkTextCountNewDispInfo != tkTextCountDestroyDispInfo
#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
	    || tkTextCountNewBaseChars != tkTextCountDestroyBaseChars
#endif
	    || tkTextCountNewStyle != tkTextCountDestroyStyle
	    || tkRangeListCountNew != tkRangeListCountDestroy) {
	fprintf(stderr, "*** memory leak detected ***\n");
    }
}
#endif /* TK_CHECK_ALLOCS */

/*
 * Some helpers:
 */

static const char doNotBreakAtAll[8] = {
    LINEBREAK_NOBREAK, LINEBREAK_NOBREAK, LINEBREAK_NOBREAK, LINEBREAK_NOBREAK,
    LINEBREAK_NOBREAK, LINEBREAK_NOBREAK, LINEBREAK_NOBREAK, LINEBREAK_NOBREAK };

/* XRectangle is rectricted to 16 bit, so we need a private rectangle struct. */
typedef struct DRect {
    int x, y;
    int width, height;
} DRect;

static int RectIsEmpty(const XRectangle *rect) { return rect->width == 0 || rect->height == 0; }

static int
RectIntersects(
    const XRectangle *rect1,
    const DRect *rect2)
{
    return (int) rect1->x < rect2->x + rect2->width
	&& rect2->x < (int) rect1->x + (int) rect1->width
	&& (int) rect1->y < rect2->y + rect2->height
	&& rect2->y < (int) rect1->y + (int) rect1->height;
}

static int
RectContainsRect(
    const DRect *rect1,		/* this rectangle */
    const XRectangle *rect2)	/* contains this one? */
{
    return rect1->x <= (int) rect2->x
	&& (int) rect2->x + (int) rect2->width <= rect1->x + rect1->width
	&& rect1->y <= (int) rect2->y
	&& (int) rect2->y + (int) rect2->height <= rect1->y + rect1->height;
}

static int RegionIsEmpty(const DRegion *region) { return region->y1 >= region->y2; }

static void
RegionUnion(
    DRegion* region,
    int y1,
    int y2)
{
    if (RegionIsEmpty(region))
    {
	region->y1 = y1;
	region->y2 = y2;
    }
    else
    {
	region->y1 = MIN(region->y1, y1);
	region->y2 = MAX(region->y2, y2);
    }
}

static int
RegionIntersects(
    const DRegion* region,
    int y1,
    int y2)
{
    return y1 < region->y2 && region->y1 < y2;
}

static void ClearRegion(DRegion* region) { region->y1 = region->y2 = 0; }

static int IsPowerOf2(unsigned n) { return !(n & (n - 1)); }

static int IsBlank(int ch) { return ch == ' ' || ch == '\t'; }
static int IsDecimalPoint(int ch) { return ch == '.' || ch == ','; }

static unsigned
NextPowerOf2(uint32_t n)
{
    --n;
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    return ++n;
}

static int
IsExpandableSpace(
    const char *s)
{
    /* Normal space or non-break space? */
    return UCHAR(s[0]) == 0x20 || (UCHAR(s[0]) == 0xc2 && UCHAR(s[1]) == 0x0a);
}

static void
LogTextHeightCalc(
    TkText *textPtr,
    const TkTextIndex *indexPtr)
{
    char string[TK_POS_CHARS];

    assert(tkTextDebug);

    /*
     * Debugging is enabled, so keep a log of all the lines whose
     * height was recalculated. The test suite uses this information.
     */

    TkrTextPrintIndex(textPtr, indexPtr, string);
    LOG("tk_textHeightCalc", string);
}

static void
LogTextRelayout(
    TkText *textPtr,
    const TkTextIndex *indexPtr)
{
    char string[TK_POS_CHARS];

    assert(tkTextDebug);

    /*
     * Debugging is enabled, so keep a log of all the lines that
     * were re-layed out. The test suite uses this information.
     */

    TkrTextPrintIndex(textPtr, indexPtr, string);
    LOG("tk_textRelayout", string);
}

static void
LogTextInvalidateLine(
    TkText *textPtr,
    unsigned count)
{
    char buffer[4*TCL_INTEGER_SPACE + 3];
    const TkRangeList *ranges = textPtr->dInfoPtr->lineMetricUpdateRanges;
    unsigned totalCount = TkRangeListCount(ranges) - count;
    unsigned totalLines = TkrBTreeNumLines(textPtr->sharedTextPtr->tree, textPtr);
    int lineNum = TkRangeListIsEmpty(ranges) ? -1 : TkRangeListLow(ranges);

    assert(tkTextDebug);

    snprintf(buffer, sizeof(buffer), "%d %u - %u %u", lineNum, totalLines, count, totalCount);
    LOG("tk_textInvalidateLine", buffer);
}

static void
DisplayTextWhenIdle(
    TkText *textPtr)
{
    if (textPtr->sharedTextPtr->allowUpdateLineMetrics && !(textPtr->dInfoPtr->flags & REDRAW_PENDING)) {
	textPtr->dInfoPtr->flags |= REDRAW_PENDING;
	Tcl_DoWhenIdle(DisplayText, textPtr);
    }
}

static int
GetLeftLineMargin(
    const DLine *dlPtr,
    const StyleValues *sValuePtr)
{
    assert(dlPtr);
    assert(sValuePtr);
    return (dlPtr->flags & PARAGRAPH_START) ? sValuePtr->lMargin1 : sValuePtr->lMargin2;
}

#if SPEEDUP_MONOSPACED_LINE_HEIGHTS

static int
TestMonospacedLineHeights(
    const TkText *textPtr)
{
    return textPtr->wrapMode == TEXT_WRAPMODE_NONE
	    && textPtr->dInfoPtr->countImages == 0
	    && textPtr->dInfoPtr->countWindows == 0
	    && TkTextTagSetDisjunctiveBits(TkBTreeRootTagInfo(textPtr->sharedTextPtr->tree),
		textPtr->sharedTextPtr->affectLineHeightTags);
    return 0;
}

#endif /* SPEEDUP_MONOSPACED_LINE_HEIGHTS */

static int
UseMonospacedLineHeights(
    const TkText *textPtr)
{
#if SPEEDUP_MONOSPACED_LINE_HEIGHTS
    return TestMonospacedLineHeights(textPtr)
	    && TkRangeListIsEmpty(textPtr->dInfoPtr->lineMetricUpdateRanges);
#else
    (void)textPtr;
    return 0;
#endif
}

/*
 * Some helpers for hyphenation support (Latin-1 only):
 */

static const unsigned char isVowel[256] = {
#define _ 0
/*  00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 00 - 0f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 10 - 1f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 20 - 2f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 30 - 3f */
    _, 1, _, _, _, 1, _, _, _, 1, _, _, _, _, _, 1, /* 40 - 4f */
    _, _, _, _, _, 1, _, _, _, _, _, _, _, _, _, _, /* 50 - 5f */
    _, 1, _, _, _, 1, _, _, _, 1, _, _, _, _, _, 1, /* 60 - 6f */
    _, _, _, _, _, 1, _, _, _, _, _, _, _, _, _, _, /* 70 - 7f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 80 - 8f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 90 - 9f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* a0 - af */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* b0 - bf */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* c0 - cf */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* d0 - df */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* e0 - ef */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* f0 - ff */
/*  00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */
#undef _
};

static const unsigned char isConsonant[256] = {
#define _ 0
/*  00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 00 - 0f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 10 - 1f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 20 - 2f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 30 - 3f */
    _, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, /* 40 - 4f */
    1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, _, _, _, _, _, /* 50 - 5f */
    _, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, /* 60 - 6f */
    1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, _, _, _, _, _, /* 70 - 7f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 80 - 8f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 90 - 9f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* a0 - af */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* b0 - bf */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* c0 - cf */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* d0 - df */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* e0 - ef */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* f0 - ff */
/*  00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */
#undef _
};

static const unsigned char isUmlaut[256] = {
#define _ 0
/*  00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 00 - 0f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 10 - 1f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 20 - 2f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 30 - 3f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 40 - 4f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 50 - 5f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 60 - 6f */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* 70 - 7f */
    _, _, _, _, 1, _, _, _, _, _, _, 1, _, _, _, _, /* 80 - 8f */
    _, _, _, _, _, _, 1, _, _, _, _, _, 1, _, _, _, /* 90 - 9f */
    _, _, _, _, 1, _, _, _, _, _, _, 1, _, _, _, _, /* a0 - af */
    _, _, _, _, _, _, 1, _, _, _, _, _, 1, _, _, _, /* b0 - bf */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* c0 - cf */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* d0 - df */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* e0 - ef */
    _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, /* f0 - ff */
/*  00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */
#undef _
};

static const unsigned char umlautToVowel[256] = {
#define ___ 0
/*   00   01   02   03   04   05   06   07   08   09   0a   0b   0c   0d   0e   0f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 00 - 0f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 10 - 1f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 20 - 2f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 30 - 3f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 40 - 4f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 50 - 5f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 60 - 6f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 70 - 7f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 80 - 8f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* 90 - 9f */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* a0 - af */
    ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, /* b0 - bf */
    ___, ___, ___, ___, 'A', ___, ___, ___, ___, ___, ___, 'E', ___, ___, ___, ___, /* c0 - cf */
    ___, ___, ___, ___, ___, ___, 'O', ___, ___, ___, ___, ___, 'U', ___, ___, ___, /* d0 - df */
    ___, ___, ___, ___, 'a', ___, ___, ___, ___, ___, ___, 'e', ___, ___, ___, ___, /* e0 - ef */
    ___, ___, ___, ___, ___, ___, 'o', ___, ___, ___, ___, ___, 'u', ___, ___, ___, /* f0 - ff */
/*   00   01   02   03   04   05   06   07   08   09   0a   0b   0c   0d   0e   0f */
#undef ___
};

static int IsVowel(unsigned char c)     { return isVowel[c]; }
static int IsUmlaut(unsigned char c)    { return umlautToVowel[c] != 0; }
static int IsConsonant(unsigned char c) { return isConsonant[c]; }

static unsigned char UmlautToVowel(unsigned char c) { return umlautToVowel[c]; }
static unsigned char ConvertC3Next(unsigned char c) { return 0xc0 | (c - 0x80); }

static int
IsUmlautOrVowel(const char *s)
{
    return UCHAR(s[0]) == 0xc3 ? isUmlaut[UCHAR(s[1])] : UCHAR(s[0]) < 0x80 && isVowel[UCHAR(s[0])];
}

static void
SetupHyphenChars(
    TkTextSegment *segPtr,
    unsigned offset)
{
    assert(offset <= 2); /* don't exceed 5 characters */

    /*
     * NOTE: U+2010 (HYPHEN) always has a visible rendition, but U+00AD
     * (SOFT HYPHEN) is an invisible format character (per definition).
     * And don't use '-' (U+002D = HYPHEN-MINUS), because the meaning of
     * this character is contextual. So we have to use U+2010.
     */

    assert(segPtr->typePtr->group == SEG_GROUP_HYPHEN);
    assert(sizeof(doNotBreakAtAll) >= 6); /* we need this break array for hyphens */

    memcpy(segPtr->body.chars + offset, HYPHEN_STRING, HYPHEN_LENGTH + 1);
    segPtr->body.hyphen.textSize = HYPHEN_LENGTH + offset;
}

static int
IsDoubleDigraph(
    char c1,
    char c2)
{
    switch (c1) {
	case 'c': /* fallthru */	/* c-cs -> cs-cs */
	case 'z': return c2 == 's';	/* z-zs -> zs-zs */
	case 'g': /* fallthru */	/* g-gy -> gy-gy */
	case 'l': /* fallthru */	/* l-ly -> ly-ly */
	case 'n': /* fallthru */	/* n-ny -> ny-ny */
	case 't': return c2 == 'y';	/* t-ty -> ty-ty */
	case 's': return c2 == 'z';	/* s-sz -> sz-sz */
    }
    return 0;
}

static int
IsHyphenChunk(
    const TkTextDispChunk *chunkPtr)
{
    assert(chunkPtr);
    return chunkPtr->layoutProcs && chunkPtr->layoutProcs->type == TEXT_DISP_HYPHEN;
}

static int
IsCharChunk(
    const TkTextDispChunk *chunkPtr)
{
    assert(chunkPtr);
    return chunkPtr->layoutProcs && chunkPtr->layoutProcs->type == TEXT_DISP_CHAR;
}

static char
GetLastCharInChunk(
    const TkTextDispChunk *chunkPtr)
{
    const CharInfo *ciPtr;

    if (!chunkPtr) {
	return '\0';
    }

    assert(chunkPtr->layoutProcs);
    assert(chunkPtr->clientData);

    if (!IsCharChunk(chunkPtr)) {
	return '\0';
    }

    ciPtr = (const CharInfo *)chunkPtr->clientData;
    assert(ciPtr->numBytes > 0);
    return ciPtr->u.chars[ciPtr->baseOffset + ciPtr->numBytes - 1];
}

static char
GetSecondLastCharInChunk(
    const TkTextDispChunk *chunkPtr)
{
    const CharInfo *ciPtr;

    if (!chunkPtr || !IsCharChunk(chunkPtr)) {
	return '\0';
    }

    ciPtr = (const CharInfo *)chunkPtr->clientData;
    assert(chunkPtr->clientData);
    assert(ciPtr->numBytes > 0);

    if (ciPtr->numBytes > 1) {
	return ciPtr->u.chars[ciPtr->baseOffset + ciPtr->numBytes - 2];
    }
    if ((chunkPtr = chunkPtr->prevCharChunkPtr) && IsCharChunk(chunkPtr)) {
	ciPtr = (const CharInfo *)chunkPtr->clientData;
	assert(ciPtr->numBytes > 0);
	return ciPtr->u.chars[ciPtr->baseOffset + ciPtr->numBytes - 1];
    }

    return '\0';
}

static int
FilterHyphenRules(
    int hyphenRules,
    const char *lang)
{
    if (lang && hyphenRules) {
	enum {
	    CA_RULES = (1 << TK_TEXT_HYPHEN_GEMINATION),
	    DE_RULES = (1 << TK_TEXT_HYPHEN_CK)|(1 << TK_TEXT_HYPHEN_TRIPLE_CONSONANT),
	    HU_RULES = (1 << TK_TEXT_HYPHEN_DOUBLE_DIGRAPH),
	    NL_RULES = (1 << TK_TEXT_HYPHEN_DOUBLE_VOWEL)|(1 << TK_TEXT_HYPHEN_TREMA),
	    NO_RULES = (1 << TK_TEXT_HYPHEN_TRIPLE_CONSONANT),
	    PL_RULES = (1 << TK_TEXT_HYPHEN_REPEAT),
	    SV_RULES = (1 << TK_TEXT_HYPHEN_TRIPLE_CONSONANT)
	};

	switch (lang[0]) {
	case 'c': if (lang[1] == 'a') { hyphenRules &= CA_RULES; }; break;
	case 'd': if (lang[1] == 'e') { hyphenRules &= DE_RULES; }; break;
	case 'h': if (lang[1] == 'u') { hyphenRules &= HU_RULES; }; break;
	case 'p': if (lang[1] == 'l') { hyphenRules &= PL_RULES; }; break;
	case 's': if (lang[1] == 'v') { hyphenRules &= SV_RULES; }; break;
	case 'n':
	    switch (lang[1]) {
	    case 'b': /* fallthru */
	    case 'n': /* fallthru */
	    case 'o': hyphenRules &= NO_RULES; break;
	    case 'l': hyphenRules &= NL_RULES; break;
	    }
	    break;
	}
    }

    return hyphenRules;
}

/*
 *--------------------------------------------------------------
 *
 * TkTextPendingSync --
 *
 *	This function checks if any line heights are not up-to-date.
 *
 * Results:
 *	Returns boolean 'true' if it is the case, or 'false' if all line
 *      heights are up-to-date.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

int
TkTextPendingSync(
    const TkText *textPtr)	/* Information about text widget. */
{
    /*
     * NOTE: We cannot use
     *
     *    !TkRangeListIsEmpty(textPtr->dInfoPtr->lineMetricUpdateRanges)
     *
     * because this statement does not guarantee that TkTextRunAfterSyncCmd has
     * been triggered, and we need the state after triggering.
     */

    return !!(textPtr->dInfoPtr->flags & (ASYNC_UPDATE|ASYNC_PENDING));
}

/*
 *--------------------------------------------------------------
 *
 * TestIfLinesUpToDate --
 *
 *	This function checks whether the lines up to given index
 *	position (inclusive) is up-to-date.
 *
 * Results:
 *	Returns boolean 'true' if it is the case, or 'false' if these
 *      line heights aren't up-to-date.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
TestIfLinesUpToDate(
    const TkTextIndex *indexPtr)	/* last line of range (inclusive) */
{
    const TkRangeList *ranges;

    assert(indexPtr->textPtr);

    ranges = indexPtr->textPtr->dInfoPtr->lineMetricUpdateRanges;

    if (TkRangeListIsEmpty(ranges)) {
	return 1;
    }

    return (int) TkTextIndexGetLineNumber(indexPtr, indexPtr->textPtr) < TkRangeListLow(ranges);
}

/*
 *----------------------------------------------------------------------
 *
 * InvokeAsyncUpdateYScrollbar --
 *
 *	This function invokes the update of the vertical scrollbar.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
InvokeAsyncUpdateYScrollbar(
    TkText *textPtr)
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    assert(!dInfoPtr->scrollbarTimer);
    textPtr->refCount += 1;

    if (textPtr->syncTime == 0) {
	AsyncUpdateYScrollbar(textPtr);
    } else {
	dInfoPtr->scrollbarTimer = Tcl_CreateTimerHandler(textPtr->syncTime,
		AsyncUpdateYScrollbar, textPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * InvokeAsyncUpdateLineMetrics --
 *
 *	This function invokes the update of the line metric calculation.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
InvokeAsyncUpdateLineMetrics(
    TkText *textPtr)
{
    assert(textPtr->sharedTextPtr->allowUpdateLineMetrics);

    if (textPtr->syncTime > 0) {
	TextDInfo *dInfoPtr = textPtr->dInfoPtr;

	if (!dInfoPtr->lineUpdateTimer) {
	    textPtr->refCount += 1;
	    dInfoPtr->lineUpdateTimer = Tcl_CreateTimerHandler(1, AsyncUpdateLineMetrics, textPtr);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextCreateDInfo --
 *
 *	This function is called when a new text widget is created. Its job is
 *	to set up display-related information for the widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A TextDInfo data structure is allocated and initialized and attached
 *	to textPtr.
 *
 *----------------------------------------------------------------------
 */

static void
SetupEolSegment(
    TkText *textPtr,
    TextDInfo *dInfoPtr)
{
    char eolChar[10];
    Tcl_UniChar uc;
    const char *p = textPtr->eolCharPtr ? Tcl_GetString(textPtr->eolCharPtr) : NULL;
    int len;

    if (!p || !*p) {
	p = "\xc2\xb6"; /* U+00B6 = PILCROW SIGN */
    }
    len = Tcl_UtfToUniChar(p, &uc);
    strcpy(eolChar, p);
    strcpy(eolChar + len, "\n");
    if (dInfoPtr->endOfLineSegPtr) {
	TkBTreeFreeSegment(dInfoPtr->endOfLineSegPtr);
    }
    dInfoPtr->endOfLineSegPtr = TkBTreeMakeCharSegment(
	    eolChar, len + 1, textPtr->sharedTextPtr->emptyTagInfoPtr);
}

static void
SetupEotSegment(
    TkText *textPtr,
    TextDInfo *dInfoPtr)
{
    char eotChar[10];
    Tcl_UniChar uc;
    const char *p = textPtr->eotCharPtr ? Tcl_GetString(textPtr->eotCharPtr) : NULL;
    int len;

    if (!p || !*p) {
	if (textPtr->eolCharPtr) {
	    p = Tcl_GetString(textPtr->eolCharPtr);
	}
	if (!p || !*p) {
	    p = "\xc2\xb6"; /* U+00B6 = PILCROW SIGN */
	}
    }
    len = Tcl_UtfToUniChar(p, &uc);
    strcpy(eotChar, p);
    strcpy(eotChar + len, "\n");
    if (dInfoPtr->endOfTextSegPtr) {
	TkBTreeFreeSegment(dInfoPtr->endOfTextSegPtr);
    }
    dInfoPtr->endOfTextSegPtr = TkBTreeMakeCharSegment(
	    eotChar, len + 1, textPtr->sharedTextPtr->emptyTagInfoPtr);
}

void
TkTextCreateDInfo(
    TkText *textPtr)	/* Overall information for text widget. */
{
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    TkTextBTree tree = sharedTextPtr->tree;
    TextDInfo *dInfoPtr;
    XGCValues gcValues;
    int isMonospaced;

    dInfoPtr = (TextDInfo *)ckalloc(sizeof(TextDInfo));
    memset(dInfoPtr, 0, sizeof(TextDInfo));
    Tcl_InitHashTable(&dInfoPtr->styleTable, sizeof(StyleValues)/sizeof(int));
    gcValues.graphics_exposures = True;
    dInfoPtr->copyGC = NULL;
    dInfoPtr->scrollGC = Tk_GetGC(textPtr->tkwin, GCGraphicsExposures, &gcValues);
    dInfoPtr->insertFgGC = NULL;
    dInfoPtr->xScrollFirst = -1;
    dInfoPtr->xScrollLast = -1;
    dInfoPtr->yScrollFirst = -1;
    dInfoPtr->yScrollLast = -1;
    dInfoPtr->topLineNo = -1;
    dInfoPtr->topByteIndex = -1;
    dInfoPtr->flags = DINFO_OUT_OF_DATE;
    dInfoPtr->lineMetricUpdateRanges = TkRangeListCreate(64);
    dInfoPtr->firstLineNo = TkBTreeLinesTo(tree, NULL, TkBTreeGetStartLine(textPtr), NULL);
    dInfoPtr->lastLineNo = TkBTreeLinesTo(tree, NULL, TkBTreeGetLastLine(textPtr), NULL);
    dInfoPtr->lineMetricUpdateEpoch = 1;
    dInfoPtr->strBufferSize = 512;
    dInfoPtr->strBuffer = (char *)ckalloc(dInfoPtr->strBufferSize);
    ClearRegion(&dInfoPtr->invalidRegion);
    TkTextIndexClear(&dInfoPtr->metricIndex, textPtr);
    TkTextIndexClear(&dInfoPtr->currChunkIndex, textPtr);
    SetupEolSegment(textPtr, dInfoPtr);
    SetupEotSegment(textPtr, dInfoPtr);

    if (textPtr->state == TK_TEXT_STATE_NORMAL
	    && textPtr->blockCursorType
	    && textPtr->showInsertFgColor) {
	XGCValues gcValues1;
	gcValues.foreground = textPtr->insertFgColor->pixel;
	dInfoPtr->insertFgGC = Tk_GetGC(textPtr->tkwin, GCForeground, &gcValues1);
    }

    /*
     * Note: Setup of defaultStyle must be postponed.
     */

    textPtr->dInfoPtr = dInfoPtr;
    isMonospaced = UseMonospacedLineHeights(textPtr);

    if (isMonospaced) {
	TkBTreeUpdatePixelHeights(textPtr, TkBTreeGetStartLine(textPtr), 1,
		dInfoPtr->lineMetricUpdateEpoch);
    } else {
	dInfoPtr->lineMetricUpdateRanges = TkRangeListAdd(dInfoPtr->lineMetricUpdateRanges, 0, 0);
    }

    if (!sharedTextPtr->breakInfoTableIsInitialized) {
	Tcl_InitHashTable(&sharedTextPtr->breakInfoTable, TCL_ONE_WORD_KEYS);
	sharedTextPtr->breakInfoTableIsInitialized = 1;
    }

    if (sharedTextPtr->allowUpdateLineMetrics) {
	if (!isMonospaced) {
	    InvokeAsyncUpdateLineMetrics(textPtr);
	}
	InvokeAsyncUpdateYScrollbar(textPtr);
    }

#ifdef TK_CHECK_ALLOCS
    if (hookStatFunc) {
	atexit(AllocStatistic);
	hookStatFunc = 0;
    }
#endif
#ifndef NDEBUG
    if (!stats.perfFuncIsHooked) {
#ifndef _MSC_VER	/* MSVC erroneously triggers warning warning C4113 */
	atexit(PerfStatistic);
#endif
	stats.perfFuncIsHooked = 1;
    }
#endif
}
/*
 *----------------------------------------------------------------------
 *
 * TkTextDeleteBreakInfoTableEntries --
 *
 *	Delete all cached break information. Normally this table will
 *	be empty when this function is called, but under some specific
 *	conditions the given table will not be empty - this will only
 *	happen if a tag redraw action has been interrupted, and this
 *	will be seldom the case.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Some resources might be freed.
 *
 *----------------------------------------------------------------------
 */

void
TkTextDeleteBreakInfoTableEntries(
    Tcl_HashTable *breakInfoTable)
{
    Tcl_HashSearch search;
    Tcl_HashEntry *hPtr;

    assert(breakInfoTable);

    for (hPtr = Tcl_FirstHashEntry(breakInfoTable, &search); hPtr; hPtr = Tcl_NextHashEntry(&search)) {
	TkTextBreakInfo *breakInfo = (TkTextBreakInfo *)Tcl_GetHashValue(hPtr);

	assert(breakInfo->brks);
	DEBUG(memset(breakInfo->brks, 0xff, breakInfo->brksSize));
	ckfree(breakInfo->brks);
	ckfree(breakInfo);
	DEBUG_ALLOC(tkTextCountDestroyBreakInfo++);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextFreeDInfo --
 *
 *	This function is called to free up all of the private display
 *	information kept by this file for a text widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Lots of resources get freed.
 *
 *----------------------------------------------------------------------
 */

void
TkTextFreeDInfo(
    TkText *textPtr)		/* Overall information for text widget. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    TkTextDispChunk *chunkPtr;
    TkTextDispChunkSection *sectionPtr;
    DLine *dlPtr;
    CharInfo *ciPtr;

    /*
     * Cancel pending events.
     */

    if (dInfoPtr->pendingUpdateLineMetricsFinished) {
	Tcl_CancelIdleCall(RunUpdateLineMetricsFinished, textPtr);
    }
    if (dInfoPtr->flags & REDRAW_PENDING) {
	Tcl_CancelIdleCall(DisplayText, textPtr);
    }

    /*
     * Be careful to free up styleTable *after* freeing up all the DLines, so
     * that the hash table is still intact to free up the style-related
     * information from the lines. Once the lines are all free then styleTable
     * will be empty.
     */

    FreeDLines(textPtr, dInfoPtr->dLinePtr, NULL, DLINE_UNLINK);
    FreeDLines(textPtr, dInfoPtr->savedDLinePtr, NULL, DLINE_FREE_TEMP);
    FreeDLines(textPtr, NULL, NULL, DLINE_CACHE);  /* release cached lines */
    FreeDLines(textPtr, NULL, NULL, DLINE_METRIC); /* release cached lines */

    if (dInfoPtr->copyGC != NULL) {
	Tk_FreeGC(textPtr->display, dInfoPtr->copyGC);
    }
    Tk_FreeGC(textPtr->display, dInfoPtr->scrollGC);
    if (dInfoPtr->insertFgGC != NULL) {
	Tk_FreeGC(textPtr->display, dInfoPtr->insertFgGC);
    }
    if (dInfoPtr->lineUpdateTimer) {
	Tcl_DeleteTimerHandler(dInfoPtr->lineUpdateTimer);
	textPtr->refCount -= 1;
	dInfoPtr->lineUpdateTimer = NULL;
    }
    if (dInfoPtr->scrollbarTimer) {
	Tcl_DeleteTimerHandler(dInfoPtr->scrollbarTimer);
	textPtr->refCount -= 1;
	dInfoPtr->scrollbarTimer = NULL;
    }
    if (dInfoPtr->repickTimer) {
	Tcl_DeleteTimerHandler(dInfoPtr->repickTimer);
	textPtr->refCount -= 1;
	dInfoPtr->repickTimer = NULL;
    }
    ciPtr = dInfoPtr->charInfoPoolPtr;
    while (ciPtr) {
	CharInfo *nextPtr = ciPtr->u.next;
	ckfree(ciPtr);
	DEBUG_ALLOC(tkTextCountDestroyCharInfo++);
	ciPtr = nextPtr;
    }
    sectionPtr = dInfoPtr->sectionPoolPtr;
    while (sectionPtr) {
	TkTextDispChunkSection *nextPtr = sectionPtr->nextPtr;
	ckfree(sectionPtr);
	DEBUG_ALLOC(tkTextCountDestroySection++);
	sectionPtr = nextPtr;
    }
    chunkPtr = dInfoPtr->chunkPoolPtr;
    while (chunkPtr) {
	TkTextDispChunk *nextPtr = chunkPtr->nextPtr;
	ckfree(chunkPtr);
	DEBUG_ALLOC(tkTextCountDestroyChunk++);
	chunkPtr = nextPtr;
    }
    dlPtr = dInfoPtr->dLinePoolPtr;
    while (dlPtr) {
	DLine *nextPtr = dlPtr->nextPtr;
	ckfree(dlPtr);
	DEBUG_ALLOC(tkTextCountDestroyDLine++);
	dlPtr = nextPtr;
    }
    if (dInfoPtr->defaultStyle) {
#if 0
	/*
	 * TODO: The following assertion sometimes fails. Luckily it doesn't matter,
	 * because it will be freed anyway, but why can it fail (and only sometimes)?
	 */
	 DEBUG_ALLOC(assert(dInfoPtr->defaultStyle->refCount == 1));
#endif
	FreeStyle(textPtr, dInfoPtr->defaultStyle);
    }
    Tcl_DeleteHashTable(&dInfoPtr->styleTable);
    TkRangeListDestroy(&dInfoPtr->lineMetricUpdateRanges);
    TkBTreeFreeSegment(dInfoPtr->endOfLineSegPtr);
    TkBTreeFreeSegment(dInfoPtr->endOfTextSegPtr);
    ckfree(dInfoPtr->strBuffer);
    ckfree(dInfoPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextResetDInfo --
 *
 *	This function will be called when the whole text has been deleted.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Line metrics will be updated.
 *
 *----------------------------------------------------------------------
 */

void
TkTextResetDInfo(
    TkText *textPtr)	/* Overall information for text widget. */
{
    TextDInfo *dInfoPtr;
    TkSharedText *sharedTextPtr;
    TkTextIndex index1, index2;
    unsigned lineNo1, lineNo2;

    if (UseMonospacedLineHeights(textPtr)) {
	return; /* already synchronized */
    }

    dInfoPtr = textPtr->dInfoPtr;
    sharedTextPtr = textPtr->sharedTextPtr;

    TkTextIndexSetupToStartOfText(&index1, textPtr, sharedTextPtr->tree);
    TkTextIndexSetupToEndOfText(&index2, textPtr, sharedTextPtr->tree);
    TkrTextChanged(sharedTextPtr, NULL, &index1, &index2);

    lineNo1 = TkBTreeLinesTo(sharedTextPtr->tree, textPtr, TkTextIndexGetLine(&index1), NULL);
    lineNo2 = TkBTreeLinesTo(sharedTextPtr->tree, textPtr, TkTextIndexGetLine(&index2), NULL);

    assert(lineNo1 < lineNo2);

    TkRangeListClear(dInfoPtr->lineMetricUpdateRanges);
    dInfoPtr->lineMetricUpdateRanges =
	    TkRangeListAdd(dInfoPtr->lineMetricUpdateRanges, lineNo1, lineNo2 - 1);
    dInfoPtr->lineMetricUpdateEpoch = 1;
    dInfoPtr->topLineNo = -1;
    dInfoPtr->topByteIndex = -1;

    if (textPtr->sharedTextPtr->allowUpdateLineMetrics) {
	TkTextUpdateLineMetrics(textPtr, lineNo1, lineNo2);
    }

    FreeDLines(textPtr, NULL, NULL, DLINE_CACHE);  /* release cached lines */
    FreeDLines(textPtr, NULL, NULL, DLINE_METRIC); /* release cached lines */
}

/*
 *----------------------------------------------------------------------
 *
 * GetStyle --
 *
 *	This function creates all the information needed to display text at a
 *	particular location. We know that the given chain of tags is sorted
 *	in ascending order.
 *
 * Results:
 *	The return value is a pointer to a TextStyle structure that
 *	corresponds to *sValuePtr.
 *
 * Side effects:
 *	A new entry may be created in the style table for the widget.
 *
 *----------------------------------------------------------------------
 */

static int
FillStyle(
    const TkTextTag *tagPtr,
    StyleValues *stylePtr,
    int haveFocus,
    int containsSelection)
{
    int selBorderPrio = -1;

    Tk_3DBorder border = tagPtr->attrs.border;
    XColor *fgColor    = tagPtr->attrs.fgColor;

    if (!haveFocus) {
	if (tagPtr->attrs.inactiveBorder)  { border = tagPtr->attrs.inactiveBorder; }
	if (tagPtr->attrs.inactiveFgColor) { fgColor = tagPtr->attrs.inactiveFgColor; }
    }

    if (containsSelection) {
	if (tagPtr->selBorder) {
	    border = tagPtr->selBorder;
	    if (haveFocus) {
		selBorderPrio = tagPtr->priority;
	    }
	}
	if (tagPtr->selFgColor) {
	    fgColor = tagPtr->selFgColor;
	}
	if (!haveFocus) {
	    if (tagPtr->inactiveSelBorder) {
		border = tagPtr->inactiveSelBorder;
		selBorderPrio = tagPtr->priority;
	    }
	    if (tagPtr->inactiveSelFgColor) {
		fgColor = tagPtr->inactiveSelFgColor;
	    }
	}
    }

    if (border)                         { stylePtr->border = border; }
    if (fgColor != NULL)                { stylePtr->fgColor = fgColor; }
    if (tagPtr->relief != TK_RELIEF_NULL) { stylePtr->relief = tagPtr->relief; }
    if (tagPtr->bgStipple != None)      { stylePtr->bgStipple = tagPtr->bgStipple; }
    if (tagPtr->indentBg >= 0)          { stylePtr->indentBg = tagPtr->indentBg; }
    if (tagPtr->tkfont != NULL)         { stylePtr->tkfont = tagPtr->tkfont; }
    if (tagPtr->fgStipple != None)      { stylePtr->fgStipple = tagPtr->fgStipple; }
    if (tagPtr->justify != TK_TEXT_JUSTIFY_NULL) { stylePtr->justify = tagPtr->justify; }
    if (tagPtr->lMargin1Obj)            { stylePtr->lMargin1 = tagPtr->lMargin1; }
    if (tagPtr->lMargin2Obj)            { stylePtr->lMargin2 = tagPtr->lMargin2; }
    if (tagPtr->lMarginColor)           { stylePtr->lMarginColor = tagPtr->lMarginColor; }
    if (tagPtr->offsetObj)              { stylePtr->offset = tagPtr->offset; }
    if (tagPtr->rMarginObj)             { stylePtr->rMargin = tagPtr->rMargin; }
    if (tagPtr->rMarginColor)           { stylePtr->rMarginColor = tagPtr->rMarginColor; }
    if (tagPtr->spacing1Obj)            { stylePtr->spacing1 = tagPtr->spacing1; }
    if (tagPtr->spacing2Obj)            { stylePtr->spacing2 = tagPtr->spacing2; }
    if (tagPtr->spacing3Obj)            { stylePtr->spacing3 = tagPtr->spacing3; }
    if (tagPtr->tabStringPtr)           { stylePtr->tabArrayPtr = tagPtr->tabArrayPtr; }
    if (tagPtr->eolColor)               { stylePtr->eolColor = tagPtr->eolColor; }
    if (tagPtr->hyphenColor)            { stylePtr->hyphenColor = tagPtr->hyphenColor; }
    if (tagPtr->elide >= 0)             { stylePtr->elide = tagPtr->elide; }
    if (tagPtr->langPtr)                { stylePtr->lang = tagPtr->lang; }
    if (tagPtr->hyphenRulesPtr)         { stylePtr->hyphenRules = tagPtr->hyphenRules; }

    if (tagPtr->tabStyle == TK_TEXT_TABSTYLE_TABULAR
	    || tagPtr->tabStyle == TK_TEXT_TABSTYLE_WORDPROCESSOR) { stylePtr->tabStyle = tagPtr->tabStyle; }
    if (tagPtr->wrapMode == TEXT_WRAPMODE_CHAR
	    || tagPtr->wrapMode == TEXT_WRAPMODE_NONE
		|| tagPtr->wrapMode == TEXT_WRAPMODE_WORD
		|| tagPtr->wrapMode == TEXT_WRAPMODE_CODEPOINT)    { stylePtr->wrapMode = tagPtr->wrapMode; }

    if (tagPtr->attrs.borderWidthObj && Tcl_GetString(tagPtr->attrs.borderWidthObj)[0] != '\0') {
	stylePtr->borderWidth = tagPtr->attrs.borderWidth;
    }

    if (tagPtr->overstrike >= 0) {
	stylePtr->overstrike = tagPtr->overstrike;
	if (tagPtr->overstrikeColor != NULL) {
	     stylePtr->overstrikeColor = tagPtr->overstrikeColor;
	} else if (tagPtr->attrs.fgColor != NULL) {
	     stylePtr->overstrikeColor = tagPtr->attrs.fgColor;
	}
    }

    if (tagPtr->underline >= 0) {
	stylePtr->underline = tagPtr->underline;
	if (tagPtr->underlineColor != NULL) {
	    stylePtr->underlineColor = tagPtr->underlineColor;
	} else if (tagPtr->attrs.fgColor != NULL) {
	    stylePtr->underlineColor = tagPtr->attrs.fgColor;
	}
    }

    return selBorderPrio;
}

static TextStyle *
MakeStyle(
    const TkText *textPtr,
    TkTextTag *tagPtr,
    int containsSelection)
{
    StyleValues styleValues;
    TextStyle *stylePtr;
    Tcl_HashEntry *hPtr;
    XGCValues gcValues;
    unsigned long mask;
    int borderPrio;
    int haveFocus;
    int isNew;

    /*
     * Find out what tags are present for the character, then compute a
     * StyleValues structure corresponding to those tags (scan through all of
     * the tags, saving information for the highest-priority tag).
     */

    memset(&styleValues, 0, sizeof(StyleValues));
    styleValues.relief = TK_RELIEF_FLAT;
    styleValues.fgColor = NULL;
    styleValues.underlineColor = textPtr->fgColor;
    styleValues.overstrikeColor = textPtr->fgColor;
    styleValues.eolColor = textPtr->eolColor;
    styleValues.eotColor = textPtr->eotColor ? textPtr->eotColor : textPtr->eolColor;
    styleValues.hyphenColor = textPtr->hyphenColor;
    styleValues.tkfont = textPtr->tkfont;
    styleValues.justify = textPtr->justify;
    styleValues.spacing1 = textPtr->spacing1;
    styleValues.spacing2 = textPtr->spacing2;
    styleValues.spacing3 = textPtr->spacing3;
    styleValues.tabArrayPtr = textPtr->tabArrayPtr;
    styleValues.tabStyle = textPtr->tabStyle;
    styleValues.wrapMode = textPtr->wrapMode;
    styleValues.lang = textPtr->lang;
    styleValues.hyphenRules = textPtr->hyphenRules;

    haveFocus = !!(textPtr->flags & GOT_FOCUS);
    borderPrio = -1;

    for ( ; tagPtr; tagPtr = tagPtr->nextPtr) {
	if (!tagPtr->isSelTag) {
	    borderPrio = MAX(borderPrio, FillStyle(tagPtr, &styleValues, haveFocus, containsSelection));
	}
    }

    /*
     * Setup attributes in case of selected text.
     */

    if (containsSelection) {
	TkTextTag *tagPtr1 = textPtr->selTagPtr;

	if ((int) tagPtr1->priority > borderPrio
		&& (haveFocus
		    /*
		     * If this is the selection tag, and selAttrs.inactiveBorder is NULL
		     * (the default on Windows), then we need to skip it if we don't have
		     * the focus.
		     */
		    || (textPtr->selAttrs.inactiveBorder
			/*
			 * Don't show inactive selection in readonly widgets.
			 */
#ifndef MAC_OSX_TK
			&& (textPtr->state == TK_TEXT_STATE_NORMAL)
#endif
		))) {
	    borderPrio = FillStyle(tagPtr1, &styleValues, haveFocus, containsSelection);

	    if (borderPrio == -1) {
		if (textPtr->selAttrs.border)  { styleValues.border = textPtr->selAttrs.border; }
		if (textPtr->selAttrs.fgColor) { styleValues.fgColor = textPtr->selAttrs.fgColor; }

		if (!haveFocus) {
		    if (textPtr->selAttrs.inactiveBorder) {
			styleValues.border = textPtr->selAttrs.inactiveBorder;
		    }
		    if (textPtr->selAttrs.inactiveFgColor) {
			styleValues.fgColor = textPtr->selAttrs.inactiveFgColor;
		    }
		}
	    }

	    if (!styleValues.fgColor) {
		styleValues.fgColor = textPtr->selAttrs.fgColor;
		if (!haveFocus && textPtr->selAttrs.inactiveFgColor) {
		    styleValues.fgColor = textPtr->selAttrs.inactiveFgColor;
		}
	    }
	}
    }

    /*
     * Setup with fallback values if needed.
     */

    if (styleValues.fgColor == NULL) {
	styleValues.fgColor = textPtr->fgColor;
    }
    if (styleValues.relief != TK_RELIEF_FLAT && !styleValues.border) {
	styleValues.border = textPtr->border;
    }

    /*
     * Use an existing style if there's one around that matches.
     */

    hPtr = Tcl_CreateHashEntry(&textPtr->dInfoPtr->styleTable, (char *) &styleValues, &isNew);
    if (!isNew) {
	return (TextStyle *)Tcl_GetHashValue(hPtr);
    }

    /*
     * No existing style matched. Make a new one.
     */

    stylePtr = (TextStyle *)ckalloc(sizeof(TextStyle));
    stylePtr->refCount = 0;
    if (styleValues.border) {
	gcValues.foreground = Tk_3DBorderColor(styleValues.border)->pixel;
	mask = GCForeground;
	if (styleValues.bgStipple != None) {
	    gcValues.stipple = styleValues.bgStipple;
	    gcValues.fill_style = FillStippled;
	    mask |= GCStipple|GCFillStyle;
	}
	stylePtr->bgGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues);
    } else {
	stylePtr->bgGC = NULL;
    }
    mask = GCFont;
    gcValues.font = Tk_FontId(styleValues.tkfont);
    mask |= GCForeground;
    if (styleValues.eolColor && textPtr->showEndOfLine) {
	gcValues.foreground = styleValues.eolColor->pixel;
	stylePtr->eolGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues);
    } else {
	stylePtr->eolGC = NULL;
    }
    if (styleValues.eotColor && textPtr->showEndOfText) {
	gcValues.foreground = styleValues.eotColor->pixel;
	stylePtr->eotGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues);
    } else {
	stylePtr->eotGC = NULL;
    }
    if (styleValues.hyphenColor && textPtr->hyphenate) {
	gcValues.foreground = styleValues.hyphenColor->pixel;
	stylePtr->hyphenGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues);
    } else {
	stylePtr->hyphenGC = NULL;
    }
    gcValues.foreground = styleValues.fgColor->pixel;
    if (styleValues.fgStipple != None) {
	gcValues.stipple = styleValues.fgStipple;
	gcValues.fill_style = FillStippled;
	mask |= GCStipple|GCFillStyle;
    }
    stylePtr->fgGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues);
    mask = GCForeground;
    gcValues.foreground = styleValues.underlineColor->pixel;
    stylePtr->ulGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues);
    gcValues.foreground = styleValues.overstrikeColor->pixel;
    stylePtr->ovGC = Tk_GetGC(textPtr->tkwin, mask, &gcValues);
    stylePtr->sValuePtr = (StyleValues *) Tcl_GetHashKey(&textPtr->dInfoPtr->styleTable, hPtr);
    stylePtr->hPtr = hPtr;
    Tcl_SetHashValue(hPtr, stylePtr);
    DEBUG_ALLOC(tkTextCountNewStyle++);
    return stylePtr;
}

static TextStyle *
GetStyle(
    TkText *textPtr,		/* Overall information about text widget. */
    TkTextSegment *segPtr)	/* The text for which display information is wanted. */
{
    TextStyle *stylePtr;
    TkTextTag *tagPtr;
    int flags;

    if (segPtr && (tagPtr = TkBTreeGetSegmentTags(
		    textPtr->sharedTextPtr, segPtr, textPtr, TK_TEXT_SORT_ASCENDING, &flags))) {
	stylePtr = MakeStyle(textPtr, tagPtr, !!(flags & TK_TEXT_IS_SELECTED));
    } else {
	/*
	 * Take into account that this function can be called before UpdateDefaultStyle
	 * has been called for the first time.
	 */
	if (!textPtr->dInfoPtr->defaultStyle) {
	    UpdateDefaultStyle(textPtr);
	}
	stylePtr = textPtr->dInfoPtr->defaultStyle;
    }

    stylePtr->refCount += 1;
    return stylePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * UpdateDefaultStyle --
 *
 *	This function is called if something has changed, and some DLines
 *	have to be updated.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
UpdateDefaultStyle(
    TkText *textPtr)
{
    TextStyle *stylePtr = MakeStyle(textPtr, NULL, 0);
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    if (stylePtr != dInfoPtr->defaultStyle) {
	if (dInfoPtr->defaultStyle) {
	    FreeStyle(textPtr, dInfoPtr->defaultStyle);
	}
	dInfoPtr->defaultStyle = stylePtr;
	stylePtr->refCount += 1;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * FreeStyle --
 *
 *	This function is called when a TextStyle structure is no longer
 *	needed. It decrements the reference count and frees up the space for
 *	the style structure if the reference count is 0.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The storage and other resources associated with the style are freed up
 *	if no-one's still using it.
 *
 *----------------------------------------------------------------------
 */

static void
FreeStyle(
    TkText *textPtr,		/* Information about overall widget. */
    TextStyle *stylePtr)	/* Information about style to free. */
{
    assert(stylePtr);
    assert(stylePtr->refCount > 0);

    if (--stylePtr->refCount == 0) {
	if (stylePtr->bgGC != NULL) {
	    Tk_FreeGC(textPtr->display, stylePtr->bgGC);
	}
	if (stylePtr->fgGC != NULL) {
	    Tk_FreeGC(textPtr->display, stylePtr->fgGC);
	}
	if (stylePtr->ulGC != NULL) {
	    Tk_FreeGC(textPtr->display, stylePtr->ulGC);
	}
	if (stylePtr->ovGC != NULL) {
	    Tk_FreeGC(textPtr->display, stylePtr->ovGC);
	}
	if (stylePtr->eolGC != NULL) {
	    Tk_FreeGC(textPtr->display, stylePtr->eolGC);
	}
	if (stylePtr->eotGC != NULL) {
	    Tk_FreeGC(textPtr->display, stylePtr->eotGC);
	}
	if (stylePtr->hyphenGC != NULL) {
	    Tk_FreeGC(textPtr->display, stylePtr->hyphenGC);
	}
	Tcl_DeleteHashEntry(stylePtr->hPtr);
	ckfree(stylePtr);
	DEBUG_ALLOC(tkTextCountDestroyStyle++);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * IsStartOfNotMergedLine --
 *
 *	This function checks whether the given index is the start of a
 *      logical line that is not merged with the previous logical line
 *      (due to elision of the eol of the previous line).
 *
 * Results:
 *	Returns whether the given index denotes the first index of a
 *      logical line not merged with its previous line.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
IsStartOfNotMergedLine(
      const TkTextIndex *indexPtr)  /* Index to check. */
{
    return TkTextIndexGetLine(indexPtr)->logicalLine
	    ? TkTextIndexIsStartOfLine(indexPtr)
	    : TkTextIndexIsStartOfText(indexPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * IsSameFGStyle --
 *
 *	Compare the foreground attributes of two styles. Specifically must
 *	consider: foreground color, font, font style and font decorations,
 *	elide, "offset" and foreground stipple. Do *not* consider: background
 *	color, border, relief or background stipple.
 *
 *	If we use TkpDrawCharsInContext, we also don't need to check
 *	foreground color, font decorations, elide, offset and foreground
 *	stipple, so all that is left is font (including font size and font
 *	style) and "offset".
 *
 * Results:
 *	'true' if the two styles match, 'false' otherwise.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

#ifdef TK_LAYOUT_WITH_BASE_CHUNKS

static int
IsSameFGStyle(
    TextStyle *style1,
    TextStyle *style2)
{
    StyleValues *sv1;
    StyleValues *sv2;

    if (style1 == style2) {
	return 1;
    }

    sv1 = style1->sValuePtr;
    sv2 = style2->sValuePtr;

    return sv1->tkfont == sv2->tkfont && sv1->offset == sv2->offset;
}

#endif /* TK_LAYOUT_WITH_BASE_CHUNKS */

/*
 *----------------------------------------------------------------------
 *
 * LayoutDLine --
 *
 *	This function generates a single DLine structure for a display line
 *	whose leftmost character is given by indexPtr.
 *
 * Results:
 *	The return value is a pointer to a DLine structure describing the
 *	display line. All fields are filled in and correct except for y and
 *	nextPtr.
 *
 * Side effects:
 *	Storage is allocated for the new DLine.
 *
 *	See the comments in 'GetYView' for some thoughts on what the side-
 *	effects of this call (or its callers) should be; the synchronisation
 *	of TkTextLine->pixelHeight with the sum of the results of this
 *	function operating on all display lines within each logical line.
 *	Ideally the code should be refactored to ensure the cached pixel
 *	height is never behind what is known when this function is called
 *	elsewhere.
 *
 *----------------------------------------------------------------------
 */

static TkTextSegment *
LayoutGetNextSegment(
    TkTextSegment *segPtr)
{
    assert(segPtr);
    while ((segPtr = segPtr->nextPtr)) {
	if (segPtr->typePtr == &tkTextCharType) {
	    return segPtr;
	}
	if (segPtr->typePtr == &tkTextBranchType) {
	    segPtr = segPtr->body.branch.nextPtr;
	}
    }
    return NULL;
}

static TkTextDispChunk *
LayoutGetNextCharChunk(
    TkTextDispChunk *chunkPtr)
{
    assert(chunkPtr);
    while ((chunkPtr = chunkPtr->nextPtr)) {
	switch (chunkPtr->layoutProcs->type) {
	case TEXT_DISP_CHAR:	return chunkPtr;
	case TEXT_DISP_WINDOW:	/* fallthru */
	case TEXT_DISP_IMAGE:	return NULL;
	case TEXT_DISP_HYPHEN:	/* fallthru */
	case TEXT_DISP_ELIDED:	/* fallthru */
	case TEXT_DISP_CURSOR:	break;
	}
    }
    return NULL;
}

static void
LayoutSetupDispLineInfo(
    TkTextPixelInfo *pixelInfo)
{
    TkTextDispLineInfo *dispLineInfo = pixelInfo->dispLineInfo;
    unsigned oldNumDispLines = TkBTreeGetNumberOfDisplayLines(pixelInfo);

    if (!dispLineInfo) {
	dispLineInfo = (TkTextDispLineInfo *)ckalloc(TEXT_DISPLINEINFO_SIZE(2));
	DEBUG(memset(dispLineInfo, 0xff, TEXT_DISPLINEINFO_SIZE(2)));
	DEBUG_ALLOC(tkTextCountNewDispInfo++);
	pixelInfo->dispLineInfo = dispLineInfo;
    }

    dispLineInfo->numDispLines = 1;
    /* remember old display line count, see TkBTreeGetNumberOfDisplayLines */
    dispLineInfo->entry[1].pixels = oldNumDispLines;
}

static void
LayoutUpdateLineHeightInformation(
    const LayoutData *data,
    DLine *dlPtr,
    TkTextLine *linePtr,	/* The corresponding logical line. */
    int finished,		/* Did we finish the layout of a complete logical line? */
    int hyphenRule,		/* Applied hyphen rule; zero if no rule has been applied. */
    int tabIndex,		/* Tab index of last chunk in line; zero if no tab. */
    int tabApplied)		/* Tab index of last chunk in line has been already applied? */
{
    TkText *textPtr = data->textPtr;
    unsigned epoch = textPtr->dInfoPtr->lineMetricUpdateEpoch;
    TkTextPixelInfo *pixelInfo = TkBTreeLinePixelInfo(textPtr, linePtr);
    unsigned oldNumDispLines = TkBTreeGetNumberOfDisplayLines(pixelInfo);
    TkTextDispLineInfo *dispLineInfo;

    assert(dlPtr->byteCount > 0);
    assert(linePtr->logicalLine);
    assert(TkTextIndexGetLine(&dlPtr->index));
    assert(linePtr == TkBTreeGetLogicalLine(
	    textPtr->sharedTextPtr, textPtr, TkTextIndexGetLine(&dlPtr->index)));

    if (pixelInfo->epoch == epoch) {
	int lineNo = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, linePtr, NULL);

	if (TkRangeListContains(textPtr->dInfoPtr->lineMetricUpdateRanges, lineNo)) {
	    int mergedLines = 1;
	    TkTextLine *nextLogicalLinePtr;

	    nextLogicalLinePtr = TkBTreeNextLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
	    if (linePtr->nextPtr != nextLogicalLinePtr) {
		mergedLines = TkBTreeCountLines(textPtr->sharedTextPtr->tree, linePtr,
			nextLogicalLinePtr) - 1;
	    }
	    TkRangeListRemove(textPtr->dInfoPtr->lineMetricUpdateRanges, lineNo, lineNo + mergedLines);
	}

	return; /* already up-to-date */
    }

    TK_TEXT_DEBUG(LogTextHeightCalc(textPtr, &dlPtr->index));
    dispLineInfo = pixelInfo->dispLineInfo;
    dlPtr->hyphenRule = hyphenRule;

    if (dlPtr->displayLineNo > 0) {
	TkTextDispLineEntry *dispLineEntry;

	assert(dispLineInfo);
	assert(data->byteOffset == dispLineInfo->entry[dlPtr->displayLineNo].byteOffset);

	if (dlPtr->displayLineNo >= dispLineInfo->numDispLines
		&& !IsPowerOf2(dlPtr->displayLineNo + 2)) {
	    unsigned size = NextPowerOf2(dlPtr->displayLineNo + 2);
	    dispLineInfo = (TkTextDispLineInfo *)ckrealloc(dispLineInfo, TEXT_DISPLINEINFO_SIZE(size));
	    DEBUG(memset(dispLineInfo->entry + dlPtr->displayLineNo + 1, 0xff,
		    (size - dlPtr->displayLineNo - 1)*sizeof(dispLineInfo->entry[0])));
	    pixelInfo->dispLineInfo = dispLineInfo;
	}
	dispLineInfo->numDispLines = dlPtr->displayLineNo + 1;
	dispLineEntry = dispLineInfo->entry + dlPtr->displayLineNo;
	(dispLineEntry + 1)->byteOffset = data->byteOffset + dlPtr->byteCount;
	(dispLineEntry + 1)->pixels = oldNumDispLines;
	dispLineEntry->height = dlPtr->height;
	dispLineEntry->pixels = (dispLineEntry - 1)->pixels + dlPtr->height;
	dispLineEntry->byteOffset = data->byteOffset;
	dispLineEntry->hyphenRule = hyphenRule;
	dispLineEntry->tabIndex = tabIndex;
	dispLineEntry->tabApplied = tabApplied;
    } else if (!finished) {
	LayoutSetupDispLineInfo(pixelInfo);
	dispLineInfo = pixelInfo->dispLineInfo;
	dispLineInfo->entry[0].height = dlPtr->height;
	dispLineInfo->entry[0].pixels = dlPtr->height;
	dispLineInfo->entry[0].byteOffset = data->byteOffset;
	dispLineInfo->entry[0].hyphenRule = hyphenRule;
	dispLineInfo->entry[0].tabIndex = tabIndex;
	dispLineInfo->entry[0].tabApplied = tabApplied;
	dispLineInfo->entry[1].byteOffset = data->byteOffset + dlPtr->byteCount;
    }

    assert(finished || dispLineInfo);

    if (finished) {
	TkTextLine *nextLogicalLinePtr;
	unsigned lineHeight, mergedLines, lineNo, numDispLines, i;

	if (dlPtr->displayLineNo > 0) {
	    lineHeight = dispLineInfo->entry[dispLineInfo->numDispLines - 1].pixels;
	    numDispLines = dispLineInfo->numDispLines;
	} else {
	    lineHeight = dlPtr->height;
	    numDispLines = lineHeight > 0;
	}
	assert(linePtr->nextPtr);
	nextLogicalLinePtr = TkBTreeNextLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
	mergedLines = TkBTreeCountLines(textPtr->sharedTextPtr->tree, linePtr, nextLogicalLinePtr);
	if (mergedLines > 0) {
	    mergedLines -= 1; /* subtract first line */
	}
	if (pixelInfo->height != lineHeight || mergedLines > 0 || numDispLines != oldNumDispLines) {
	    /*
	     * Do this B-Tree update before updating the epoch, because this action
	     * needs the old values.
	     */
	    TkBTreeAdjustPixelHeight(textPtr, linePtr, lineHeight, mergedLines, numDispLines);
	}
	if (dispLineInfo && dlPtr->displayLineNo == 0) {
	    /*
	     * This is the right place to destroy the superfluous dispLineInfo. Don't do
	     * this before TkBTreeAdjustPixelHeight has been called, because the latter
	     * function needs the old display line count.
	     */
	    ckfree(dispLineInfo);
	    DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    pixelInfo->dispLineInfo = NULL;
	}
	textPtr->dInfoPtr->lineMetricUpdateCounter += 1;
	pixelInfo->epoch = epoch;
	lineNo = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, linePtr, NULL);
	for (i = 0; i < mergedLines; ++i) {
	    pixelInfo = TkBTreeLinePixelInfo(textPtr, linePtr = linePtr->nextPtr);
	    pixelInfo->epoch = epoch;
	    if (pixelInfo->dispLineInfo) {
		ckfree(pixelInfo->dispLineInfo);
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
		pixelInfo->dispLineInfo = NULL;
	    }
	}
	TkRangeListRemove(textPtr->dInfoPtr->lineMetricUpdateRanges, lineNo, lineNo + mergedLines);
    } else {
	/*
	 * This line is wrapping into several display lines. We mark it as already
	 * up-to-date, even with a partial computation. This is the right way to
	 * handle very long lines efficiently, because with very long lines the chance
	 * will be high that the lookup into the cache succeeds even with a partial
	 * computation. (If the lookup fails, because the cache for this line is not
	 * yet complete, then the required remaining lines will be computed, and the
	 * result will also be stored in the cache, because all metric computation
	 * will be done with LayoutDLine, and this function is caching any computation.)
	 */

	pixelInfo->epoch = epoch | PARTIAL_COMPUTED_BIT;
    }
}

static unsigned
LayoutComputeBreakLocations(
    LayoutData *data)
{
    unsigned totalSize = 0;
    TkText *textPtr = data->textPtr;
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    TkTextSegment *segPtr = data->logicalLinePtr->segPtr;
    int useUniBreak = data->textPtr->useUniBreak;
    char const *lang = useUniBreak ? textPtr->lang : NULL;
    char const *nextLang = NULL;
    unsigned capacity = dInfoPtr->strBufferSize;
    char *str = dInfoPtr->strBuffer;
    char *brks = textPtr->brksBuffer;

    /*
     * The codepoint line break computation requires the whole logical line (due to a
     * poor design of libunibreak), but separated by languages, because this line break
     * algorithm is in general language dependent.
     */

    while (segPtr) {
	unsigned size = 0;
	unsigned newTotalSize;

	for ( ; segPtr; segPtr = segPtr->nextPtr) {
	    switch ((int) segPtr->typePtr->group) {
	    case SEG_GROUP_CHAR: {
		unsigned newSize;

		if (useUniBreak) {
		    const char *myLang = TkBTreeGetLang(textPtr, segPtr);

		    if (myLang[0] != lang[0] || myLang[1] != lang[1]) {
			nextLang = myLang;
			break;
		    }
		}
		if ((newSize = size + segPtr->size) >= capacity) {
		    capacity = MAX(2*capacity, newSize + 1);
		    str = (char *)ckrealloc(str, newSize);
		}
		memcpy(str + size, segPtr->body.chars, segPtr->size);
		size = newSize;
		break;
	    }
	    case SEG_GROUP_HYPHEN:
		if (useUniBreak) {
		    const char *myLang = TkBTreeGetLang(textPtr, segPtr);

		    if (myLang[0] != lang[0] || myLang[1] != lang[1]) {
			nextLang = myLang;
			break;
		    }
		}

		/*
		 * Use TAB (U+0009) instead of SHY (U+00AD), because SHY needs two bytes,
		 * but TAB needs only one byte, and this corresponds to the byte size of
		 * a hyphen segment. The TAB character has the same character class as
		 * the SHY character, so it's a proper substitution.
		 *
		 * NOTE: Do not use '-' (U+002D) for substitution, because the meaning
		 * of this character is contextual.
		 */

		/* FALLTHRU */
	    case SEG_GROUP_IMAGE:
	    case SEG_GROUP_WINDOW:
		/* The language variable doesn't matter here. */
		if (size + 1 >= capacity) {
		    assert(2*capacity > size + 1);
		    str = (char *)ckrealloc(str, capacity *= 2);
		}
		/* Substitute with a TAB, so we can break at this point. */
		str[size++] = '\t';
		break;
	    case SEG_GROUP_BRANCH:
		segPtr = segPtr->body.branch.nextPtr;
		break;
	    }
	}
	if (size > 0) {
	    newTotalSize = totalSize + size;

	    if (newTotalSize > textPtr->brksBufferSize) {
		/*
		 * Take into account that the buffer must be a bit larger, because we need
		 * one additional byte for trailing NUL (see below).
		 */
		textPtr->brksBufferSize = MAX(newTotalSize, textPtr->brksBufferSize + 512);
		textPtr->brksBuffer = (char *)ckrealloc(textPtr->brksBuffer, textPtr->brksBufferSize + 1);
		brks = textPtr->brksBuffer;
	    }

	    str[size] = '\0'; /* TkTextComputeBreakLocations expects traling nul */
	    TkTextComputeBreakLocations(data->textPtr->interp, str, size,
		    lang ? (*lang ? lang : "en") : NULL, brks + totalSize);
	    totalSize = newTotalSize;
	}
	lang = nextLang;
    }

    dInfoPtr->strBuffer = str;
    dInfoPtr->strBufferSize = capacity;

    return totalSize;
}

static void
LayoutLookAheadChars(
    TkTextDispChunk *chunkPtr,
    const char *str,
    unsigned numChars,
    char *buf)
{
    TkTextSegment *segPtr = ((CharInfo *) chunkPtr->clientData)->segPtr;

    for ( ; numChars > 0; --numChars) {
	if (!*str) {
	    segPtr = LayoutGetNextSegment(segPtr);
	    if (!segPtr) {
		memset(buf, '\0', numChars);
		return;
	    }
	    str = segPtr->body.chars;
	}
	*buf++ = *str++;
    }
}

static void
LayoutApplyHyphenRules(
    LayoutData *data,
    TkTextDispChunk *prevCharChunkPtr,
    TkTextDispChunk *hyphenChunkPtr,
    TkTextDispChunk *nextCharChunkPtr)
{
    TkTextSegment *hyphenPtr = (TkTextSegment *)hyphenChunkPtr->clientData;
    const StyleValues *sValPtr = hyphenChunkPtr->stylePtr->sValuePtr;
    int hyphenRules = sValPtr->hyphenRules & hyphenChunkPtr->hyphenRules;

    data->increaseNumBytes = 0;
    data->decreaseNumBytes = 0;
    SetupHyphenChars(hyphenPtr, 0);
    hyphenRules = FilterHyphenRules(hyphenRules, sValPtr->lang);

    if (hyphenRules) {
	const CharInfo *prevCiPtr;
	const CharInfo *nextCiPtr;
	const char *prevCharPtr;
	const char *nextCharPtr;
	unsigned char prevChar;
	unsigned char nextChar;
	char lookAhead[3];

	if (hyphenRules & (1 << TK_TEXT_HYPHEN_REPEAT)) {
	    data->increaseNumBytes = -1;
	    data->hyphenRule = TK_TEXT_HYPHEN_REPEAT;
	    return;
	}

	if (!IsCharChunk(prevCharChunkPtr)) {
	    return;
	}

	while ((prevCiPtr = (const CharInfo *)prevCharChunkPtr->clientData)->numBytes == 0) {
	    if (!(prevCharChunkPtr = (TkTextDispChunk *)prevCharChunkPtr->prevCharChunkPtr)
		    || !IsCharChunk(prevCharChunkPtr)) {
		return;
	    }
	}
	prevCharPtr = prevCiPtr->u.chars + prevCiPtr->baseOffset + prevCiPtr->numBytes - 1;

	/*
	 * We know that we have to inspect only Latin-1 characters, either
	 * from ASCII code page (< 0x80), or starting with 0xc3.
	 */

	if (UCHAR(prevCharPtr[0]) < 0x80) {
	    prevChar = UCHAR(prevCharPtr[0]);
	} else if (prevCiPtr->numBytes > 1 && UCHAR(prevCharPtr[-1]) == 0xc3) {
	    prevChar = ConvertC3Next(prevCharPtr[1]);
	} else {
	    return;
	}

	if (hyphenRules & (1 << TK_TEXT_HYPHEN_DOUBLE_VOWEL)) {
	    /* op(aa-)tje  -> op(a-)tje */
	    /* caf(ee-)tje -> caf(é-)tje */
	    if (IsVowel(prevChar)) {
		char secondPrevChar = '\0';

		if (prevCiPtr->numBytes > 1) {
		    secondPrevChar = prevCharPtr[-1];
		} else {
		    const TkTextDispChunk *chunkPtr = prevCharChunkPtr->prevCharChunkPtr;
		    if (chunkPtr && IsCharChunk(chunkPtr)) {
			const TkTextSegment *segPtr = CHAR_CHUNK_GET_SEGMENT(chunkPtr);
			secondPrevChar = segPtr->body.chars[segPtr->size - 1];
		    }
		}
		if (prevChar == secondPrevChar) {
		    if (prevChar == 'e') {
			char *s = hyphenPtr->body.chars; /* this avoids warnings */
			data->decreaseNumBytes = 2;
			s[0] = 0xc3; s[1] = 0xa9; /* 'é' = U+00E9 */
			SetupHyphenChars(hyphenPtr, 2);
		    } else {
			data->decreaseNumBytes = 1;
		    }
		    data->hyphenRule = TK_TEXT_HYPHEN_DOUBLE_VOWEL;
		    return;
		}
	    }
	}

	if (!IsCharChunk(nextCharChunkPtr)) {
	    return;
	}
	if ((nextCiPtr = (const CharInfo *)nextCharChunkPtr->clientData)->numBytes == 0) {
	    TkTextSegment *segPtr = LayoutGetNextSegment((TkTextSegment *)nextCharChunkPtr->clientData);
	    if (!segPtr) {
		return;
	    }
	    nextCharPtr = segPtr->body.chars;
	} else {
	    nextCharPtr = nextCiPtr->u.chars + nextCiPtr->baseOffset;
	}
	if (UCHAR(nextCharPtr[0]) < 0x80) {
	    nextChar = UCHAR(nextCharPtr[0]);
	} else if (UCHAR(nextCharPtr[0]) == 0xc3) {
	    nextChar = ConvertC3Next(nextCharPtr[1]);
	} else {
	    return;
	}

	if (hyphenRules & (1 << TK_TEXT_HYPHEN_CK)) {
	    /* Dru(c-k)er -> Dru(k-k)er */
	    if (prevChar == UCHAR('c') && nextChar == UCHAR('k')) {
		data->decreaseNumBytes = 1;
		hyphenPtr->body.chars[0] = 'k';
		SetupHyphenChars(hyphenPtr, 1);
		data->hyphenRule = TK_TEXT_HYPHEN_CK;
		return;
	    }
	}
	if (hyphenRules & (1 << TK_TEXT_HYPHEN_DOUBLE_DIGRAPH)) {
	    /* vi(s-sz)a -> vi(sz-sz)a */
	    if (prevChar == nextChar) {
		LayoutLookAheadChars(nextCharChunkPtr, nextCharPtr + 1, 1, lookAhead);
		if (lookAhead[0] && IsDoubleDigraph(prevChar, lookAhead[0])) {
		    hyphenPtr->body.chars[0] = lookAhead[0];
		    SetupHyphenChars(hyphenPtr, 1);
		    data->hyphenRule = TK_TEXT_HYPHEN_DOUBLE_DIGRAPH;
		    return;
		}
	    }
	}
	if (hyphenRules & (1 << TK_TEXT_HYPHEN_TREMA)) {
	    /* r(e-ëe)l -> r(e-ee)l */
	    if (IsVowel(prevChar) && IsUmlaut(nextChar)) {
		data->hyphenRule = TK_TEXT_HYPHEN_TREMA;
		return;
	    }
	}
	if (hyphenRules & (1 << TK_TEXT_HYPHEN_GEMINATION)) {
	    /* para(-l·l)el -> para(l-l)el */
	    if (tolower(nextChar) == 'l') {
		LayoutLookAheadChars(nextCharChunkPtr, nextCharPtr + 1, 3, lookAhead);
		/* test for U+00B7 = MIDDOT */
		if (UCHAR(lookAhead[0]) == 0xc2
			&& UCHAR(lookAhead[1]) == 0xb7
			&& lookAhead[2] == nextChar) {
		    data->increaseNumBytes = 3;
		    hyphenPtr->body.chars[0] = nextChar;
		    SetupHyphenChars(hyphenPtr, 1);
		    data->hyphenRule = TK_TEXT_HYPHEN_GEMINATION;
		    return;
		}
	    }
	}
    }
}

static unsigned
LayoutMakeCharInfo(
    LayoutData *data,
    TkTextSegment *segPtr,
    int byteOffset,
    int maxBytes)
{
    char const *p = segPtr->body.chars + byteOffset;
    CharInfo *ciPtr = AllocCharInfo(data->textPtr);

    assert(data->chunkPtr);
    assert(!data->chunkPtr->clientData);

    /*
     * Take into account that maxBytes == 0 is possible.
     */

    if (data->trimSpaces && maxBytes > 0 && p[maxBytes - 1] == ' ') {
	while (maxBytes > 1 && p[maxBytes - 2] == ' ') {
	    maxBytes -= 1;
	}
    }

#ifdef TK_LAYOUT_WITH_BASE_CHUNKS

    if (data->baseChunkPtr
	    && (!IsSameFGStyle(data->baseChunkPtr->stylePtr, data->chunkPtr->stylePtr)
		|| (data->lastCharChunkPtr && data->lastCharChunkPtr->numSpaces > 0))) {
	data->baseChunkPtr = NULL;
    }

    if (!data->baseChunkPtr) {
	data->baseChunkPtr = data->chunkPtr;
	Tcl_DStringInit(&data->chunkPtr->baseChars);
	DEBUG_ALLOC(tkTextCountNewBaseChars++);
    }

    data->chunkPtr->baseChunkPtr = data->baseChunkPtr;
    ciPtr->baseOffset = Tcl_DStringLength(&data->baseChunkPtr->baseChars);
    ciPtr->u.chars = Tcl_DStringAppend(&data->baseChunkPtr->baseChars, p, maxBytes);

#else

    ciPtr->baseOffset = 0;
    ciPtr->u.chars = p;

#endif

    /*
     * Keep the char segment, otherwise a split may invalidate our string. This segment
     * is also used for hyphenation support.
     */

    segPtr->refCount += 1;
    ciPtr->segPtr = segPtr;
    ciPtr->numBytes = maxBytes;
    data->chunkPtr->clientData = ciPtr;

    return maxBytes;
}

static void
LayoutFinalizeCharInfo(
    LayoutData *data,
    int gotTab)
{
    CharInfo *ciPtr = (CharInfo *)data->chunkPtr->clientData;

    assert(data->trimSpaces ?
	    (Tcl_Size)data->chunkPtr->numBytes >= ciPtr->numBytes :
	    (Tcl_Size)data->chunkPtr->numBytes == ciPtr->numBytes);

    /*
     * Update the character information. Take into account that we don't want
     * to display the newline character.
     */

    if (ciPtr->u.chars[ciPtr->baseOffset + ciPtr->numBytes - 1] == '\n') {
	ciPtr->numBytes -= 1;
    }

#ifdef TK_LAYOUT_WITH_BASE_CHUNKS

    assert(data->chunkPtr->baseChunkPtr);

    /*
     * Final update for the current base chunk data.
     */

    Tcl_DStringSetLength(&data->baseChunkPtr->baseChars, ciPtr->baseOffset + ciPtr->numBytes);
    data->baseChunkPtr->baseWidth =
	    data->chunkPtr->width + (data->chunkPtr->x - data->baseChunkPtr->x);

    /*
     * Finalize the base chunk if this chunk ends in a tab, which definitly breaks the context.
     */

    if (gotTab) {
	data->baseChunkPtr = NULL;
    }
#else
    (void)gotTab;
#endif
}

static void
LayoutUndisplay(
    LayoutData *data,
    TkTextDispChunk *chunkPtr)
{
    assert(chunkPtr->layoutProcs);

    if (chunkPtr->layoutProcs->undisplayProc) {
	chunkPtr->layoutProcs->undisplayProc(data->textPtr, chunkPtr);
    }
#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
    if (chunkPtr == data->baseChunkPtr) {
	data->baseChunkPtr = NULL;
    }
#endif
}

static void
LayoutReleaseChunk(
    TkText *textPtr,
    TkTextDispChunk *chunkPtr)
{
    if (chunkPtr->layoutProcs) {
	if (chunkPtr->layoutProcs->type == TEXT_DISP_IMAGE) {
	    textPtr->dInfoPtr->countImages -= 1;
	} else if (chunkPtr->layoutProcs->type == TEXT_DISP_WINDOW) {
	    textPtr->dInfoPtr->countWindows -= 1;
	}
    }
    FreeStyle(textPtr, chunkPtr->stylePtr);
}

static void
LayoutFreeChunk(
    LayoutData *data)
{
    TextDInfo *dInfoPtr = data->textPtr->dInfoPtr;
    TkTextDispChunk *chunkPtr = data->chunkPtr;

    assert(chunkPtr);
    assert(data->lastChunkPtr != chunkPtr);
    assert(data->lastCharChunkPtr != chunkPtr);
    assert(!chunkPtr->sectionPtr);

    if (chunkPtr->layoutProcs) {
	LayoutUndisplay(data, chunkPtr);
    }

    LayoutReleaseChunk(data->textPtr, chunkPtr);
    DEBUG(chunkPtr->stylePtr = NULL);
    assert(!chunkPtr->clientData);
    data->numBytesSoFar -= chunkPtr->numBytes;
    chunkPtr->nextPtr = dInfoPtr->chunkPoolPtr;
    dInfoPtr->chunkPoolPtr = chunkPtr;
    dInfoPtr->chunkPoolPtr->prevPtr = NULL;
    data->chunkPtr = NULL;
    assert(data->countChunks > 0);
    data->countChunks -= 1;
    if (chunkPtr->width > 0) {
	assert(data->countVisibleChunks > 0);
	data->countVisibleChunks -= 1;
    }
}

static void
LayoutDoWidthAdjustmentForContextDrawing(
    LayoutData *data)
{
#if defined(TK_LAYOUT_WITH_BASE_CHUNKS) && TK_DRAW_IN_CONTEXT
    TkTextDispChunk *chunkPtr = data->chunkPtr;

    if (chunkPtr->prevPtr) {
	chunkPtr->x += chunkPtr->prevPtr->xAdjustment;
    }

    if (IsCharChunk(chunkPtr)) {
	int newWidth;

	CharChunkMeasureChars(chunkPtr, NULL, 0, 0, -1, 0, -1, data->textPtr->spaceMode, 0, &newWidth);
	chunkPtr->xAdjustment = newWidth - chunkPtr->width;
	chunkPtr->width = newWidth;
    }
#else
    (void)data;
#endif
}

static void
LayoutFinalizeChunk(
    LayoutData *data)
{
    const TkTextDispChunkProcs *layoutProcs;

    if (!data->chunkPtr) {
	return;
    }

    layoutProcs = data->chunkPtr->layoutProcs;

    if (!layoutProcs) {
	assert(data->chunkPtr->numBytes == 0);
	assert(!data->chunkPtr->clientData);
	LayoutFreeChunk(data);
	return;
    }

    if (layoutProcs->type & TEXT_DISP_CONTENT) {
	data->lastCharChunkPtr = data->chunkPtr;
	if (!data->firstCharChunkPtr) {
	    data->firstCharChunkPtr = data->chunkPtr;
	}
	if (layoutProcs->type & TEXT_DISP_TEXT) {
	    LayoutDoWidthAdjustmentForContextDrawing(data);
	}
    }
    if (data->chunkPtr->breakIndex > 0) {
	data->breakChunkPtr = data->chunkPtr;
    }
    if (!data->firstChunkPtr) {
	assert(!data->lastChunkPtr);
	data->firstChunkPtr = data->chunkPtr;
    } else {
	assert(data->lastChunkPtr);
	data->lastChunkPtr->nextPtr = data->chunkPtr;
    }
    data->lastChunkPtr = data->chunkPtr;
    data->dispLineOffset += data->chunkPtr->numBytes;
    data->chunkPtr = NULL;
}

static TkTextDispChunkSection *
LayoutNewSection(
    TextDInfo *dInfoPtr)
{
    TkTextDispChunkSection *sectionPtr = dInfoPtr->sectionPoolPtr;

    if (sectionPtr) {
	dInfoPtr->sectionPoolPtr = dInfoPtr->sectionPoolPtr->nextPtr;
    } else {
	DEBUG_ALLOC(tkTextCountNewSection++);
	sectionPtr = (TkTextDispChunkSection *)ckalloc(sizeof(TkTextDispChunkSection));
    }

    memset(sectionPtr, 0, sizeof(TkTextDispChunkSection));
    return sectionPtr;
}

static void
LayoutMakeNewChunk(
    LayoutData *data)
{
    TkTextDispChunk *newChunkPtr;
    TextDInfo *dInfoPtr = data->textPtr->dInfoPtr;

    LayoutFinalizeChunk(data);
    if ((newChunkPtr = dInfoPtr->chunkPoolPtr)) {
	dInfoPtr->chunkPoolPtr = newChunkPtr->nextPtr;
    } else {
	newChunkPtr = (TkTextDispChunk *)ckalloc(sizeof(TkTextDispChunk));
	DEBUG_ALLOC(tkTextCountNewChunk++);
    }
    memset(newChunkPtr, 0, sizeof(TkTextDispChunk));
    newChunkPtr->dlPtr = data->dlPtr;
    newChunkPtr->uniqID = dInfoPtr->chunkCounter++;
    newChunkPtr->prevPtr = data->lastChunkPtr;
    newChunkPtr->prevCharChunkPtr = data->lastCharChunkPtr;
    newChunkPtr->stylePtr = GetStyle(data->textPtr, NULL);
    newChunkPtr->x = data->x;
    newChunkPtr->byteOffset = data->dispLineOffset;
    data->chunkPtr = newChunkPtr;
    data->countChunks += 1;
}

static void
LayoutSkipBytes(
    LayoutData *data,
    TCL_UNUSED(DLine *),
    const TkTextIndex *indexPtr1,
    const TkTextIndex *indexPtr2)
{
    LayoutMakeNewChunk(data);
    data->chunkPtr->layoutProcs = &layoutElideProcs;
    data->chunkPtr->numBytes = TkTextIndexCountBytes(indexPtr1, indexPtr2);
}

static void
LayoutSetupChunk(
    LayoutData *data,
    TkTextSegment *segPtr)
{
    TkTextDispChunk *chunkPtr = data->chunkPtr;
    TkText *textPtr = data->textPtr;
    TextStyle *stylePtr;

    assert(segPtr->tagInfoPtr);
    assert(chunkPtr->stylePtr == textPtr->dInfoPtr->defaultStyle);
    assert(chunkPtr->stylePtr->refCount > 1);

    chunkPtr->stylePtr->refCount -= 1;
    chunkPtr->stylePtr = stylePtr = GetStyle(textPtr, segPtr);

    if (data->wrapMode == TEXT_WRAPMODE_CODEPOINT) {
	if (!data->brks) {
	    Tcl_HashEntry *hPtr;
	    TkTextBreakInfo *breakInfo;
	    int isNew;

	    hPtr = Tcl_CreateHashEntry(&textPtr->sharedTextPtr->breakInfoTable,
		    (void *) data->logicalLinePtr, &isNew);

	    if (isNew) {
		breakInfo = (TkTextBreakInfo *)ckalloc(sizeof(TkTextBreakInfo));
		breakInfo->refCount = 1;
		breakInfo->brks = NULL;
		data->logicalLinePtr->changed = 0;
		Tcl_SetHashValue(hPtr, breakInfo);
		DEBUG(breakInfo->brksSize = 0);
		DEBUG_ALLOC(tkTextCountNewBreakInfo++);
	    } else {
		breakInfo = (TkTextBreakInfo *)Tcl_GetHashValue(hPtr);
		breakInfo->refCount += 1;

		/*
		 * We have to avoid repeated computations of line break information,
		 * so we use the 'changed' flag of the logical line for the determination
		 * whether a recomputation has to be performed. This is the only purpose
		 * of flag 'changed', and required because our current line break
		 * information algorithm has to process the whole logical line. If this
		 * behavior will change - for example a switch to the ICU library - then
		 * flag 'changed' has no use anymore and can be removed. But currently
		 * all line modifications have to update this flag.
		 */

		if (data->logicalLinePtr->changed) {
		    isNew = 1;
		    data->logicalLinePtr->changed = 0;
		}
	    }

	    if (isNew) {
		unsigned brksSize;

		/*
		 * In this case we have to parse the whole logical line for the computation
		 * of the break locations.
		 */

		brksSize = LayoutComputeBreakLocations(data);
		breakInfo->brks = (char *)ckrealloc(breakInfo->brks, brksSize);
		memcpy(breakInfo->brks, textPtr->brksBuffer, brksSize);
		DEBUG(breakInfo->brksSize = brksSize);
		DEBUG(stats.breakInfo += 1);
	    }

	    data->breakInfo = breakInfo;
	    data->brks = breakInfo->brks;
	}

	if (segPtr->sectionPtr) {
	    chunkPtr->brks = data->brks + data->byteOffset + chunkPtr->byteOffset;
	} else {
	    /* This is an artificial chunk for the realization of spelling changes. */
	    assert(chunkPtr->numBytes <= sizeof(doNotBreakAtAll));
	    chunkPtr->brks = doNotBreakAtAll;
	}
    }

    if (data->numBytesSoFar == 0) {
	const TextDInfo *dInfoPtr = textPtr->dInfoPtr;
	const StyleValues *sValuePtr = stylePtr->sValuePtr;

	data->tabArrayPtr = sValuePtr->tabArrayPtr;
	data->tabStyle = sValuePtr->tabStyle;
	data->justify = (TkTextJustify)sValuePtr->justify;
	data->rMargin = sValuePtr->rMargin;
	data->wrapMode = (TkWrapMode)sValuePtr->wrapMode;
	data->x = data->paragraphStart ? sValuePtr->lMargin1 : sValuePtr->lMargin2;
	data->width = dInfoPtr->maxX - dInfoPtr->x - data->rMargin;
	data->maxX = (data->wrapMode == TEXT_WRAPMODE_NONE) ? -1 : MAX(data->width, data->x);

	chunkPtr->x = data->x;

	if (data->tabIndex >= 0 && !data->tabApplied) {
	    data->tabChunkPtr = chunkPtr;
	}
	if (data->cursorChunkPtr) {
	    data->cursorChunkPtr->x = data->x;
	}
    }
}

static int
AtEndOfLine(
    TkTextSegment *segPtr,
    int offset)
{
    assert(segPtr);
    if (offset < segPtr->size) {
	return 0;
    }
    while ((segPtr = segPtr->nextPtr)) {
	switch (segPtr->typePtr->group) {
	case SEG_GROUP_CHAR:
	case SEG_GROUP_HYPHEN:
	case SEG_GROUP_IMAGE:
	case SEG_GROUP_WINDOW:
	    return 0;
	case SEG_GROUP_BRANCH:
	    if (segPtr->typePtr == &tkTextBranchType) {
		segPtr = segPtr->body.branch.nextPtr;
	    }
	    break;
	case SEG_GROUP_MARK:
	case SEG_GROUP_PROTECT:
	case SEG_GROUP_TAG:
	    break;
	}
    }
    return 1;
}

static int
IsDecimalPointPos(
    LayoutData *data,
    const TkTextSegment *segPtr,
    int offset)
{
    return segPtr == data->decimalPointPos.segPtr && offset == data->decimalPointPos.offset;
}

static int
IsNumericalEndPos(
    LayoutData *data,
    const TkTextSegment *segPtr,
    int offset)
{
    return segPtr == data->lastNumericalPos.segPtr && offset == data->lastNumericalPos.offset;
}

static int
LayoutChars(
    LayoutData *data,
    TkTextSegment *segPtr,
    int size,
    int byteOffset)
{
    const char *base = segPtr->body.chars + byteOffset;
    TkTextDispChunk *chunkPtr;
    int gotTab = 0;
    int adjustForNumericTab = 0;
    unsigned maxBytes;
    unsigned numBytes;
    int maxX;

    assert(size - byteOffset > 0); /* this will ensure maxBytes > 0 */
    assert(byteOffset < size);
    assert(segPtr->typePtr->layoutProc);

    LayoutMakeNewChunk(data);
    LayoutSetupChunk(data, segPtr);

    chunkPtr = data->chunkPtr;
    maxBytes = size - byteOffset;

    if (data->textPtr->showEndOfLine
	    && base[maxBytes - 1] == '\n'
	    && (data->textPtr->showEndOfText
		|| segPtr->sectionPtr->linePtr->nextPtr != TkBTreeGetLastLine(data->textPtr))) {
	maxBytes -= 1; /* now may become zero */
    }

    if (maxBytes == 0) {
	/*
	 * Can only happen if we are at end of logical line.
	 */

	if (segPtr->sectionPtr->linePtr->nextPtr != TkBTreeGetLastLine(data->textPtr)) {
	    segPtr = data->textPtr->dInfoPtr->endOfLineSegPtr;
	} else {
	    segPtr = data->textPtr->dInfoPtr->endOfTextSegPtr;
	}
	base = segPtr->body.chars;
	maxBytes = segPtr->size;
	chunkPtr->endOfLineSymbol = 1;
	byteOffset = 0;
    } else if (segPtr->typePtr != &tkTextHyphenType
		&& segPtr->sectionPtr) { /* ignore artifical segments (spelling changes) */
	if (data->wrapMode == TEXT_WRAPMODE_CODEPOINT) {
	    const char *brks = chunkPtr->brks;
	    unsigned i;

	    assert(brks);
	    assert(brks + maxBytes <= data->brks + data->breakInfo->brksSize);

	    for (i = 1; i < maxBytes; ++i) {
		assert(brks[i] <= LINEBREAK_INSIDEACHAR);
		if (brks[i] == LINEBREAK_MUSTBREAK) {
		    if (i < maxBytes - 2 && base[i] != '\n') {
			maxBytes = i + 1;
		    }
		    break;
		}
	    }
	}

	if (data->textPtr->hyphenate) {
	    const char *p = base;

	    /*
	     * Check whether the "tripleconsonant" rule has to be applied. This rule is
	     * very special, because in this case we are virtually doing the opposite.
	     * Instead of doing a spelling change when hyphenating, we are doing a spelling
	     * change when *not* hyphenating.
	     */

	    if (IsConsonant(*p)
		    && data->lastCharChunkPtr
		    && data->lastCharChunkPtr->prevCharChunkPtr
		    && data->lastChunkPtr
		    && data->lastChunkPtr->layoutProcs
		    && data->lastChunkPtr->layoutProcs->type == TEXT_DISP_HYPHEN
		    && *p == GetLastCharInChunk(data->lastCharChunkPtr->prevCharChunkPtr)
		    && *p == GetSecondLastCharInChunk(data->lastCharChunkPtr->prevCharChunkPtr)) {
		const char *nextCharPtr;

		if (maxBytes > 1) {
		    nextCharPtr = p + 1;
		} else {
		    const TkTextSegment *nextCharSegPtr = LayoutGetNextSegment(segPtr);
		    nextCharPtr = nextCharSegPtr ? nextCharSegPtr->body.chars : NULL;
		}

		/* For Norwegian it's required to consider 'j' as a vowel. */
		if (nextCharPtr && (nextCharPtr[0] == 'j' || IsUmlautOrVowel(nextCharPtr))) {
		    /*
		     * Probably we have to apply hyphen rule "tripleconsonant" to the first
		     * character after possible (but unapplied) hyphenation point.
		     */

		    const StyleValues *sValPtr = data->lastChunkPtr->stylePtr->sValuePtr;
		    int hyphenRules = FilterHyphenRules(sValPtr->hyphenRules, sValPtr->lang);

		    if (hyphenRules & (1 << TK_TEXT_HYPHEN_TRIPLE_CONSONANT)) {
			/* Schi(ff-f)ahrt -> Schi(ff)ahrt */
			byteOffset += 1;
			base += 1;
			maxBytes -= 1; /* now may become zero */
			chunkPtr->skipFirstChar = 1;
		    }
		}
	    }
	}

	if (data->trimSpaces) {
	    unsigned i;

	    for (i = 0; i < maxBytes; ++i) {
		if (base[i] == ' ' && base[i + 1] == ' ') {
		    while (base[i] == ' ') {
			++i;
		    }
		    maxBytes = i;
		    data->skipSpaces = 1;
		    break;
		}
	    }
	}

	/*
	 * See if there is a tab in the current chunk; if so, only layout
	 * characters up to (and including) the tab.
	 */

	if (data->justify == TK_TEXT_JUSTIFY_FULL) {
	    const char *p = base;
	    const char *e = p + maxBytes;

	    for ( ; p < e && !IsExpandableSpace(p); ++p) {
		if (*p == '\t') {
		    chunkPtr->numSpaces = 0;
		    maxBytes = p - base + 1;
		    gotTab = 1;
		    break;
		}
	    }
	    if (!gotTab && p < e) {
		assert(IsExpandableSpace(p));

		do {
		    chunkPtr->numSpaces += 1;

		    if (*p == '\t'
			    && (!data->tabArrayPtr || data->tabIndex < data->tabArrayPtr->numTabs)) {
			/*
			 * Don't expand spaces if we have numeric tabs.
			 */
			chunkPtr->numSpaces = 0;
			gotTab = 1;
			p += 1;
			break;
		    }

		    p = Tcl_UtfNext(p);
		} while (IsExpandableSpace(p));

		maxBytes = p - base;
	    }
	} else {
	    const char *p = base;
	    unsigned i;

	    /* TODO: direction of tabs should depend on gravity of insert mark?! */

	    for (i = 0; i < maxBytes; ++i, ++p) {
		if (*p == '\t') {
		    maxBytes = i + 1;
		    gotTab = 1;
		    break;
		}
	    }
	}
    }

    if (maxBytes == 0) {
	/*
	 * In seldom cases, if hyphenation is activated, we may have an empty
	 * chunk here, caused by the "tripleconsonant" rule. This chunk has to
	 * consume the skipped character.
	 */

	assert(size == 1);
	assert(chunkPtr->skipFirstChar);
	data->chunkPtr->layoutProcs = &layoutElideProcs;
	data->chunkPtr->numBytes = 1; /* must have size 1, see above */
	return 1;
    }

    maxX = data->maxX - data->tabSize;

    if (data->isNumericTab) {
	/*
	 * Only compute layout until decimal point, otherwise we cannot determine
	 * the correct line break position.
	 */

	const char *p = base;
	unsigned i;

	chunkPtr->integralPart = IsDecimalPointPos(data, segPtr, byteOffset);

	for (i = 0; i < maxBytes; ++i, ++p) {
	    if (IsNumericalEndPos(data, segPtr, byteOffset + i)
		    || IsDecimalPointPos(data, segPtr, byteOffset + i)) {
		adjustForNumericTab = 1;
		data->isNumericTab = 0;
		data->tabSize = 0;
		if (i > 0) {
		    if (*p == '\n' || *p == '\t') {
			i += 1;
		    }
		    maxBytes = i;
		    gotTab = (*p == '\t');
		}
		break;
	    }
	}

	if (data->shiftToNextLine
		&& data->numBytesSoFar > 0
		&& segPtr == data->shiftToNextLinePos.segPtr
		&& (int) (maxBytes + byteOffset) > data->shiftToNextLinePos.offset) {
	    int n = MIN(maxBytes + byteOffset - data->shiftToNextLinePos.offset, data->shiftToNextLine);

	    if (n > 0) {
		n = MIN(n, (int) maxBytes);
		data->shiftToNextLine -= n;
		if ((maxBytes -= n) == 0) {
		    data->isNumericTab = 0;
		    return 0;
		}
		gotTab = 0;
	    }
	    maxX = data->maxX;
	} else {
	    maxX = data->maxX - data->x;
	}
    } else if (data->isRightTab) {
	if (data->shiftToNextLine == 0) {
	    return 0;
	}
	if (data->numBytesSoFar > 0
		&& segPtr == data->shiftToNextLinePos.segPtr
		&& (int) (maxBytes + byteOffset) > data->shiftToNextLinePos.offset) {
	    int n = MIN(maxBytes + byteOffset - data->shiftToNextLinePos.offset, data->shiftToNextLine);

	    if (gotTab) {
		n += 1;
	    }
	    if (n > 0) {
		data->shiftToNextLine -= n;
		n = MIN(n, (int) maxBytes);
		if ((maxBytes -= n) == 0) {
		    data->isRightTab = 0;
		    return 0;
		}
		gotTab = 0;
	    }
	}
	maxX = data->maxX;
    }

    numBytes = LayoutMakeCharInfo(data, segPtr, byteOffset, maxBytes);

    if (segPtr->typePtr->layoutProc(&data->index, segPtr, byteOffset, maxX, numBytes,
	    data->countVisibleChunks == 0, data->wrapMode, data->textPtr->spaceMode, chunkPtr) == 0) {
	/*
	 * No characters from this segment fit in the window: this means
	 * we're at the end of the display line.
	 */

	chunkPtr->numSpaces = 0;
	return 0;
    }

    if (numBytes == chunkPtr->numBytes) {
	chunkPtr->numBytes = maxBytes;
	assert(maxBytes > 0);

	if (data->trimSpaces && base[maxBytes - 1] == ' ') {
	    data->skipSpaces = 1;
	}
    }

    assert(chunkPtr->numBytes + chunkPtr->skipFirstChar > 0);

    LayoutFinalizeCharInfo(data, gotTab);
    data->x += chunkPtr->width;

    if (!segPtr->sectionPtr && segPtr->typePtr != &tkTextHyphenType) {
	assert(segPtr == data->textPtr->dInfoPtr->endOfLineSegPtr
		|| segPtr == data->textPtr->dInfoPtr->endOfTextSegPtr);
	chunkPtr->numBytes = (chunkPtr->numBytes == maxBytes) ? 1 : 0;
	chunkPtr->breakIndex = chunkPtr->numBytes;
	chunkPtr->brks = NULL;
	maxBytes = 1;
    } else {
	chunkPtr->numBytes += chunkPtr->skipFirstChar;
    }

    data->numBytesSoFar += chunkPtr->numBytes;
    data->numSpaces += chunkPtr->numSpaces;
    data->countVisibleChunks += 1;

    if (chunkPtr->numBytes != maxBytes + chunkPtr->skipFirstChar) {
	return AtEndOfLine(segPtr, byteOffset + chunkPtr->numBytes); /* end of line display reached */
    }

    assert(!chunkPtr->brks
	    || (data->brks <= chunkPtr->brks
		&& chunkPtr->brks + chunkPtr->numBytes <= data->brks + data->breakInfo->brksSize));

    if (adjustForNumericTab) {
	if (data->lastChunkPtr) {
	    data->lastChunkPtr->nextPtr = data->chunkPtr; /* we need the complete chain. */
	}
	AdjustForTab(data);
	if (data->lastChunkPtr) {
	    data->lastChunkPtr->nextPtr = NULL; /* restore */
	}
	data->tabChunkPtr = NULL;
	if ((data->x = chunkPtr->x + chunkPtr->width) == data->maxX) {
	    return AtEndOfLine(segPtr, byteOffset + chunkPtr->numBytes);/* end of display line reached */
	}
    }

    /*
     * If we're at a new tab, adjust the layout for all the chunks pertaining to the
     * previous tab. Also adjust the amount of space left in the line to account for
     * space that will be eaten up by the tab.
     */

    if (gotTab) {
	data->isNumericTab = 0;

	if (data->tabIndex >= 0) {
	    if (data->lastChunkPtr) {
		data->lastChunkPtr->nextPtr = data->chunkPtr; /* we need the complete chain. */
	    }
	    AdjustForTab(data);
	    if (data->lastChunkPtr) {
		data->lastChunkPtr->nextPtr = NULL; /* restore */
	    }
	    data->tabChunkPtr = NULL;
	    data->x = chunkPtr->x + chunkPtr->width;
	}

	data->tabChunkPtr = chunkPtr;
	ComputeSizeOfTab(data, segPtr, chunkPtr->numBytes + byteOffset);

	if (data->maxX >= 0) {
	    switch (data->tabAlignment) {
	    case LEFT:
	    case CENTER:
		if (data->tabSize >= data->maxX - data->x) {
		    return 0; /* end of display line reached */
		}
		break;
	    case RIGHT:
		if (data->tabSize > data->maxX - data->x) {
		    return 0; /* end of display line reached */
		}
		if (data->displayLineNo == 0 && data->tabX >= 2*data->maxX) {
		    return 0; /* end of display line reached */
		}
		if (data->tabX > data->maxX) {
		    ComputeShiftForRightTab(data, segPtr, chunkPtr->numBytes + byteOffset);
		}
		break;
	    case NUMERIC:
		if (data->tabSize - data->maxX + data->x >= data->maxX) {
		    return 0; /* end of display line reached */
		}
		if (data->tabSize >= data->maxX - data->x) {
		    ComputeShiftForNumericTab(data, segPtr, chunkPtr->numBytes + byteOffset);
		}
		break;
	    }
	}
    }

    return 1;
}

static int
LayoutHyphen(
    LayoutData *data,
    TkTextSegment *segPtr)
{
    int rc;

    assert(segPtr->sectionPtr); /* don't works with artificial segments */

    if (data->textPtr->hyphenate) {
	LayoutMakeNewChunk(data);
	LayoutSetupChunk(data, segPtr);
	data->numBytesSoFar += segPtr->size;
	data->countVisibleChunks += 1;
	segPtr->body.hyphen.textSize = 0;
	data->chunkPtr->layoutProcs = &layoutHyphenProcs;
	data->chunkPtr->clientData = segPtr;
	data->chunkPtr->breakIndex = -1;
	data->chunkPtr->numBytes = segPtr->size;
	data->chunkPtr->hyphenRules = segPtr->body.hyphen.rules;
	segPtr->refCount += 1;
	rc = 1;
    } else {
	SetupHyphenChars(segPtr, 0);
	rc = LayoutChars(data, segPtr, segPtr->body.hyphen.textSize, 0);
	data->chunkPtr->numBytes = MIN(1u, data->chunkPtr->numBytes);
    }

    data->chunkPtr->breakIndex = data->chunkPtr->numBytes;
    return rc;
}

static int
LayoutEmbedded(
    LayoutData *data,
    TkTextSegment *segPtr)
{
    TkTextDispChunk *chunkPtr;
    int maxX;

    assert(segPtr->typePtr->layoutProc);

    LayoutMakeNewChunk(data);
    chunkPtr = data->chunkPtr;
    maxX = data->maxX - (data->isNumericTab ? data->x : data->tabSize);

    if (segPtr->typePtr->layoutProc(&data->index, segPtr, 0, maxX, 0, data->countVisibleChunks == 0,
	    data->wrapMode, data->textPtr->spaceMode, chunkPtr) != 1) {
	return 0;
    }

#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
    data->baseChunkPtr = NULL;
#endif
    LayoutSetupChunk(data, segPtr);
    data->numBytesSoFar += chunkPtr->numBytes;

    if (chunkPtr->width > 0) {
	data->x += chunkPtr->width;
	data->countVisibleChunks += 1;
	assert(chunkPtr->minHeight + chunkPtr->minAscent + chunkPtr->minDescent > 0);
    } else {
	assert(chunkPtr->minHeight == 0);
	assert(chunkPtr->minAscent == 0);
	assert(chunkPtr->minDescent == 0);
    }

    if (segPtr->typePtr->group == SEG_GROUP_IMAGE) {
	data->textPtr->dInfoPtr->countImages += 1;
    } else {
	data->textPtr->dInfoPtr->countWindows += 1;
    }

    return 1;
}

static int
LayoutMark(
    LayoutData *data,
    TkTextSegment *segPtr)
{
    int maxX;

    assert(segPtr->typePtr->layoutProc);

    if (segPtr != data->textPtr->insertMarkPtr) {
	return 0;
    }
    LayoutMakeNewChunk(data);

    maxX = data->maxX - (data->isNumericTab ? data->x : data->tabSize);
    segPtr->typePtr->layoutProc(&data->index, segPtr, 0, maxX, 0, data->countVisibleChunks == 0,
	    data->wrapMode, data->textPtr->spaceMode, data->chunkPtr);
    return 1;
}

static int
LayoutLogicalLine(
    LayoutData *data,
    DLine *dlPtr)
{
    const TkTextDispLineInfo *dispLineInfo = NULL;
    TkTextSegment *segPtr, *endPtr;
    Tcl_Size byteIndex, byteOffset;

    assert(!TkTextIsElided(&data->index));

    byteIndex = TkTextIndexGetByteIndex(&data->index);

    if (data->displayLineNo > 0) {
	dispLineInfo = TkBTreeLinePixelInfo(data->textPtr, data->logicalLinePtr)->dispLineInfo;
	/*
	 * It's possible that display line info not exists. But this can only happen if the
	 * content is out of date and will be re-computed later. In such a case the next block
	 * of code can be skipped. This happens only in rare cases, for example when
	 * TextBlinkProc() has been invoked.
	 */
    }

    if (dispLineInfo) {
	const TkTextDispLineEntry *dispLineEntry = dispLineInfo->entry + (data->displayLineNo - 1);

	if (dispLineEntry->tabIndex) {
	    const TextDInfo *dInfoPtr = data->textPtr->dInfoPtr;
	    const StyleValues *sValuePtr;
	    TextStyle *stylePtr;
	    Tcl_Size byteOffset1;

	    segPtr = TkTextIndexGetContentSegment(&data->index, &byteOffset1);
	    stylePtr = GetStyle(data->textPtr, segPtr);
	    sValuePtr = stylePtr->sValuePtr;
	    data->tabArrayPtr = sValuePtr->tabArrayPtr;
	    data->tabStyle = sValuePtr->tabStyle;
	    data->tabIndex = dispLineEntry->tabIndex - 2;
	    data->width = dInfoPtr->maxX - dInfoPtr->x - data->rMargin;
	    data->x = data->paragraphStart ? sValuePtr->lMargin1 : sValuePtr->lMargin2;
	    data->maxX = MAX(data->width, data->x);
	    FreeStyle(data->textPtr, stylePtr);
	    ComputeSizeOfTab(data, segPtr, byteOffset1);
	    data->tabApplied = dispLineEntry->tabApplied;

	    switch (data->tabAlignment) {
	    case LEFT:
		data->tabSize = 0;
		data->tabApplied = 1;
		break;
	    case CENTER:
		if (data->tabApplied) {
		    data->tabSize = 0;
		}
		break;
	    case RIGHT:
		data->tabSize = 0;
		if (data->tabApplied) {
		    data->adjustFirstChunk = 0;
		}
		break;
	    case NUMERIC:
		if (!data->tabApplied) {
		    if (IsDecimalPointPos(data, segPtr, byteOffset1)) {
			data->tabSize = 0;
			data->isNumericTab = 0;
		    }
		    if (data->maxX >= 0 && data->tabSize >= data->maxX - data->x) {
			data->tabX += data->maxX;
			ComputeShiftForNumericTab(data, segPtr, byteOffset1);
			if (data->lengthOfFractional == data->shiftToNextLine) {
			    data->shiftToNextLine = 0;
			}
		    }
		}
		break;
	    }
	}

	if (data->textPtr->hyphenate) {
	    Tcl_Size byteOffset1;
	    int hyphenRule;

	    segPtr = TkTextIndexGetContentSegment(&data->index, &byteOffset1);
	    hyphenRule = dispLineEntry->hyphenRule;

	    switch (hyphenRule) {
	    case TK_TEXT_HYPHEN_REPEAT:
	    case TK_TEXT_HYPHEN_TREMA:
	    case TK_TEXT_HYPHEN_DOUBLE_DIGRAPH: {
		Tcl_Size numBytes = 0; /* prevents compiler warning */
		TkTextSegment *nextCharSegPtr;
		char buf[1];
		int cont;

		/*
		 * We have to realize spelling changes.
		 */

		switch (hyphenRule) {
		case TK_TEXT_HYPHEN_REPEAT:
		    buf[0] = '-';
		    numBytes = 1;
		    break;
		case TK_TEXT_HYPHEN_TREMA:
		    assert(UCHAR(segPtr->body.chars[byteOffset1]) == 0xc3);
		    buf[0] = UmlautToVowel(ConvertC3Next(segPtr->body.chars[byteOffset1 + 1]));
		    numBytes = 2;
		    break;
		case TK_TEXT_HYPHEN_DOUBLE_DIGRAPH:
		    buf[0] = segPtr->body.chars[0];
		    numBytes = 1;
		    break;
		}
		nextCharSegPtr = TkBTreeMakeCharSegment(buf, 1, segPtr->tagInfoPtr);
		cont = LayoutChars(data, nextCharSegPtr, 1, 0);
		TkBTreeFreeSegment(nextCharSegPtr);
		data->chunkPtr->numBytes = numBytes;
		if (!cont) {
		    LayoutFinalizeChunk(data);
		    return 0;
		}
		TkrTextIndexForwBytes(data->textPtr, &data->index,
			data->chunkPtr->numBytes, &data->index);
		byteIndex += data->chunkPtr->numBytes;
		break;
	    }
	    }
	}
    }

    segPtr = TkTextIndexGetFirstSegment(&data->index, &byteOffset);
    endPtr = data->textPtr->endMarker;

    if (segPtr->typePtr == &tkTextLinkType) {
	segPtr = segPtr->nextPtr;
    }

    /*
     * Each iteration of the loop below creates one TkTextDispChunk for the
     * new display line. The line will always have at least one chunk (for the
     * newline character at the end, if there's nothing else available).
     */

    while (1) {
	if (segPtr->typePtr == &tkTextCharType) {
	    if (data->skipSpaces) {
		if (segPtr->body.chars[byteOffset] == ' ') {
		    TkTextIndex index = data->index;
		    int offset = byteOffset;

		    while (segPtr->body.chars[byteOffset] == ' ') {
			byteOffset += 1;
		    }
		    TkrTextIndexForwBytes(data->textPtr, &index, byteOffset - offset, &data->index);
		    LayoutSkipBytes(data, dlPtr, &index, &data->index);
		    byteIndex = TkTextIndexGetByteIndex(&data->index);
		}
		data->skipSpaces = 0;
	    }
	    if (segPtr->size > byteOffset) {
		if (!LayoutChars(data, segPtr, segPtr->size, byteOffset)) {
		    /* finished with this display line */
		    LayoutFinalizeChunk(data);
		    return 0;
		}
		assert(data->chunkPtr);
		byteIndex += data->chunkPtr->numBytes;
		/* NOTE: byteOffset may become larger than segPtr->size because of end of line symbol. */
		if ((byteOffset += data->chunkPtr->numBytes) >= segPtr->size) {
		    segPtr = segPtr->nextPtr;
		    byteOffset = 0;
		}
	    } else {
		assert(segPtr->size == byteOffset);
		segPtr = segPtr->nextPtr;
		byteOffset = 0;
	    }
	} else {
	    switch (segPtr->typePtr->group) {
	    case SEG_GROUP_HYPHEN:
		if (!LayoutHyphen(data, segPtr)) {
		    /* finished with this display line */
		    LayoutFinalizeChunk(data);
		    return 0;
		}
		byteIndex += segPtr->size;
		data->skipSpaces = 0;
		break;
	    case SEG_GROUP_IMAGE:
	    case SEG_GROUP_WINDOW:
		if (!LayoutEmbedded(data, segPtr)) {
		    /* finished with this display line */
		    LayoutFinalizeChunk(data);
		    return 0;
		}
		byteIndex += segPtr->size;
		data->skipSpaces = 0;
		break;
	    case SEG_GROUP_MARK:
		if (segPtr == endPtr) {
		    /*
		     * We need a final chunk containing the final newline, otherwise x position
		     * lookup will not work. Here we will not use LayoutSkipBytes() for the bytes
		     * between current position and last char in line, because this would require
		     * an inconsistent index, and it's easier to avoid this. It's only a single
		     * newline which terminates the line, so no bad things will happen if we omit
		     * this skip-chunk.
		     */
		    segPtr = segPtr->sectionPtr->linePtr->lastPtr;
		    LayoutChars(data, segPtr, segPtr->size, segPtr->size - 1);
		} else {
		    if (LayoutMark(data, segPtr)) {
			data->cursorChunkPtr = data->chunkPtr;
		    }
		    assert(segPtr->size == 0);
		}
		break;
	    case SEG_GROUP_BRANCH: {
		TkTextIndex index = data->index;
		assert(segPtr->typePtr == &tkTextBranchType);
		assert(segPtr->size == 0);
		TkTextIndexSetSegment(&data->index, segPtr = segPtr->body.branch.nextPtr);
		LayoutSkipBytes(data, dlPtr, &index, &data->index);
		byteIndex = TkTextIndexGetByteIndex(&data->index);
		break;
	    }
	    case SEG_GROUP_PROTECT:
	    case SEG_GROUP_TAG:
	    case SEG_GROUP_CHAR:
		assert(!"unexpected segment type");
		break;
	    }
	    segPtr = segPtr->nextPtr;
	    byteOffset = 0;
	}
	if (!segPtr) {
	    LayoutFinalizeChunk(data);
	    return 1;
	}
	TkTextIndexSetPosition(&data->index, byteIndex, segPtr);
    }

    return 0; /* never reached */
}

static void
LayoutDestroyChunks(
    LayoutData *data)
{
    TkTextDispChunk *chunkPtr = data->lastChunkPtr;
    TextDInfo *dInfoPtr;

    if (chunkPtr == data->breakChunkPtr) {
	return;
    }

    dInfoPtr = data->textPtr->dInfoPtr;

    /*
     * We have to destroy the chunks backward, because the context support
     * is expecting this.
     */

    for ( ; chunkPtr != data->breakChunkPtr; chunkPtr = chunkPtr->prevPtr) {
	assert(chunkPtr != data->firstCharChunkPtr);
	assert(chunkPtr->layoutProcs);
	assert(!chunkPtr->sectionPtr);

	data->numSpaces -= chunkPtr->numSpaces;
	data->dispLineOffset -= chunkPtr->numBytes;
	data->numBytesSoFar -= chunkPtr->numBytes;
	data->countChunks -= 1;
	if (chunkPtr->width > 0) {
	    data->countVisibleChunks -= 1;
	}

	if (chunkPtr == data->cursorChunkPtr) {
	    data->cursorChunkPtr = NULL;
	} else if (chunkPtr == data->lastCharChunkPtr) {
	    data->lastCharChunkPtr = chunkPtr->prevCharChunkPtr;
	}
	if (chunkPtr->layoutProcs->type == TEXT_DISP_IMAGE) {
	    dInfoPtr->countImages -= 1;
	} else if (chunkPtr->layoutProcs->type == TEXT_DISP_WINDOW) {
	    dInfoPtr->countWindows -= 1;
	}
	LayoutUndisplay(data, chunkPtr);
	LayoutReleaseChunk(data->textPtr, chunkPtr);
	DEBUG(chunkPtr->stylePtr = NULL);
    }

    data->lastChunkPtr->nextPtr = dInfoPtr->chunkPoolPtr;
    dInfoPtr->chunkPoolPtr = data->breakChunkPtr->nextPtr;
    dInfoPtr->chunkPoolPtr->prevPtr = NULL;
    data->breakChunkPtr->nextPtr = NULL;
    data->lastChunkPtr = data->breakChunkPtr;
    data->chunkPtr = NULL;
    data->x = data->lastChunkPtr->x + data->lastChunkPtr->width;
#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
    data->baseChunkPtr = data->breakChunkPtr->baseChunkPtr;
#endif
}

static void
LayoutBreakLine(
    LayoutData *data,
    const TkTextIndex *indexPtr)	/* Index of display line start. */
{
    if (!data->breakChunkPtr) {
	/*
	 * This code makes sure that we don't accidentally display chunks with
	 * no characters at the end of the line (such as the insertion
	 * cursor). These chunks belong on the next line. So, throw away
	 * everything after the last chunk that has characters in it.
	 */

	data->breakChunkPtr = data->lastCharChunkPtr;
    }

    while (IsHyphenChunk(data->breakChunkPtr)) {
	TkTextDispChunk *hyphenChunkPtr;
	TkTextDispChunk *prevChunkPtr;
	TkTextDispChunk *nextChunkPtr;

	/*
	 * This can only happen if the breaking chunk is a hyphen segment.
	 * So try to hyphenate at this point. Normally this will succeed,
	 * but in seldom cases the hyphenation does not fit, then we have
	 * to search back for the next breaking chunk.
	 */

	hyphenChunkPtr = data->breakChunkPtr;
	prevChunkPtr = hyphenChunkPtr->prevCharChunkPtr;
	nextChunkPtr = LayoutGetNextCharChunk(hyphenChunkPtr);

	if (prevChunkPtr && nextChunkPtr) {
	    TkTextSegment *hyphenSegPtr = (TkTextSegment *)hyphenChunkPtr->clientData;

	    LayoutApplyHyphenRules(data, prevChunkPtr, hyphenChunkPtr, nextChunkPtr);
	    data->breakChunkPtr = prevChunkPtr;
	    LayoutDestroyChunks(data);

	    if (data->decreaseNumBytes > 0) {
		TkTextIndex index = *indexPtr;
		TkTextSegment *segPtr;
		unsigned newNumBytes = 0;
		unsigned numBytes;

		/*
		 * We need a new layout of the preceding char chunk because of possible
		 * spelling changes.
		 */

		while (data->decreaseNumBytes >= prevChunkPtr->numBytes
			&& prevChunkPtr != data->firstCharChunkPtr) {
		    data->decreaseNumBytes -= prevChunkPtr->numBytes;
		    newNumBytes += prevChunkPtr->numBytes;
		    prevChunkPtr = prevChunkPtr->prevPtr;
		}

		data->breakChunkPtr = prevChunkPtr;
		LayoutDestroyChunks(data);
		newNumBytes += prevChunkPtr->numBytes;

		if (data->decreaseNumBytes > 0) {
		    segPtr = CHAR_CHUNK_GET_SEGMENT(prevChunkPtr);
		    prevChunkPtr->numBytes -= data->decreaseNumBytes;
		    numBytes = prevChunkPtr->numBytes;
		    assert(prevChunkPtr->layoutProcs);
		    LayoutUndisplay(data, prevChunkPtr);
		    data->chunkPtr = prevChunkPtr;
		    LayoutMakeCharInfo(data, segPtr, prevChunkPtr->segByteOffset, numBytes);
		    TkrTextIndexForwBytes(data->textPtr, &index, prevChunkPtr->byteOffset, &index);
		    segPtr->typePtr->layoutProc(&index, segPtr, prevChunkPtr->segByteOffset,
			    data->maxX, numBytes, 0, data->wrapMode, data->textPtr->spaceMode,
			    prevChunkPtr);
		    LayoutFinalizeCharInfo(data, 0); /* second parameter doesn't matter here */

		    if (prevChunkPtr->numBytes != numBytes && prevChunkPtr != data->firstCharChunkPtr) {
			/*
			 * The content doesn't fits into the display line (but it must fit if
			 * this is the first char chunk).
			 */
			hyphenSegPtr = NULL;
		    }
		}

		prevChunkPtr->numBytes = newNumBytes;
		data->chunkPtr = NULL;
	    }

	    if (hyphenSegPtr) {
		int maxX = data->maxX;
		int fits;

		data->x = prevChunkPtr->x + prevChunkPtr->width;
		if (prevChunkPtr == data->firstCharChunkPtr && prevChunkPtr->breakIndex <= 0) {
		    data->maxX = INT_MAX; /* The hyphen must be shown. */
		}
		fits = LayoutChars(data, hyphenSegPtr, hyphenSegPtr->body.hyphen.textSize, 0);
		assert(!fits || (int) data->chunkPtr->numBytes == hyphenSegPtr->body.hyphen.textSize);
		hyphenChunkPtr = data->chunkPtr;
		data->maxX = maxX;

		if (fits) {
		    /* The hyphen fits, so we're done. */
		    LayoutFinalizeChunk(data);
		    hyphenChunkPtr->numBytes = 1 + data->increaseNumBytes;
		    return;
		}

		LayoutFreeChunk(data);
		data->hyphenRule = 0;
	    }
	}

	/*
	 * We couldn't hyphenate, so search for next candidate for wrapping.
	 */

	if (IsHyphenChunk(data->breakChunkPtr)) {
	    if (!(data->breakChunkPtr = data->breakChunkPtr->prevPtr)) {
		return;
	    }
	}
	if (data->breakChunkPtr->breakIndex <= 0) {
	    do {
		if (!(data->breakChunkPtr = data->breakChunkPtr->prevPtr)) {
		    return;
		}
	    } while (data->breakChunkPtr->breakIndex <= 0 && !IsHyphenChunk(data->breakChunkPtr));
	}

	data->chunkPtr = NULL;
    }

    /*
     * Now check if we must break because the line length have been exceeded. At this point
     * hyphenation is not involved.
     */

    if (data->breakChunkPtr
	    && (data->lastChunkPtr != data->breakChunkPtr
		|| (data->lastChunkPtr->breakIndex > 0
		    && data->lastChunkPtr->breakIndex != (int) data->lastChunkPtr->numBytes))) {
	unsigned addNumBytes = 0;

	LayoutDestroyChunks(data);

	if (data->breakChunkPtr->breakIndex > 0 && data->breakChunkPtr->numSpaces > 0) {
	    const TkTextDispChunk *breakChunkPtr = data->breakChunkPtr;
	    const CharInfo *ciPtr = (const CharInfo *)breakChunkPtr->clientData;
	    const char *p = ciPtr->u.chars + ciPtr->baseOffset + breakChunkPtr->breakIndex;
	    const char *q = Tcl_UtfPrev(p, ciPtr->u.chars + ciPtr->baseOffset);

	    if (IsExpandableSpace(q)
		    && !(breakChunkPtr->wrappedAtSpace
			&& breakChunkPtr->breakIndex == (int) breakChunkPtr->numBytes)) {
		addNumBytes = p - q;
		data->breakChunkPtr->breakIndex -= addNumBytes;
		data->breakChunkPtr->numSpaces -= 1;
		data->numSpaces -= 1;
	    }
	}

	if (data->breakChunkPtr->breakIndex != (int) data->breakChunkPtr->numBytes) {
	    TkTextSegment *segPtr;
	    TkTextDispChunk *chunkPtr = data->breakChunkPtr;
	    TkTextIndex index = *indexPtr;

	    LayoutUndisplay(data, chunkPtr);
	    data->chunkPtr = chunkPtr;
	    TkrTextIndexForwBytes(data->textPtr, &index, chunkPtr->byteOffset, &index);
	    segPtr = TkTextIndexGetContentSegment(&index, NULL);
	    LayoutMakeCharInfo(data, segPtr, chunkPtr->segByteOffset, data->breakChunkPtr->breakIndex);
	    segPtr->typePtr->layoutProc(&index, segPtr, chunkPtr->segByteOffset, data->maxX,
		    data->breakChunkPtr->breakIndex, 0, data->wrapMode, data->textPtr->spaceMode,
		    chunkPtr);
	    LayoutFinalizeCharInfo(data, 0); /* second parameter doesn't matter here */
	    LayoutDoWidthAdjustmentForContextDrawing(data);
	    chunkPtr->numBytes += addNumBytes;

	    if (chunkPtr->skipFirstChar) {
		chunkPtr->numBytes += 1;
	    }
	}
    }

    /*
     * Remove all the empty chunks at end of line. In this way we avoid to have
     * an insert cursur chunk at end of line, which should belong to the next line.
     */

    if (data->lastChunkPtr->numBytes == 0) {
	data->breakChunkPtr = data->breakChunkPtr->prevPtr;
	assert(data->breakChunkPtr);
	while (data->breakChunkPtr->numBytes == 0) {
	    data->breakChunkPtr = data->breakChunkPtr->prevPtr;
	    assert(data->breakChunkPtr);
	}
	LayoutDestroyChunks(data);
    }
}

static void
LayoutFullJustification(
    LayoutData *data,
    DLine *dlPtr)
{
    TkTextDispChunk *chunkPtr;
    TkTextDispChunk *nextChunkPtr;
    unsigned numSpaces;
    int remainingPixels;
    int shiftX;

    numSpaces = data->numSpaces;
    remainingPixels = data->maxX - dlPtr->length;

    if (numSpaces == 0 || remainingPixels <= 0) {
	return;
    }

    shiftX = 0;
    chunkPtr = dlPtr->chunkPtr;

    while ((nextChunkPtr = chunkPtr->nextPtr)) {
	if (chunkPtr->numSpaces > 0) {
	    unsigned expand = 0;
	    unsigned i;

	    assert(IsCharChunk(chunkPtr));

	    for (i = 0; i < chunkPtr->numSpaces; ++i) {
		unsigned space;

		assert(numSpaces > 0);
		space = (remainingPixels + numSpaces - 1)/numSpaces;
		expand += space;
		remainingPixels -= space;
		numSpaces -= 1;
	    }

	    shiftX += expand;
	    chunkPtr->width += expand;
	    chunkPtr->additionalWidth = expand;
	}

	nextChunkPtr->x += shiftX;
	chunkPtr = nextChunkPtr;
    }
}

static int
LayoutPrevDispLineEndsWithSpace(
    const TkText *textPtr,
    const TkTextSegment *segPtr,
    int offset)
{
    assert(segPtr);
    assert(offset < segPtr->size);

    if (TkTextSegmentIsElided(textPtr, segPtr)) {
	if (!(segPtr = TkBTreeFindStartOfElidedRange(textPtr->sharedTextPtr, textPtr, segPtr))) {
	    return 0;
	}
	offset = -1;
    }

    if (offset == -1) {
	while (1) {
	    if (!(segPtr = segPtr->prevPtr)) {
		return 0;
	    }
	    switch ((int) segPtr->typePtr->group) {
	    case SEG_GROUP_CHAR:
		return segPtr->body.chars[segPtr->size - 1] == ' ';
	    case SEG_GROUP_BRANCH:
		if (segPtr->typePtr == &tkTextLinkType) {
		    segPtr = segPtr->body.link.prevPtr;
		}
		break;
	    case SEG_GROUP_MARK:
		/* skip */
		break;
	    case SEG_GROUP_HYPHEN:
	    case SEG_GROUP_IMAGE:
	    case SEG_GROUP_WINDOW:
		return 0;
	    }
	}
    }

    return segPtr->typePtr == &tkTextCharType && segPtr->body.chars[offset] == ' ';
}

static DLine *
LayoutDLine(
    const TkTextIndex *indexPtr,/* Beginning of display line. May not necessarily point to
				 * a character segment. */
    unsigned displayLineNo)	/* Display line number of logical line, needed for caching. */
{
    TextDInfo *dInfoPtr;
    DLine *dlPtr;
    TkText *textPtr;
    StyleValues *sValPtr;
    TkTextDispChunk *chunkPtr;
    TkTextDispChunkSection *sectionPtr;
    TkTextDispChunkSection *prevSectionPtr;
    TkTextSegment *segPtr;
    LayoutData data;
    int endOfLogicalLine;
    int isStartOfLine;
    int ascent, descent, leading, jIndent;
    unsigned countChunks;
    unsigned chunksPerSection;
    int length;
    Tcl_Size offset;

    assert((displayLineNo == 0) ==
	    (IsStartOfNotMergedLine(indexPtr) || TkTextIndexIsStartOfText(indexPtr)));
    assert(indexPtr);
    assert(TkTextIndexGetLine(indexPtr));

    DEBUG(stats.numLayouted += 1);

    textPtr = indexPtr->textPtr;
    assert(textPtr);
    dInfoPtr = textPtr->dInfoPtr;

    /*
     * Create and initialize a new DLine structure.
     */

    if (dInfoPtr->dLinePoolPtr) {
	dlPtr = dInfoPtr->dLinePoolPtr;
	dInfoPtr->dLinePoolPtr = dlPtr->nextPtr;
    } else {
	dlPtr = (DLine *)ckalloc(sizeof(DLine));
	DEBUG_ALLOC(tkTextCountNewDLine++);
    }
    dlPtr = (DLine *)memset(dlPtr, 0, sizeof(DLine));
    dlPtr->flags = NEW_LAYOUT|OLD_Y_INVALID;
    dlPtr->index = *indexPtr;
    TkTextIndexMakePersistent(&dlPtr->index);
    dlPtr->displayLineNo = displayLineNo;
    TkTextIndexToByteIndex(&dlPtr->index);
    isStartOfLine = TkTextIndexIsStartOfLine(&dlPtr->index);

    /*
     * Initialize layout data.
     */

    memset(&data, 0, sizeof(data));
    data.dlPtr = dlPtr;
    data.index = dlPtr->index;
    data.justify = textPtr->justify;
    data.tabIndex = -1;
    data.tabStyle = TK_TEXT_TABSTYLE_TABULAR;
    data.wrapMode = textPtr->wrapMode;
    data.paragraphStart = displayLineNo == 0;
    data.trimSpaces = textPtr->spaceMode == TEXT_SPACEMODE_TRIM;
    data.displayLineNo = displayLineNo;
    data.textPtr = textPtr;

    if (data.paragraphStart) {
	dlPtr->flags |= PARAGRAPH_START;
	data.logicalLinePtr = TkTextIndexGetLine(indexPtr);
	data.byteOffset = TkTextIndexGetByteIndex(indexPtr);
    } else {
	TkTextLine *linePtr = TkTextIndexGetLine(indexPtr);
	TkTextIndex index2 = *indexPtr;

	data.logicalLinePtr = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
	DEBUG(TkTextIndexSetPeer(&index2, NULL)); /* allow index outside of peer */
	TkTextIndexSetByteIndex2(&index2, data.logicalLinePtr, 0);
	data.byteOffset = TkTextIndexCountBytes(&index2, indexPtr);
    }

    segPtr = TkTextIndexGetContentSegment(indexPtr, &offset);
    data.skipSpaces = data.trimSpaces && LayoutPrevDispLineEndsWithSpace(textPtr, segPtr, offset - 1);

    /*
     * Skip elided region.
     */

    if (TkTextSegmentIsElided(textPtr, segPtr)) {
	segPtr = TkBTreeFindEndOfElidedRange(textPtr->sharedTextPtr, textPtr, segPtr);
	TkTextIndexSetSegment(&data.index, segPtr);
	LayoutSkipBytes(&data, dlPtr, indexPtr, &data.index);

	/*
	 * NOTE: it is possible that we have reached now the end of text. This is
	 * the only case that an empty display line can be produced, which will be
	 * linked into the list of display lines. It's only a single superfluous
	 * line, so we can live with that.
	 */

	if (!textPtr->showEndOfText && TkTextIndexIsEndOfText(&data.index)) {
	    assert(data.chunkPtr);
	    assert(!data.chunkPtr->nextPtr);
	    dlPtr->byteCount = data.chunkPtr->numBytes;
	    LayoutFreeChunk(&data);
	    LayoutUpdateLineHeightInformation(&data, dlPtr, data.logicalLinePtr, 1, 0, 0, 0);
	    return dlPtr;
	}
    }

    endOfLogicalLine = LayoutLogicalLine(&data, dlPtr);
    assert(data.numBytesSoFar > 0);

    /*
     * We're at the end of the display line. Throw away everything after the
     * most recent word break, if there is one; this may potentially require
     * the last chunk to be layed out again. Also perform hyphenation, if
     * enabled, this probably requires the re-layout of a few chunks at the
     * end of the line.
     */

    if (!endOfLogicalLine) {
	LayoutBreakLine(&data, &dlPtr->index);
    }

    if (data.textPtr->hyphenate) {
	TkTextDispChunk *chunkPtr1 = data.firstChunkPtr->nextPtr;

	/*
	 * Remove all unused hyphen segments, this will speed up the display process,
	 * because this removal will be done only one time, but the display process
	 * may iterate over the chunks several times.
	 */

	while (chunkPtr1) {
	    TkTextDispChunk *nextChunkPtr = chunkPtr1->nextPtr;

	    if (nextChunkPtr && chunkPtr1->width == 0 && chunkPtr1 != data.cursorChunkPtr) {
		chunkPtr1->prevPtr->numBytes += chunkPtr1->numBytes;

		if ((chunkPtr1->prevPtr->nextPtr = nextChunkPtr)) {
		    nextChunkPtr->prevPtr = chunkPtr1->prevPtr;
		    data.chunkPtr = chunkPtr1;
		    LayoutFreeChunk(&data);
		}
	    }

	    chunkPtr1 = nextChunkPtr;
	}
    }

    /*
     * This has to be done after LayoutBreakLine.
     */

    dlPtr->chunkPtr = data.firstChunkPtr;
    dlPtr->lastChunkPtr = data.lastChunkPtr;
    dlPtr->cursorChunkPtr = data.cursorChunkPtr;
    dlPtr->firstCharChunkPtr = data.firstCharChunkPtr;
    dlPtr->breakInfo = data.breakInfo;
    dlPtr->invisible = data.countVisibleChunks == 0;

    /*
     * Make tab adjustments for the last tab stop, if there is one.
     */

    if (data.tabIndex >= 0) {
	AdjustForTab(&data);
    }

    /*
     * Make one more pass over the line to recompute various things like its
     * height, length, and total number of bytes. Also modify the x-locations
     * of chunks to reflect justification.
     */

    if (data.wrapMode == TEXT_WRAPMODE_NONE) {
	data.maxX = dInfoPtr->maxX - dInfoPtr->x - data.rMargin;
    }
    length = dlPtr->length = data.lastChunkPtr->x + data.lastChunkPtr->width;
    if (data.wrapMode != TEXT_WRAPMODE_NONE) {
	length = MIN(length, data.maxX);
    }

    jIndent = 0;

    switch (data.justify) {
    default:
	/* no action */
	break;
    case TK_TEXT_JUSTIFY_RIGHT:
	jIndent = data.maxX - length;
	break;
    case TK_TEXT_JUSTIFY_FULL:
	if (!endOfLogicalLine) {
	    LayoutFullJustification(&data, dlPtr);
	}
	break;
    case TK_TEXT_JUSTIFY_CENTER:
	jIndent = (data.maxX - length)/2;
	break;
    }

    ascent = descent = 0;
    sectionPtr = prevSectionPtr = NULL;
    chunksPerSection = (data.countChunks + MAX_SECTIONS_PER_LINE - 1)/MAX_SECTIONS_PER_LINE;
    chunksPerSection = MAX(chunksPerSection, MIN_CHUNKS_PER_SECTION);
    countChunks = chunksPerSection - 1;

    for (chunkPtr = dlPtr->chunkPtr; chunkPtr; chunkPtr = chunkPtr->nextPtr) {
	if (++countChunks == chunksPerSection) {
	    /*
	     * Create next section.
	     */
	    sectionPtr = LayoutNewSection(dInfoPtr);
	    if (prevSectionPtr) {
		prevSectionPtr->nextPtr = sectionPtr;
	    }
	    sectionPtr->chunkPtr = chunkPtr;
	    prevSectionPtr = sectionPtr;
	    countChunks = 0;
	}
	chunkPtr->sectionPtr = sectionPtr;
	sectionPtr->numBytes += chunkPtr->numBytes;
	dlPtr->byteCount += chunkPtr->numBytes;
	chunkPtr->x += jIndent;
	ascent = MAX(ascent, chunkPtr->minAscent);
	descent = MAX(descent, chunkPtr->minDescent);
	dlPtr->height = MAX(dlPtr->height, chunkPtr->minHeight);
	dlPtr->width += chunkPtr->width;
	sValPtr = chunkPtr->stylePtr->sValuePtr;
	if (sValPtr->borderWidth > 0 && sValPtr->relief != TK_RELIEF_FLAT) {
	    dlPtr->flags |= HAS_3D_BORDER;
	}
    }

    leading = ascent + descent;

    if (dlPtr->height < leading) {
	dlPtr->height = leading;
	dlPtr->baseline = ascent;
    } else {
	dlPtr->baseline = ascent + (dlPtr->height - leading)/2;
    }

    sValPtr = dlPtr->chunkPtr->stylePtr->sValuePtr;

    dlPtr->spaceAbove = isStartOfLine ? sValPtr->spacing1 : (sValPtr->spacing2 + 1)/2;
    dlPtr->spaceBelow = endOfLogicalLine ? sValPtr->spacing3 : sValPtr->spacing2/2;
    dlPtr->height += dlPtr->spaceAbove + dlPtr->spaceBelow;
    dlPtr->baseline += dlPtr->spaceAbove;
    /* line length may have changed because of justification */
    dlPtr->length = data.lastChunkPtr->x + jIndent + data.lastChunkPtr->width;

    if (data.tabStyle == TK_TEXT_TABSTYLE_WORDPROCESSOR) {
	data.tabIndex = -1;
    }
    LayoutUpdateLineHeightInformation(&data, dlPtr, data.logicalLinePtr,
	    endOfLogicalLine, data.hyphenRule, data.tabIndex + 1, data.tabApplied);

    return dlPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * CheckIfLineMetricIsUpToDate --
 *
 *	This function wil be invoked after update of line metric calculations.
 *	It checks whether the all line metrics are up-to-date, and will
 *	invoke the appropriate actions.
 *
 * Results:
 *	Returns true if the widget has not been deleted by receiver of the
 *	triggered callback.
 *
 * Side effects:
 *	Firing the <<WidgetViewSync>> event, scrollbar update, and resetting
 *	some states.
 *
 *----------------------------------------------------------------------
 */

static int
TriggerWatchCursor(
    TkText *textPtr)
{
    if (textPtr->watchCmd) {
	TextDInfo *dInfoPtr = textPtr->dInfoPtr;
	char buf[2][2*TK_POS_CHARS + 2];

	if (memcmp(&dInfoPtr->curPixelPos, &dInfoPtr->prevPixelPos, sizeof(PixelPos)) != 0) {
	    textPtr->sharedTextPtr->triggerWatchCmd = 0;
	    snprintf(buf[0], sizeof(buf[0]), "@%d,%d",
		    dInfoPtr->curPixelPos.xFirst, dInfoPtr->curPixelPos.yFirst);
	    snprintf(buf[1], sizeof(buf[1]), "@%d,%d",
		    dInfoPtr->curPixelPos.xLast, dInfoPtr->curPixelPos.yLast);
	    TkTextTriggerWatchCmd(textPtr, "view", buf[0], buf[1], NULL, NULL, NULL, 0);
	    memcpy(&textPtr->dInfoPtr->prevPixelPos, &textPtr->dInfoPtr->curPixelPos, sizeof(PixelPos));
	    textPtr->sharedTextPtr->triggerWatchCmd = 1;
	}
    }

    return !(textPtr->flags & DESTROYED);
}

static void
UpdateLineMetricsFinished(
    TkText *textPtr,
    int sendImmediately)
{
    assert(TkRangeListIsEmpty(textPtr->dInfoPtr->lineMetricUpdateRanges));

    textPtr->dInfoPtr->flags &= ~(ASYNC_UPDATE|ASYNC_PENDING);
    textPtr->dInfoPtr->pendingUpdateLineMetricsFinished = 0;

    TkTextRunAfterSyncCmd(textPtr);

    /*
     * Fire the <<WidgetViewSync>> event since the widget view is in sync
     * with its internal data (actually it will be after the next trip
     * through the event loop, because the widget redraws at idle-time).
     */

    TkTextGenerateWidgetViewSyncEvent(textPtr, sendImmediately);
}

static void
RunUpdateLineMetricsFinished(
    void *clientData)
{
    TkText *textPtr = (TkText *) clientData;

    if (!(textPtr->flags & DESTROYED)) {
	textPtr->dInfoPtr->pendingUpdateLineMetricsFinished = 0;
	if (TkRangeListIsEmpty(textPtr->dInfoPtr->lineMetricUpdateRanges)) {
	    UpdateLineMetricsFinished(textPtr, 1);
	}
    }
}

static void
CheckIfLineMetricIsUpToDate(
    TkText *textPtr)
{
    if (textPtr->sharedTextPtr->allowUpdateLineMetrics
	    && TkRangeListIsEmpty(textPtr->dInfoPtr->lineMetricUpdateRanges)) {
	/*
	 * Remove the async handler.
	 */

	if (textPtr->dInfoPtr->lineUpdateTimer) {
	    Tcl_DeleteTimerHandler(textPtr->dInfoPtr->lineUpdateTimer);
	    textPtr->refCount -= 1;
	    textPtr->dInfoPtr->lineUpdateTimer = NULL;
	}

	/*
	 * If we have a full update, then also update the scrollbar.
	 */

	GetYView(textPtr->interp, textPtr, 1);

	if (!(TriggerWatchCursor(textPtr))) {
	    return; /* the widget has been deleted */
	}

	/*
	 * Report finish of full update.
	 */

	if (!textPtr->dInfoPtr->pendingUpdateLineMetricsFinished) {
	    textPtr->dInfoPtr->pendingUpdateLineMetricsFinished = 1;
	    Tcl_DoWhenIdle(RunUpdateLineMetricsFinished, textPtr);
	}

	if (tkBTreeDebug) {
	    CheckLineMetricConsistency(textPtr);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SaveDisplayLines --
 *
 *	Save the display lines, produced during line metric computation,
 *	for displaying. So UpdateDisplayInfo eventually must not re-compute
 *	these lines. This function will only be called if it is sure that
 *	DisplayText will be triggered afterwards, because UpdateDisplayInfo
 *	(called by DisplayText) is responsible for releasing the unused lines.
 *	The caller is responsible that the display will be saved in order from
 *	top to bottom, without gaps.
 *
 *	Saving the produced display lines is an important speed improvement
 *	(especially on Mac). Consider the following use case:
 *
 *	1. The text widget will be created.
 *	2. Content will be inserted.
 *	3. The view will be changed (for example to the end of the file).
 *
 *	In this case MeasureDown will produce display lines for line metric
 *	calculation, needed for the change of the view, and afterwards
 *	UpdateDisplayInfo needs (some of) these lines for displaying.
 *
 *	Note that no more lines will be saved than fitting into the widget,
 *	all surplus lines will be released immediately.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The display lines will be saved in TextDInfo. Function UpdateDisplayInfo
 *	is responsible to release the unused lines. The cached lines in
 *	argument 'info' will be taken over, this means that 'info->dLinePtr'
 *	is NULL after this function has done his work.
 *
 *----------------------------------------------------------------------
 */

static void
SaveDisplayLines(
    TkText *textPtr,
    DisplayInfo *info,
    int append)	/* Append to previously saved lines if 'true', otherwise prepend. */
{
    TextDInfo *dInfoPtr;
    DLine *firstPtr, *lastPtr;
    int height, viewHeight;

    if (!(firstPtr = info->dLinePtr)) {
	return;
    }

    assert(info->lastDLinePtr);
    lastPtr = info->lastDLinePtr;
    dInfoPtr = textPtr->dInfoPtr;
    height = dInfoPtr->savedDisplayLinesHeight + info->heightOfCachedLines;
    viewHeight = Tk_Height(textPtr->tkwin) - 2*textPtr->highlightWidth;
    /* we need some overhead, because the widget may show lines only partially */
    viewHeight += info->dLinePtr->height;

    if (append) {
	if (dInfoPtr->lastSavedDLinePtr) {
	    dInfoPtr->lastSavedDLinePtr->nextPtr = firstPtr;
	    firstPtr->prevPtr = dInfoPtr->lastSavedDLinePtr;
	} else {
	    dInfoPtr->savedDLinePtr = firstPtr;
	}
	dInfoPtr->lastSavedDLinePtr = lastPtr;
	firstPtr = lastPtr = dInfoPtr->savedDLinePtr;
	while (lastPtr->nextPtr && height >= viewHeight - lastPtr->height) {
	    height -= lastPtr->height;
	    lastPtr = lastPtr->nextPtr;
	}
	if (firstPtr != lastPtr) {
	    FreeDLines(textPtr, firstPtr, lastPtr, DLINE_FREE_TEMP);
	    assert(dInfoPtr->savedDLinePtr == lastPtr);
	}
    } else {
	if (dInfoPtr->savedDLinePtr) {
	    lastPtr->nextPtr = dInfoPtr->savedDLinePtr;
	    dInfoPtr->savedDLinePtr->prevPtr = lastPtr;
	} else {
	    dInfoPtr->lastSavedDLinePtr = lastPtr;
	}
	dInfoPtr->savedDLinePtr = firstPtr;
	firstPtr = lastPtr = dInfoPtr->lastSavedDLinePtr;
	while (firstPtr->prevPtr && height >= viewHeight - firstPtr->height) {
	    height -= firstPtr->height;
	    firstPtr = firstPtr->prevPtr;
	}
	if (firstPtr != lastPtr) {
	    FreeDLines(textPtr, firstPtr->nextPtr, NULL, DLINE_FREE_TEMP);
	    assert(!firstPtr->nextPtr);
	    dInfoPtr->lastSavedDLinePtr = firstPtr;
	}
    }

    dInfoPtr->savedDisplayLinesHeight = height;
    info->dLinePtr = info->lastDLinePtr = NULL;
    info->numCachedLines = 0;
    info->heightOfCachedLines = 0;
    assert(!dInfoPtr->savedDLinePtr == !dInfoPtr->lastSavedDLinePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeDisplayLineInfo --
 *
 *	This functions computes the display line information for struct
 *	DisplayInfo. If the cached information is still incomplete for
 *	this computation then LayoutDLine will be used for the computation
 *	of the missing display lines.
 *
 *	If additional display line computation is required for the line
 *	metric computation, then these lines will be cached, but only
 *	the last produced lines which can fit into the widget (this means:
 *	no more lines than fitting into the widget will be cached).
 *
 * Results:
 *	The attributes of 'info' will be set. The return value is the
 *	corresponding logical line.
 *
 * Side effects:
 *	The cache may be filled with more line metric information.
 *	Furthermore some of the produced display lines will be cached,
 *	the caller is responsible to release these lines.
 *
 *----------------------------------------------------------------------
 */

static TkTextDispLineEntry *
SearchDispLineEntry(
    TkTextDispLineEntry *first,
    const TkTextDispLineEntry *last,
    unsigned byteOffset)
{
    /*
     * NOTE: here 'last' is the last entry (not the pointer after the last
     * element as usual).
     */

    if (byteOffset >= last->byteOffset) {
	return (TkTextDispLineEntry *) last; /* frequent case */
    }

    while (first != last) {
	TkTextDispLineEntry *mid = first + (last - first)/2;

	if (byteOffset >= (mid + 1)->byteOffset) {
	    first = mid + 1;
	} else {
	    last = mid;
	}
    }

    return first;
}

static void
InsertDLine(
    TkText *textPtr,
    DisplayInfo *info,
    DLine *dlPtr,
    unsigned viewHeight)
{
    DLine *firstPtr = info->dLinePtr;

    assert(!dlPtr->nextPtr);
    assert(!dlPtr->prevPtr);

    info->heightOfCachedLines += dlPtr->height;

    if (firstPtr && info->heightOfCachedLines >= viewHeight + firstPtr->height) {
	info->heightOfCachedLines -= firstPtr->height;
	if ((info->dLinePtr = firstPtr->nextPtr)) {
	    info->dLinePtr->prevPtr = NULL;
	} else {
	    info->lastDLinePtr = NULL;
	}
	firstPtr->nextPtr = NULL;
	FreeDLines(textPtr, firstPtr, NULL, DLINE_FREE_TEMP);
    } else {
	info->numCachedLines += 1;
    }
    if (info->lastDLinePtr) {
	assert(info->dLinePtr);
	info->lastDLinePtr->nextPtr = dlPtr;
	dlPtr->prevPtr = info->lastDLinePtr;
    } else {
	assert(!info->dLinePtr);
	info->dLinePtr = dlPtr;
    }
    info->lastDLinePtr = dlPtr;
}

static TkTextLine *
ComputeDisplayLineInfo(
    TkText *textPtr,
    const TkTextIndex *indexPtr,
    DisplayInfo *info)
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    TkTextPixelInfo *pixelInfo;
    TkTextDispLineInfo *dispLineInfo;
    TkTextDispLineEntry *entry;
    TkTextLine *logicalLinePtr;
    TkTextLine *linePtr;
    unsigned byteOffset;
    unsigned startByteOffset;
    unsigned viewHeight;

    assert(info);
    assert(TkTextIndexGetLine(indexPtr));

    linePtr = TkTextIndexGetLine(indexPtr);
    logicalLinePtr = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
    pixelInfo = TkBTreeLinePixelInfo(textPtr, logicalLinePtr);
    dispLineInfo = pixelInfo->dispLineInfo;
    info->index = *indexPtr;
    TkTextIndexSetToStartOfLine2(&info->index, logicalLinePtr);
    startByteOffset = TkTextIndexGetByteIndex(&info->index);
    byteOffset = TkTextIndexCountBytes(&info->index, indexPtr);
    byteOffset += TkTextIndexGetByteIndex(&info->index);

    info->pixelInfo = pixelInfo;
    info->displayLineNo = 0;
    info->numDispLines = 1;
    info->entry = info->entryBuffer;
    info->dLinePtr = info->lastDLinePtr = NULL;
    info->nextByteOffset = -1;
    info->numCachedLines = 0;
    info->heightOfCachedLines = 0;
    info->linePtr = linePtr;

    if (dInfoPtr->lineMetricUpdateEpoch == (pixelInfo->epoch & EPOCH_MASK)) {
	if (!dispLineInfo) {
	    TkTextLine *nextLogicalLinePtr =
		    TkBTreeNextLogicalLine(textPtr->sharedTextPtr, textPtr, logicalLinePtr);

	    entry = info->entryBuffer;
	    if (logicalLinePtr->nextPtr == nextLogicalLinePtr
		    && TkTextIndexIsStartOfLine(&info->index)) {
		info->nextByteOffset = logicalLinePtr->size - byteOffset;
		entry->byteOffset = 0;
		(entry + 1)->byteOffset = logicalLinePtr->size;
	    } else {
		TkTextIndex index2 = info->index;
		TkTextIndexSetToStartOfLine2(&index2, nextLogicalLinePtr);
		info->nextByteOffset = TkTextIndexCountBytes(&info->index, &index2);
		entry->byteOffset = TkTextIndexGetByteIndex(&info->index);
		(entry + 1)->byteOffset = entry->byteOffset + info->nextByteOffset;
	    }
	    info->byteOffset = byteOffset;
	    info->isComplete = 1;
	    info->pixels = pixelInfo->height;
	    entry->height = pixelInfo->height;
	    entry->pixels = pixelInfo->height;
	    byteOffset = (entry + 1)->byteOffset - startByteOffset;
	    TkrTextIndexForwBytes(textPtr, &info->index, byteOffset, &info->index);
	    return logicalLinePtr;
	}

	if (dispLineInfo->numDispLines > 0) {
	    const TkTextDispLineEntry *last;
	    unsigned nextByteOffset;

	    last = dispLineInfo->entry + dispLineInfo->numDispLines;
	    entry = SearchDispLineEntry(dispLineInfo->entry, last, byteOffset);

	    if (entry != last) {
		info->entry = entry;
		info->byteOffset = byteOffset - entry->byteOffset;
		info->nextByteOffset = (entry + 1)->byteOffset - byteOffset;
		info->displayLineNo = entry - dispLineInfo->entry;
		info->numDispLines = dispLineInfo->numDispLines;
		info->pixels = (last - 1)->pixels;
		info->isComplete = (dInfoPtr->lineMetricUpdateEpoch == pixelInfo->epoch);
		byteOffset = last->byteOffset - startByteOffset;
		TkrTextIndexForwBytes(textPtr, &info->index, byteOffset, &info->index);
		return logicalLinePtr;
	    }

	    /*
	     * If we reach this point, then we need more information than already
	     * computed for this line.
	     */

	    info->displayLineNo = dispLineInfo->numDispLines;
	    nextByteOffset = last->byteOffset - dispLineInfo->entry[0].byteOffset;
	    TkBTreeMoveForward(&info->index, nextByteOffset);
	    byteOffset -= nextByteOffset;
	}
    }

    /*
     * Compute missing line metric information. Don't throw away the produced display
     * lines, probably the caller might use it. But do not cache more than fitting into
     * the widget.
     */

    viewHeight = Tk_Height(textPtr->tkwin) - 2*textPtr->highlightWidth;
    /* we need some overhead, because the widget may show lines only partially */
    viewHeight += dInfoPtr->dLinePtr ? dInfoPtr->dLinePtr->height : 20;

    while (1) {
	DLine *dlPtr;

	if (dInfoPtr->lastMetricDLinePtr
		&& pixelInfo->epoch == dInfoPtr->lineMetricUpdateEpoch
		&& TkTextIndexIsEqual(&info->index, &dInfoPtr->lastMetricDLinePtr->index)) {
	    dlPtr = dInfoPtr->lastMetricDLinePtr;
	    dInfoPtr->lastMetricDLinePtr = NULL;
	    assert(dlPtr->displayLineNo == info->displayLineNo);
	} else {
	    dlPtr = LayoutDLine(&info->index, info->displayLineNo);
	}
	InsertDLine(textPtr, info, dlPtr, viewHeight);
	TkrTextIndexForwBytes(textPtr, &info->index, dlPtr->byteCount, &info->index);
	if (dInfoPtr->lineMetricUpdateEpoch == pixelInfo->epoch || byteOffset < dlPtr->byteCount) {
	    info->byteOffset = byteOffset;
	    info->nextByteOffset = dlPtr->byteCount - byteOffset;
	    info->isComplete = (dInfoPtr->lineMetricUpdateEpoch == pixelInfo->epoch);
	    break;
	}
	byteOffset -= dlPtr->byteCount;
	info->displayLineNo += 1;
    }

    /*
     * Note that LayoutDLine may re-allocate 'pixelInfo->dispLineInfo',
     * so variable 'dispLineInfo' is in general not valid anymore.
     */

    dispLineInfo = pixelInfo->dispLineInfo;

    if (dispLineInfo) {
	info->numDispLines = dispLineInfo->numDispLines;
	info->entry = dispLineInfo->entry + info->displayLineNo;
	info->pixels = dispLineInfo->entry[dispLineInfo->numDispLines - 1].pixels;
    } else {
	info->pixels = pixelInfo->height;
	info->entryBuffer[0].height = pixelInfo->height;
	info->entryBuffer[0].pixels = pixelInfo->height;
	info->entryBuffer[0].byteOffset = byteOffset;
	info->entryBuffer[1].byteOffset = info->nextByteOffset + info->byteOffset;
    }

    return logicalLinePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeMissingMetric --
 *
 *	This functions is continuing the computation of an unfinished
 *	display line metric, which can only happen if a logical line
 *	is wrapping into several display lines. It may not be required
 *	to compute all missing display lines, the computation stops
 *	until the threshold has been reached. But the computation will
 *	always stop at the end of the logical line.
 *
 *	Possible threshold types are THRESHOLD_BYTE_OFFSET,
 *	THRESHOLD_PIXEL_DISTANCE, and THRESHOLD_LINE_OFFSET. The two
 *	former thresholds will be specified absolute (but relative to
 *	start of logical line), and the latter thresholds will be specified
 *	relative to info->displayLineNo.
 *
 *	If additional display line computation is required for the line
 *	metric computation, then these lines will be cached, but only
 *	the last produced lines which can fit into the widget (this means:
 *	no more lines than fitting into the widget will be cached).
 *
 *	It is important that this function is only computing the relevant
 *	line metric. It may happen that a logical line may wrap into
 *	thousands of display lines, but if only the first 100 (following
 *	lines) are needed, then only the first 100 should be computed here,
 *	not more.
 *
 * Results:
 *	The attributes of 'info' will be updated.
 *
 * Side effects:
 *	The cache may be filled with more line metric information.
 *	Furthermore some of the produced display lines will be cached,
 *	the caller is responsible to release these lines.
 *
 *----------------------------------------------------------------------
 */

static void
ComputeMissingMetric(
    TkText *textPtr,
    DisplayInfo *info,
    Threshold thresholdType,
    int threshold)
{
    int byteOffset, additionalLines;
    unsigned displayLineNo;
    int *metricPtr = NULL; /* avoids compiler warning */
    unsigned viewHeight;
    TkTextIndex index;

    assert(threshold >= 0);

    if (info->isComplete) {
	return;
    }

    additionalLines = info->numDispLines - info->displayLineNo;
    assert(additionalLines > 0);
    byteOffset = info->entry[additionalLines].byteOffset;
    displayLineNo = info->numDispLines;
    viewHeight = Tk_Height(textPtr->tkwin) - 2*textPtr->highlightWidth;
    /* we need some overhead, because the widget may show lines only partially */
    viewHeight += textPtr->dInfoPtr->dLinePtr ? textPtr->dInfoPtr->dLinePtr->height : 20;
    TkrTextIndexForwBytes(textPtr, &info->index,
	    byteOffset - info->entry[additionalLines - 1].byteOffset, &index);

    switch (thresholdType) {
    case THRESHOLD_BYTE_OFFSET:    metricPtr = &byteOffset; break;
    case THRESHOLD_LINE_OFFSET:    metricPtr = &additionalLines; break;
    case THRESHOLD_PIXEL_DISTANCE: metricPtr = &info->pixels; break;
    }

    while (threshold >= *metricPtr) {
	DLine *dlPtr = LayoutDLine(&info->index, displayLineNo++);
	info->pixels += dlPtr->height;
	byteOffset += dlPtr->byteCount;
	info->numDispLines += 1;
	additionalLines -= 1;
	TkrTextIndexForwBytes(textPtr, &info->index, dlPtr->byteCount, &info->index);
	InsertDLine(textPtr, info, dlPtr, viewHeight);

	if (IsStartOfNotMergedLine(&info->index)) {
	    info->isComplete = 1;
	    break;
	}
    }

    info->entry = info->pixelInfo->dispLineInfo->entry + info->displayLineNo;
}

/*
 *----------------------------------------------------------------------
 *
 * UpdateDisplayInfo --
 *
 *	This function is invoked to recompute some or all of the DLine
 *	structures for a text widget. At the time it is called the DLine
 *	structures still left in the widget are guaranteed to be correct
 *	except that (a) the y-coordinates aren't necessarily correct, (b)
 *	there may be missing structures (the DLine structures get removed as
 *	soon as they are potentially out-of-date), and (c) DLine structures
 *	that don't start at the beginning of a line may be incorrect if
 *	previous information in the same line changed size in a way that moved
 *	a line boundary (DLines for any info that changed will have been
 *	deleted, but not DLines for unchanged info in the same text line).
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Upon return, the DLine information for textPtr correctly reflects the
 *	positions where characters will be displayed. However, this function
 *	doesn't actually bring the display up-to-date.
 *
 *----------------------------------------------------------------------
 */

static Tk_RestrictAction
UpdateRestrictProc(
    void *arg,
    XEvent *eventPtr)
{
    TkText* textPtr = (TkText *) arg;

    /*
     * Defer events which aren't for the specified window.
     */

    if (eventPtr->xany.display == textPtr->display
	    && eventPtr->xany.window == Tk_WindowId(textPtr->tkwin)) {
	if (eventPtr->type == NoExpose) {
	    /*
	     * We handle this case although we do not expect this type of event.
	     */
	    return TK_DISCARD_EVENT;
	}
	if (eventPtr->type == GraphicsExpose) {
	    /*
	     * We handle this case although we do not expect this type of event.
	     */
	    TkTextRedrawRegion(textPtr,
		    eventPtr->xgraphicsexpose.x, eventPtr->xgraphicsexpose.y,
		    eventPtr->xgraphicsexpose.width, eventPtr->xgraphicsexpose.height);
	    return TK_DISCARD_EVENT;
	}
	if (eventPtr->type == Expose) {
	    TkTextRedrawRegion(textPtr,
		    eventPtr->xexpose.x, eventPtr->xexpose.y,
		    eventPtr->xexpose.width, eventPtr->xexpose.height);
	    return TK_DISCARD_EVENT;
	}
    }

    return TK_DEFER_EVENT;
}

static int
LineIsUpToDate(
    TkText *textPtr,
    DLine *dlPtr,
    unsigned lineMetricUpdateEpoch)
{
    const TkTextPixelInfo *pixelInfo = TkBTreeLinePixelInfo(textPtr, TkTextIndexGetLine(&dlPtr->index));
    const TkTextDispLineInfo *dispLineInfo = pixelInfo->dispLineInfo;
    unsigned epoch = pixelInfo->epoch;

    assert(!(epoch & PARTIAL_COMPUTED_BIT) || dispLineInfo);

    return (epoch & EPOCH_MASK) == lineMetricUpdateEpoch
	    && (!dispLineInfo || dlPtr->displayLineNo < dispLineInfo->numDispLines);
}

static void
UpdateDisplayInfo(
    TkText *textPtr)	/* Text widget to update. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    DLine *dlPtr;
    DLine *topLine;
    DLine *bottomLine;
    DLine *newTopLine;
    DLine *savedDLine;		/* usable saved display lines */
    DLine *prevSavedDLine;	/* last old unfreed display line */
    TkTextIndex index;
    TkTextLine *lastLinePtr;
    TkTextLine *linePtr;
    DisplayInfo info;
    int y, maxY, xPixelOffset, maxOffset;
    unsigned displayLineNo;
    unsigned epoch;
    Tk_RestrictProc* prevRestrictProc;
    void *prevRestrictArg;

    if (!(dInfoPtr->flags & DINFO_OUT_OF_DATE)) {
	return;
    }
    dInfoPtr->flags &= ~DINFO_OUT_OF_DATE;

    /*
     * Before doing any change in display lines we have to process all the dangling
     * exposure events in event queue for this widget, because these events are
     * belonging to the state before updating the display lines.
     *
     * Consider the following situation:
     * A dialog window is triggering a deletion of a B-Tree line, and concurrently
     * the dialog disappears (closed). The basic graphic layer (e.g. X11) will
     * push exposure events because a region has been unobscured. But a motion
     * event is preceding the exposure events, and this motion events is triggering
     * TkTextPixelIndex() which needs updated display lines, and calls UpdateDisplayInfo()
     * before the exposure events has been processed. When processing the exposure
     * events afterwards function TextInvalidateRegion() will flag the wrong display
     * lines as changed, because of the deletion of display lines the y position of
     * some display lines has changed, but the exposure belongs to the old y positions.
     * Such a situation has to be avoided, especially in combination with tooltips
     * graphical glitches are very likely if we do not process the exposure events
     * at the right time. Currently many widgets in the Tk library are suffering from
     * this problem.
     *
     * TODO:
     * This handling is still a work-around, because we have the problem that other
     * events like motion events eventually are belonging to a different graphical
     * state. But our handling is not worsen the situation. It seems that the whole
     * library needs a clean basic concept how to handle events synchronously, but
     * still efficient. Currently the concepts of the Tk library are a bit simple.
     */

    prevRestrictProc = Tk_RestrictEvents(UpdateRestrictProc, textPtr, &prevRestrictArg);
    while (Tcl_ServiceEvent(TCL_WINDOW_EVENTS)) {}
    Tk_RestrictEvents(prevRestrictProc, prevRestrictArg, &prevRestrictArg);

    /*
     * At first, update the default style, and reset cached chunk.
     */

    UpdateDefaultStyle(textPtr);
    dInfoPtr->currChunkPtr = NULL;

    /*
     * Release the cached display lines.
     */

    FreeDLines(textPtr, NULL, NULL, DLINE_CACHE);

    /*
     * Delete any DLines that are now above the top of the window.
     */

    index = textPtr->topIndex;
    prevSavedDLine = NULL;
    savedDLine = dInfoPtr->savedDLinePtr;

    if ((dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, &index))) {
	/*
	 * Don't throw away unused display lines immediately, because it may happen
	 * that we will reuse some of them later.
	 */

	prevSavedDLine = FreeDLines(textPtr, dInfoPtr->dLinePtr, dlPtr, DLINE_SAVE);
    }

    /*
     * Scan through the contents of the window from top to bottom, recomputing
     * information for lines that are missing.
     */

    linePtr = TkTextIndexGetLine(&index);
    lastLinePtr = TkBTreeGetLastLine(textPtr);
    dlPtr = dInfoPtr->dLinePtr;
    topLine = bottomLine = NULL;
    y = dInfoPtr->y - dInfoPtr->newTopPixelOffset;
    maxY = dInfoPtr->maxY;
    newTopLine = NULL;
    epoch = dInfoPtr->lineMetricUpdateEpoch;
    dInfoPtr->maxLength = 0;

    if (IsStartOfNotMergedLine(&index)) {
	displayLineNo = 0;
    } else {
	ComputeDisplayLineInfo(textPtr, &index, &info);
	TkrTextIndexBackBytes(textPtr, &index, info.byteOffset, &index);
	displayLineNo = info.displayLineNo;

	if (info.lastDLinePtr) {
	    /*
	     * Keep last produced display line, probably we can re-use it for new top line.
	     */

	    newTopLine = info.lastDLinePtr;
	    if (newTopLine->prevPtr) {
		newTopLine->prevPtr->nextPtr = NULL;
		newTopLine->prevPtr = NULL;
	    } else {
		assert(info.dLinePtr == info.lastDLinePtr);
		info.dLinePtr = info.lastDLinePtr = NULL;
	    }
	    assert(!newTopLine->nextPtr);
	}
	FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
    }

    /*
     * If we have saved display lines from a previous metric computation,
     * then we will search for the first re-usable line.
     */

    while (savedDLine && TkTextIndexCompare(&savedDLine->index, &index) < 0) {
	savedDLine = savedDLine->nextPtr;
    }

    /*
     * If we have a cached top-line, then insert this line into the list of saved lines.
     */

    if (newTopLine) {
	/*
	 * If we have a cached top-line, then it's not possible that this line
	 * is also in the list of saved lines (because ComputeDisplayLineInfo
	 * cannot produce a display line if the metric of this line is already
	 * known, and the line metric is known as soon as the line has been
	 * computed). This means that we can prepend this top-line to the list
	 * of saved lines.
	 */

	assert(!savedDLine || TkTextIndexCompare(&savedDLine->index, &newTopLine->index) > 0);

	if ((newTopLine->nextPtr = savedDLine)) {
	    newTopLine->prevPtr = savedDLine->prevPtr;
	    savedDLine->prevPtr = newTopLine;
	} else if (dInfoPtr->savedDLinePtr) {
	    dInfoPtr->lastSavedDLinePtr->nextPtr = newTopLine;
	    newTopLine->prevPtr = dInfoPtr->lastSavedDLinePtr;
	    dInfoPtr->lastSavedDLinePtr = newTopLine;
	}
	if (dInfoPtr->savedDLinePtr == savedDLine) {
	    dInfoPtr->savedDLinePtr = newTopLine;
	}
	if (!dInfoPtr->lastSavedDLinePtr) {
	    dInfoPtr->lastSavedDLinePtr = newTopLine;
	}

	savedDLine = newTopLine;
    } else {
	newTopLine = savedDLine;
    }

    if (newTopLine && !prevSavedDLine) {
	prevSavedDLine = newTopLine->prevPtr;
    }

    while (linePtr != lastLinePtr) {
	int cmp;

	/*
	 * There are three possibilities right now:
	 *
	 * (a) the next DLine (dlPtr) corresponds exactly to the next
	 *     information we want to display: just use it as-is.
	 *
	 * (b) the next DLine corresponds to a different line, or to a segment
	 *     that will be coming later in the same line: leave this DLine
	 *     alone in the hopes that we'll be able to use it later, then
	 *     create a new DLine in front of it.
	 *
	 * (c) the next DLine corresponds to a segment in the line we want,
	 *     but it's a segment that has already been processed or will
	 *     never be processed. Delete the DLine and try again.
	 *
	 * One other twist on all this. It's possible for 3D borders to
	 * interact between lines (see DisplayLineBackground) so if a line is
	 * relayed out and has styles with 3D borders, its neighbors have to
	 * be redrawn if they have 3D borders too, since the interactions
	 * could have changed (the neighbors don't have to be relayed out,
	 * just redrawn).
	 */

	if (!dlPtr
		|| TkTextIndexGetLine(&dlPtr->index) != linePtr
		|| !LineIsUpToDate(textPtr, dlPtr, epoch)
		|| (cmp = TkTextIndexCompare(&index, &dlPtr->index)) < 0) {
	    /*
	     * Case (b) -- must make new DLine.
	     */

	    TK_TEXT_DEBUG(LogTextRelayout(textPtr, &index));
	    if (savedDLine && TkTextIndexIsEqual(&index, &savedDLine->index)) {
		dlPtr = savedDLine;
		savedDLine = savedDLine->nextPtr;
		if (dInfoPtr->savedDLinePtr == dlPtr) {
		    dInfoPtr->savedDLinePtr = dlPtr->nextPtr;
		}
		if (dInfoPtr->lastSavedDLinePtr == dlPtr) {
		    dInfoPtr->lastSavedDLinePtr = dlPtr->prevPtr;
		}
		if (dlPtr->prevPtr) {
		    dlPtr->prevPtr->nextPtr = dlPtr->nextPtr;
		}
		if (dlPtr->nextPtr) {
		    dlPtr->nextPtr->prevPtr = dlPtr->prevPtr;
		}
		dlPtr->prevPtr = dlPtr->nextPtr = NULL;
		DEBUG(stats.numReused++);
	    } else {
		dlPtr = LayoutDLine(&index, displayLineNo);
	    }
	    assert(!(dlPtr->flags & (LINKED|CACHED|DELETED)));
	    if (!bottomLine) {
		if ((dlPtr->nextPtr = dInfoPtr->dLinePtr)) {
		    dInfoPtr->dLinePtr->prevPtr = dlPtr;
		}
		dInfoPtr->dLinePtr = dlPtr;
	    } else {
		if ((dlPtr->nextPtr = bottomLine->nextPtr)) {
		    bottomLine->nextPtr->prevPtr = dlPtr;
		}
		bottomLine->nextPtr = dlPtr;
		dlPtr->prevPtr = bottomLine;

		if (bottomLine->flags & HAS_3D_BORDER) {
		    bottomLine->flags |= OLD_Y_INVALID;
		}
	    }
	    DEBUG(dlPtr->flags |= LINKED);
	} else if (cmp == 0) {
	    /*
	     * Case (a) - can use existing display line as-is.
	     */

	    if (bottomLine && (dlPtr->flags & HAS_3D_BORDER) && (bottomLine->flags & NEW_LAYOUT)) {
		dlPtr->flags |= OLD_Y_INVALID;
	    }
	    assert(dlPtr->displayLineNo == displayLineNo);
	} else /* if (cmp > 0) */ {
	    /*
	     * Case (c) - dlPtr is useless. Discard it and start again with the next display line.
	     */

	    DLine *nextPtr = dlPtr->nextPtr;
	    FreeDLines(textPtr, dlPtr, nextPtr, DLINE_UNLINK);
	    dlPtr = nextPtr;
	    continue;
	}

	/*
	 * Advance to the start of the next display line.
	 */

	dlPtr->y = y;
	y += dlPtr->height;
	TkrTextIndexForwBytes(textPtr, &index, dlPtr->byteCount, &index);
	linePtr = TkTextIndexGetLine(&index);

	if (linePtr->logicalLine && TkTextIndexIsStartOfLine(&index)) {
	    displayLineNo = 0;
	} else {
	    displayLineNo += 1;
	}

	bottomLine = dlPtr;
	dlPtr = dlPtr->nextPtr;

	/*
	 * It's important to have the following check here rather than in the
	 * while statement for the loop, so that there's always at least one
	 * DLine generated, regardless of how small the window is. This keeps
	 * a lot of other code from breaking.
	 */

	if (y >= maxY) {
	    break;
	}
    }

    /* Delete any DLine structures that don't fit on the screen. */
    FreeDLines(textPtr, dlPtr, NULL, DLINE_UNLINK);
    topLine = dInfoPtr->dLinePtr;

    /*
     * If there is extra space at the bottom of the window (because we've hit
     * the end of the text), then bring in more lines at the top of the
     * window, if there are any, to fill in the view.
     *
     * Since the top line may only be partially visible, we try first to
     * simply show more pixels from that line (newTopPixelOffset). If that
     * isn't enough, we have to layout more lines.
     */

    if (y < maxY) {
	/*
	 * This counts how many vertical pixels we have left to fill by
	 * pulling in more display pixels either from the first currently
	 * displayed, or the lines above it.
	 */

	int spaceLeft = maxY - y;

	if (spaceLeft <= dInfoPtr->newTopPixelOffset) {
	    /*
	     * We can fill up all the needed space just by showing more of the
	     * current top line.
	     */

	    dInfoPtr->newTopPixelOffset -= spaceLeft;
	    y += spaceLeft;
	    spaceLeft = 0;
	} else {
	    TkTextLine *linePtr1;
	    TkTextLine *firstLinePtr;

	    /*
	     * Add in all of the current top line, which won't be enough to bring y
	     * up to maxY (if it was we would be in the 'if' block above).
	     */

	    y += dInfoPtr->newTopPixelOffset;
	    dInfoPtr->newTopPixelOffset = 0;
	    spaceLeft = maxY - y;

	    /*
	     * Layout an entire text line (potentially > 1 display line), then
	     * link in as many display lines as fit without moving the bottom
	     * line out of the window. Repeat this until all the extra space
	     * has been used up or we've reached the beginning of the text.
	     */

	    if (spaceLeft > 0) {
		firstLinePtr = TkBTreeGetStartLine(textPtr)->prevPtr;
		index = topLine ? topLine->index : textPtr->topIndex;
		savedDLine = prevSavedDLine;
		if (TkrTextIndexBackBytes(textPtr, &index, 1, &index) == 1) {
		    firstLinePtr = linePtr1 = NULL; /* we are already at start of text */
		} else {
		    linePtr1 = TkTextIndexGetLine(&index);
		}

		for ( ; linePtr1 != firstLinePtr && spaceLeft > 0; linePtr1 = linePtr1->prevPtr) {
		    if (linePtr1 != TkTextIndexGetLine(&index)) {
			TkTextIndexSetToLastChar2(&index, linePtr1);
		    }
		    linePtr1 = ComputeDisplayLineInfo(textPtr, &index, &info);

		    do {
			if (info.lastDLinePtr) {
			    dlPtr = info.lastDLinePtr;
			    if (dlPtr->prevPtr) {
				dlPtr->prevPtr->nextPtr = NULL;
				info.lastDLinePtr = dlPtr->prevPtr;
				dlPtr->prevPtr = NULL;
				assert(dlPtr != info.dLinePtr);
			    } else {
				assert(info.dLinePtr == info.lastDLinePtr);
				info.dLinePtr = info.lastDLinePtr = NULL;
			    }
			} else {
			    TkTextIndexSetToStartOfLine2(&index, linePtr1);
			    TkrTextIndexForwBytes(textPtr, &index, info.entry->byteOffset, &index);
			    if (savedDLine && TkTextIndexIsEqual(&index, &savedDLine->index)) {
				dlPtr = savedDLine;
				savedDLine = savedDLine->prevPtr;
				if (dlPtr->prevPtr) {
				    dlPtr->prevPtr->nextPtr = dlPtr->nextPtr;
				} else {
				    dInfoPtr->savedDLinePtr = dlPtr->nextPtr;
				}
				if (dlPtr->nextPtr) {
				    dlPtr->nextPtr->prevPtr = dlPtr->prevPtr;
				} else {
				    dInfoPtr->lastSavedDLinePtr = dlPtr->prevPtr;
				}
				dlPtr->prevPtr = dlPtr->nextPtr = NULL;
			    } else {
				dlPtr = LayoutDLine(&index, info.displayLineNo);
			    }
			}
			if ((dlPtr->nextPtr = topLine)) {
			    topLine->prevPtr = dlPtr;
			} else {
			    bottomLine = dlPtr;
			}
			topLine = dlPtr;
			DEBUG(dlPtr->flags |= LINKED);
			TK_TEXT_DEBUG(LogTextRelayout(textPtr, &dlPtr->index));
			spaceLeft -= dlPtr->height;
			if (info.displayLineNo == 0) {
			    break;
			}
			info.displayLineNo -= 1;
			info.entry -= 1;
		    } while (spaceLeft > 0);

		    dInfoPtr->dLinePtr = topLine;
		    /* Delete remaining cached lines. */
		    FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
		}
	    }

	    /*
	     * We've either filled in the space we wanted to or we've run out
	     * of display lines at the top of the text. Note that we already
	     * set dInfoPtr->newTopPixelOffset to zero above.
	     */

	    if (spaceLeft < 0) {
		/*
		 * We've laid out a few too many vertical pixels at or above
		 * the first line. Therefore we only want to show part of the
		 * first displayed line, so that the last displayed line just
		 * fits in the window.
		 */

		dInfoPtr->newTopPixelOffset = -spaceLeft;

		/*
		 * If the entire first line we laid out is shorter than the new offset:
		 * this should not occur and would indicate a bad problem in the logic above.
		 */

		assert(dInfoPtr->newTopPixelOffset < topLine->height);
	    }
	}

	/*
	 * Now we're all done except that the y-coordinates in all the DLines
	 * are wrong and the top index for the text is wrong. Update them.
	 */

	if (topLine) {
	    dInfoPtr->dLinePtr = topLine;
	    y = dInfoPtr->y - dInfoPtr->newTopPixelOffset;
	    for (dlPtr = topLine; dlPtr; dlPtr = dlPtr->nextPtr) {
		assert(y <= dInfoPtr->maxY);
		dlPtr->y = y;
		y += dlPtr->height;
	    }
	}
    }

    /*
     * If the old top or bottom line has scrolled elsewhere on the screen, we
     * may not be able to re-use its old contents by copying bits (e.g., a
     * beveled edge that was drawn when it was at the top or bottom won't be
     * drawn when the line is in the middle and its neighbor has a matching
     * background). Similarly, if the new top or bottom line came from
     * somewhere else on the screen, we may not be able to copy the old bits.
     *
     * And don't forget to update the top index.
     */

    if (topLine) {
	textPtr->topIndex = topLine->index;
	assert(textPtr->topIndex.textPtr);
	TkTextIndexToByteIndex(&textPtr->topIndex);
	dInfoPtr->maxLength = MAX(dInfoPtr->maxLength, topLine->length);

	if ((topLine->flags & (TOP_LINE|HAS_3D_BORDER)) == HAS_3D_BORDER) {
	    topLine->flags |= OLD_Y_INVALID;
	}
	if ((bottomLine->flags & (BOTTOM_LINE|HAS_3D_BORDER)) == HAS_3D_BORDER) {
	    bottomLine->flags |= OLD_Y_INVALID;
	}

	if (topLine != bottomLine) {
	    topLine->flags &= ~BOTTOM_LINE;
	    bottomLine->flags &= ~TOP_LINE;

	    for (dlPtr = topLine->nextPtr; dlPtr != bottomLine; dlPtr = dlPtr->nextPtr) {
		dInfoPtr->maxLength = MAX(dInfoPtr->maxLength, dlPtr->length);

		if ((topLine->flags & HAS_3D_BORDER) && (dlPtr->flags & (TOP_LINE|BOTTOM_LINE))) {
		    dlPtr->flags |= OLD_Y_INVALID;
		}

		/*
		 * If the old top-line was not completely showing (i.e. the
		 * pixelOffset is non-zero) and is no longer the top-line, then we
		 * must re-draw it.
		 */

		if ((dlPtr->flags & TOP_LINE) && dInfoPtr->topPixelOffset != 0) {
		    dlPtr->flags |= OLD_Y_INVALID;
		}

		dlPtr->flags &= ~(TOP_LINE|BOTTOM_LINE);
	    }

	    dInfoPtr->maxLength = MAX(dInfoPtr->maxLength, bottomLine->length);
	}

	topLine->flags |= TOP_LINE;
	bottomLine->flags |= BOTTOM_LINE;

	dInfoPtr->topPixelOffset = dInfoPtr->newTopPixelOffset;
	dInfoPtr->curYPixelOffset = GetYPixelCount(textPtr, topLine);
	dInfoPtr->curYPixelOffset += dInfoPtr->topPixelOffset;
    } else {
	TkTextIndexSetupToStartOfText(&textPtr->topIndex, textPtr, textPtr->sharedTextPtr->tree);
    }

    dInfoPtr->lastDLinePtr = bottomLine;

    /*
     * Delete remaining saved lines.
     */

    FreeDLines(textPtr, dInfoPtr->savedDLinePtr, NULL, DLINE_FREE_TEMP);

    /*
     * Arrange for scrollbars to be updated.
     */

    textPtr->flags |= UPDATE_SCROLLBARS;

    /*
     * Deal with horizontal scrolling:
     * 1. If there's empty space to the right of the longest line, shift the
     *	  screen to the right to fill in the empty space.
     * 2. If the desired horizontal scroll position has changed, force a full
     *	  redisplay of all the lines in the widget.
     * 3. If the wrap mode isn't "none" then re-scroll to the base position.
     */

    maxOffset = dInfoPtr->maxLength - (dInfoPtr->maxX - dInfoPtr->x);
    xPixelOffset = MAX(0, MIN(dInfoPtr->newXPixelOffset, maxOffset));

    /*
     * Here's a problem: see the tests textDisp-29.2.1-4
     *
     * If the widget is being created, but has not yet been configured it will
     * have a maxY of 1 above, and we won't have examined all the lines
     * (just the first line, in fact), and so maxOffset will not be a true
     * reflection of the widget's lines. Therefore we must not overwrite the
     * original newXPixelOffset in this case.
     */

    if (!(((Tk_FakeWin *) (textPtr->tkwin))->flags & TK_NEED_CONFIG_NOTIFY)) {
	dInfoPtr->newXPixelOffset = xPixelOffset;
    }

    if (xPixelOffset != dInfoPtr->curXPixelOffset) {
	dInfoPtr->curXPixelOffset = xPixelOffset;
	for (dlPtr = topLine; dlPtr; dlPtr = dlPtr->nextPtr) {
	    dlPtr->flags |= OLD_Y_INVALID;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * FreeDLines --
 *
 *	This function is called to free up all of the resources associated
 *	with one or more DLine structures.
 *
 * Results:
 *	Returns the last unfreed line if action is DLINE_SAVE, otherwise
 *	NULL will be returned.
 *
 * Side effects:
 *	Memory gets freed and various other resources are released.
 *
 *----------------------------------------------------------------------
 */

static int
LineIsOutsideOfPeer(
    const TkText *textPtr,
    const TkTextIndex *indexPtr)
{
    const TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;

    if (textPtr->startMarker != sharedTextPtr->startMarker) {
	const TkTextLine *linePtr = textPtr->startMarker->sectionPtr->linePtr;
	int no1 = TkTextIndexGetLineNumber(indexPtr, NULL);
	int no2 = TkBTreeLinesTo(sharedTextPtr->tree, NULL, linePtr, NULL);

	if (no1 < no2) {
	    return 1;
	}
    }
    if (textPtr->endMarker != sharedTextPtr->endMarker) {
	const TkTextLine *linePtr = textPtr->endMarker->sectionPtr->linePtr;
	int no1 = TkTextIndexGetLineNumber(indexPtr, NULL);
	int no2 = TkBTreeLinesTo(sharedTextPtr->tree, NULL, linePtr, NULL);

	if (no1 > no2) {
	    return 1;
	}
    }
    return 0;
}

static void
ReleaseLines(
    TkText *textPtr,
    DLine *firstPtr,
    DLine *lastPtr,
    FreeDLineAction action)
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    DLine *dlPtr, *lastDeletedPtr = NULL; /* avoids compiler warning */

    assert(firstPtr);
    assert(firstPtr != lastPtr);

    for (dlPtr = firstPtr; dlPtr != lastPtr; dlPtr = dlPtr->nextPtr) {
	TkTextDispChunk *chunkPtr;

	assert(!(dlPtr->flags & DELETED));
	assert((action == DLINE_UNLINK || action == DLINE_UNLINK_KEEP_BRKS)
		== !!(dlPtr->flags & LINKED));
	assert((action == DLINE_CACHE) == !!(dlPtr->flags & CACHED));
	assert(dlPtr != dInfoPtr->savedDLinePtr || dlPtr == firstPtr);
	assert(dlPtr->chunkPtr || (!dlPtr->lastChunkPtr && !dlPtr->breakInfo));

	if (dlPtr->lastChunkPtr) {
	    TkTextDispChunkSection *sectionPtr = NULL;

	    /*
	     * We have to destroy the chunks backward, because the context support
	     * is expecting this.
	     */

	    for (chunkPtr = dlPtr->lastChunkPtr; chunkPtr; chunkPtr = chunkPtr->prevPtr) {
		if (chunkPtr->layoutProcs->undisplayProc) {
		    chunkPtr->layoutProcs->undisplayProc(textPtr, chunkPtr);
		}
		LayoutReleaseChunk(textPtr, chunkPtr);
		DEBUG(chunkPtr->stylePtr = NULL);

		if (chunkPtr->sectionPtr != sectionPtr) {
		    sectionPtr = chunkPtr->sectionPtr;
		    sectionPtr->nextPtr = dInfoPtr->sectionPoolPtr;
		    dInfoPtr->sectionPoolPtr = sectionPtr;
		}
	    }

	    if (dlPtr->breakInfo
		    && (action != DLINE_UNLINK_KEEP_BRKS || LineIsOutsideOfPeer(textPtr, &dlPtr->index))
		    && --dlPtr->breakInfo->refCount == 0) {
		assert(dlPtr->breakInfo->brks);
		ckfree(dlPtr->breakInfo->brks);
		DEBUG(dlPtr->breakInfo->brks = NULL);
		DEBUG(dlPtr->breakInfo->brksSize = 0);
		ckfree(dlPtr->breakInfo);
		Tcl_DeleteHashEntry(Tcl_FindHashEntry(
			&textPtr->sharedTextPtr->breakInfoTable,
			(void *) TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr,
			    TkTextIndexGetLine(&dlPtr->index))));
		DEBUG_ALLOC(tkTextCountDestroyBreakInfo++);
		DEBUG(dlPtr->breakInfo = NULL);
	    }

	    dlPtr->lastChunkPtr->nextPtr = dInfoPtr->chunkPoolPtr;
	    dInfoPtr->chunkPoolPtr = dlPtr->chunkPtr;
	    assert(!dInfoPtr->chunkPoolPtr->prevPtr);
	}

	lastDeletedPtr = dlPtr;
	DEBUG(dlPtr->flags = DELETED);
    }

    assert(lastDeletedPtr);
    lastDeletedPtr->nextPtr = dInfoPtr->dLinePoolPtr;
    dInfoPtr->dLinePoolPtr = firstPtr;

    if (lastPtr) {
	lastPtr->prevPtr = firstPtr->prevPtr;
    }
    if (firstPtr->prevPtr) {
	firstPtr->prevPtr->nextPtr = lastPtr;
    }
}

static DLine *
FreeDLines(
    TkText *textPtr,		/* Information about overall text widget. */
    DLine *firstPtr,		/* Pointer to first DLine to free up. */
    DLine *lastPtr,		/* Pointer to DLine just after last one to free (NULL means
				 * everything starting with firstPtr). */
    FreeDLineAction action)	/* DLINE_UNLINK means DLines are currently linked into the list
				 * rooted at textPtr->dInfoPtr->dLinePtr and they have to be
				 * unlinked. DLINE_FREE_TEMP, and DLINE_CACHE means the DLine given
				 * is just a temporary one and we shouldn't invalidate anything for
				 * the overall widget. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    switch (action) {
    case DLINE_CACHE:
	assert(!lastPtr);
	if (firstPtr) {
	    DLine *prevPtr = firstPtr->prevPtr;

	    assert(!(firstPtr->flags & LINKED));
	    assert(!(firstPtr->flags & CACHED));
	    assert(!(firstPtr->flags & DELETED));
	    assert(firstPtr != dInfoPtr->savedDLinePtr);

	    /*
	     * Firstly unlink this line from chain.
	     */

	    if (firstPtr == dInfoPtr->dLinePtr) {
		dInfoPtr->dLinePtr = firstPtr->nextPtr;
	    }
	    if (firstPtr == dInfoPtr->lastDLinePtr) {
		dInfoPtr->lastDLinePtr = prevPtr;
	    }
	    if (prevPtr) {
		prevPtr->nextPtr = firstPtr->nextPtr;
	    }
	    if (firstPtr->nextPtr) {
		firstPtr->nextPtr->prevPtr = prevPtr;
	    }
	    firstPtr->prevPtr = NULL;

	    /*
	     * Then link into the chain of cached lines.
	     */

	    if ((firstPtr->nextPtr = dInfoPtr->cachedDLinePtr)) {
		dInfoPtr->cachedDLinePtr->prevPtr = firstPtr;
	    } else {
		dInfoPtr->lastCachedDLinePtr = firstPtr;
	    }
	    dInfoPtr->cachedDLinePtr = firstPtr;

	    DEBUG(firstPtr->flags &= ~LINKED);
	    DEBUG(firstPtr->flags |= CACHED);
	    DEBUG(stats.numCached += 1);

	    if (dInfoPtr->numCachedLines < MAX_CACHED_DISPLAY_LINES) {
		dInfoPtr->numCachedLines += 1;
		return NULL;
	    }

	    /*
	     * Release oldest cached display line.
	     */

	    if ((firstPtr = dInfoPtr->lastCachedDLinePtr)) {
		firstPtr->prevPtr->nextPtr = NULL;
	    }
	    dInfoPtr->lastCachedDLinePtr = dInfoPtr->lastCachedDLinePtr->prevPtr;
	} else {
	    if (!(firstPtr = dInfoPtr->cachedDLinePtr)) {
		return NULL;
	    }
	    dInfoPtr->cachedDLinePtr = dInfoPtr->lastCachedDLinePtr = NULL;
	    dInfoPtr->numCachedLines = 0;
	}
	ReleaseLines(textPtr, firstPtr, lastPtr, action);
	break;
    case DLINE_METRIC:
	assert(!lastPtr);
	if (dInfoPtr->lastMetricDLinePtr) {
	    ReleaseLines(textPtr, dInfoPtr->lastMetricDLinePtr, NULL, DLINE_FREE_TEMP);
	    dInfoPtr->lastMetricDLinePtr = NULL;
	}
	if (firstPtr) {
	    assert(!firstPtr->nextPtr);
	    assert(!(firstPtr->flags & (LINKED|CACHED|DELETED)));
	    dInfoPtr->lastMetricDLinePtr = firstPtr;
	    if (firstPtr->prevPtr) {
		firstPtr->prevPtr->nextPtr = NULL;
		firstPtr->prevPtr = NULL;
	    }
	}
	break;
    case DLINE_FREE_TEMP:
	if (!firstPtr || firstPtr == lastPtr) {
	    return NULL;
	}
	DEBUG(stats.lineHeightsRecalculated += 1);
	assert(!(firstPtr->flags & LINKED));
	assert(!(firstPtr->flags & CACHED));
	if (firstPtr == dInfoPtr->savedDLinePtr) {
	    dInfoPtr->savedDLinePtr = NULL;
	    if (!lastPtr) {
		dInfoPtr->lastSavedDLinePtr = NULL;
	    } else {
		dInfoPtr->savedDLinePtr = lastPtr;
	    }
	} else {
	    assert(!lastPtr || lastPtr != dInfoPtr->lastSavedDLinePtr);
	}
	assert(!dInfoPtr->savedDLinePtr == !dInfoPtr->lastSavedDLinePtr);
	ReleaseLines(textPtr, firstPtr, lastPtr, action);
	break;
    case DLINE_UNLINK:
    case DLINE_UNLINK_KEEP_BRKS:
	if (!firstPtr || firstPtr == lastPtr) {
	    return NULL;
	}
	assert(firstPtr->flags & LINKED);
	assert(firstPtr != dInfoPtr->savedDLinePtr);
	if (dInfoPtr->dLinePtr == firstPtr) {
	    if ((dInfoPtr->dLinePtr = lastPtr)) {
		lastPtr->prevPtr = NULL;
	    }
	} else {
	    DLine *prevPtr = firstPtr->prevPtr;

	    if (prevPtr && (prevPtr->nextPtr = lastPtr)) {
		lastPtr->prevPtr = prevPtr;
	    }
	}
	if (!lastPtr) {
	    dInfoPtr->lastDLinePtr = firstPtr->prevPtr;
	}
	dInfoPtr->dLinesInvalidated = 1;
	assert(!dInfoPtr->dLinePtr || !dInfoPtr->dLinePtr->prevPtr);
	ReleaseLines(textPtr, firstPtr, lastPtr, action);
	break;
    case DLINE_SAVE: {
	unsigned epoch;
	DLine *dlPtr;

	if (!firstPtr || firstPtr == lastPtr) {
	    return NULL;
	}
	assert(firstPtr == dInfoPtr->dLinePtr);
	assert(lastPtr);

	epoch = dInfoPtr->lineMetricUpdateEpoch;

	assert(lastPtr->prevPtr);
	dInfoPtr->dLinePtr = lastPtr;

	/*
	 * Free all expired lines, we will only save valid lines.
	 */

	dlPtr = firstPtr;
	while (dlPtr != lastPtr) {
	    DLine *nextPtr = dlPtr->nextPtr;

	    assert(dlPtr->flags & LINKED);

	    if (LineIsUpToDate(textPtr, dlPtr, epoch)) {
		DEBUG(dlPtr->flags &= ~LINKED);
	    } else {
		if (dlPtr == firstPtr) {
		    firstPtr = nextPtr;
		}
		ReleaseLines(textPtr, dlPtr, nextPtr, DLINE_UNLINK);
	    }

	    dlPtr = nextPtr;
	}

	assert(!firstPtr->prevPtr);

	if (firstPtr == lastPtr) {
	    dInfoPtr->savedDLinePtr = NULL;
	    dInfoPtr->lastSavedDLinePtr = NULL;
	    return NULL;
	}

	lastPtr = lastPtr->prevPtr;
	lastPtr->nextPtr->prevPtr = NULL;
	lastPtr->nextPtr = NULL;

	if (!dInfoPtr->savedDLinePtr) {
	    dInfoPtr->savedDLinePtr = firstPtr;
	    dInfoPtr->lastSavedDLinePtr = lastPtr;
	} else if (TkTextIndexCompare(&lastPtr->index, &dInfoPtr->savedDLinePtr->index) < 0) {
	    lastPtr->nextPtr = dInfoPtr->savedDLinePtr;
	    dInfoPtr->savedDLinePtr->prevPtr = lastPtr;
	    dInfoPtr->savedDLinePtr = firstPtr;
	} else {
	    assert(TkTextIndexCompare(&firstPtr->index, &dInfoPtr->lastSavedDLinePtr->index) > 0);
	    firstPtr->prevPtr = dInfoPtr->lastSavedDLinePtr;
	    dInfoPtr->lastSavedDLinePtr->nextPtr = firstPtr;
	    dInfoPtr->lastSavedDLinePtr = lastPtr;
	}

	return lastPtr;
    }
    }

    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * DisplayDLine --
 *
 *	This function is invoked to draw a single line on the screen.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The line given by dlPtr is drawn at its correct position in textPtr's
 *	window. Note that this is one *display* line, not one *text* line.
 *
 *----------------------------------------------------------------------
 */

static void
ComputeCursorExtents(
    TkText *textPtr,	/* Text widget in which to draw line. */
    int *extent1,	/* extent of left border (leak into padding area) */
    int *extent2)	/* extent of right border (leak into padding area) */
{
    /*
     * TODO: is it possible to set the extents to zero when state=READONLY.
     * We have to test whether the cursor artefacts (in padding area) are
     * already eliminated, otherwise we cannot do this optimization.
     */

    /*
     * NOTE:
     * The cursor disappears (when not using at least value 1 for the extents) if it's at the
     * very left of the first character of display line. But we prefer that the cursor is always
     * visible, thus we allow to overlap the first character in this special case.
     */

    *extent1 = MAX(1, MIN(textPtr->padX, textPtr->insertWidth/2));
    *extent2 = MAX(1, MIN(textPtr->padX, (textPtr->insertWidth + 1)/2));
}


static void
DisplayDLine(
    TkText *textPtr,	/* Text widget in which to draw line. */
    DLine *dlPtr,	/* Information about line to draw. */
    DLine *prevPtr,	/* Line just before one to draw, or NULL if dlPtr is the top line. */
    Pixmap pixmap)	/* Pixmap to use for double-buffering. Caller must make sure
			 * it's large enough to hold line. */
{
    TkTextDispChunk *chunkPtr;
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    Display *display;
    StyleValues *sValuePtr;
    int lineHeight, yOffs;
    int yBase, height, baseline, screenY, xOffs;
#ifndef TK_NO_DOUBLE_BUFFERING
    int extent1, extent2;
    const int y = 0;
#else
    const int y = dlPtr->y;
#endif /* TK_NO_DOUBLE_BUFFERING */
    int xIndent, rMargin;
    int delayBlockCursorDrawing;

    if (!dlPtr->chunkPtr) {
	return;
    }

    display = Tk_Display(textPtr->tkwin);
    delayBlockCursorDrawing = 0;

    lineHeight = dlPtr->height;
    if (lineHeight + dlPtr->y > dInfoPtr->maxY) {
	lineHeight = dInfoPtr->maxY - dlPtr->y;
    }
    if (dlPtr->y < dInfoPtr->y) {
	yOffs = dInfoPtr->y - dlPtr->y;
	lineHeight -= yOffs;
    } else {
	yOffs = 0;
    }

#ifdef TK_NO_DOUBLE_BUFFERING
    Tk_ClipDrawableToRect(display, pixmap, dInfoPtr->x, y + yOffs,
	    dInfoPtr->maxX - dInfoPtr->x, lineHeight);
#endif /* TK_NO_DOUBLE_BUFFERING */

    /*
     * First, clear the area of the line to the background color for the text widget.
     */

    Tk_Fill3DRectangle(textPtr->tkwin, pixmap, textPtr->border, 0, y,
	    Tk_Width(textPtr->tkwin), dlPtr->height, 0, TK_RELIEF_FLAT);

    /*
     * Second, draw background information for the whole line.
     */

    DisplayLineBackground(textPtr, dlPtr, prevPtr, pixmap);

    /*
     * Third, draw the background color of the left and right margins.
     */

    sValuePtr = dlPtr->firstCharChunkPtr->stylePtr->sValuePtr;
    rMargin = (sValuePtr->wrapMode == TEXT_WRAPMODE_NONE) ? 0 : sValuePtr->rMargin;
    xIndent = GetLeftLineMargin(dlPtr, sValuePtr);

    if (xIndent > 0 && sValuePtr->lMarginColor != NULL) {
	int pad = textPtr->padX ? textPtr->padX + 1 : 0;
	Tk_Fill3DRectangle(textPtr->tkwin, pixmap, sValuePtr->lMarginColor, textPtr->padX, y,
		xIndent + dInfoPtr->x - dInfoPtr->curXPixelOffset - pad,
		dlPtr->height, 0, TK_RELIEF_FLAT);
    }
    if (rMargin > 0 && sValuePtr->rMarginColor != NULL) {
	Tk_Fill3DRectangle(textPtr->tkwin, pixmap, sValuePtr->rMarginColor,
		dInfoPtr->maxX - rMargin + dInfoPtr->curXPixelOffset,
		y, rMargin, dlPtr->height, 0, TK_RELIEF_FLAT);
    }

    yBase = y + dlPtr->spaceAbove;
    height = dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow;
    baseline = dlPtr->baseline - dlPtr->spaceAbove;
    screenY = dlPtr->y + dlPtr->spaceAbove;
    xOffs = dInfoPtr->x - dInfoPtr->curXPixelOffset;

    /*
     * Redraw the insertion cursor, if it is visible on this line. Must do it here rather
     * than in the foreground pass below because otherwise a wide insertion cursor will
     * obscure the character to its left.
     *
     * If the user has specified a foreground color for characters "behind" the block cursor,
     * we have to draw the cursor after the text has been drawn, see below.
     */

    if (dlPtr->cursorChunkPtr && textPtr->state == TK_TEXT_STATE_NORMAL) {
	delayBlockCursorDrawing = dInfoPtr->insertFgGC && TkTextDrawBlockCursor(textPtr);

	if (!delayBlockCursorDrawing) {
	    dlPtr->cursorChunkPtr->layoutProcs->displayProc(textPtr, dlPtr->cursorChunkPtr,
		    dlPtr->cursorChunkPtr->x + xOffs, yBase, height, baseline, display, pixmap, screenY);
	}
    }

    /*
     * Iterate through all of the chunks to redraw all of foreground information.
     */

    for (chunkPtr = dlPtr->chunkPtr; chunkPtr; chunkPtr = chunkPtr->nextPtr) {
	if (chunkPtr == dlPtr->cursorChunkPtr) {
	    /* Don't display the insertion cursor, this will be done separately. */
	    continue;
	}

	if (chunkPtr->layoutProcs->displayProc) {
	    int x = chunkPtr->x + xOffs;

	    if (x + chunkPtr->width <= 0 || dInfoPtr->maxX <= x) {
		/*
		 * Note: we have to call the displayProc even for chunks that are off-screen.
		 * This is needed, for example, so that embedded windows can be unmapped in
		 * this case. Display the chunk at a coordinate that can be clearly identified
		 * by the displayProc as being off-screen to the left (the displayProc may not
		 * be able to tell if something is off to the right).
		 */

		x = -chunkPtr->width;
	    }

	    /*
	     * Refcount gymnastics here to prevent the resource from being released
	     * in case the displayProc destroys the widget.
	     */

	    textPtr->refCount += 1;
	    chunkPtr->layoutProcs->displayProc(textPtr, chunkPtr, x, yBase, height,
		    baseline, display, pixmap, screenY);
	    textPtr->refCount -= 1;

	    if (TkTextReleaseIfDestroyed(textPtr)) {
		/*
		 * The displayProc invoked a binding that caused the widget
		 * to be deleted. Don't do anything.
		 */
		return;
	    }

	    if (dInfoPtr->dLinesInvalidated) {
		/*
		 * The display process has invalidated any display line, so terminate,
		 * because the display process will be repeated with valid display lines.
		 */
		return;
	    }
	}
    }

    if (delayBlockCursorDrawing) {
	/*
	 * Draw the block cursor and redraw the characters "behind" the block cursor.
	 */

	int cxMin, cxMax, cWidth, cOffs;
	GC bgGC;
	XRectangle crect;
	TkRegion clipRegion;

	assert(dInfoPtr->insertFgGC != NULL);

	cxMin = dlPtr->cursorChunkPtr->x + xOffs;
	cWidth = TkTextGetCursorWidth(textPtr, &cxMin, &cOffs);

	if (cWidth > 0) {
	    if ((bgGC = dlPtr->cursorChunkPtr->stylePtr->bgGC) == NULL) {
		Tk_3DBorder border;

		if (!(border = dlPtr->cursorChunkPtr->stylePtr->sValuePtr->border)) {
		    border = textPtr->border;
		}
		bgGC = Tk_GCForColor(Tk_3DBorderColor(border), Tk_WindowId(textPtr->tkwin));
	    }

	    cxMin += cOffs;
	    cxMax = cxMin + cWidth;

	    crect.x = cxMin;
	    crect.y = yBase;
	    crect.width = cWidth;
	    crect.height = height;
	    clipRegion = TkCreateRegion();
	    TkUnionRectWithRegion(&crect, clipRegion, clipRegion);
#ifdef HAVE_XFT
	    TkUnixSetXftClipRegion(clipRegion);
#endif

	    XFillRectangle(display, pixmap, bgGC, crect.x, crect.y, crect.width, crect.height);
	    dlPtr->cursorChunkPtr->layoutProcs->displayProc(textPtr, chunkPtr, cxMin, yBase, height,
		    baseline, display, pixmap, screenY);
	    TkSetRegion(display, dInfoPtr->insertFgGC, clipRegion);

	    for (chunkPtr = dlPtr->chunkPtr; chunkPtr; chunkPtr = chunkPtr->nextPtr) {
		int x = chunkPtr->x + xOffs;

		if (x >= cxMax) {
		    break;
		}
		if (IsCharChunk(chunkPtr) && cxMin <= x + chunkPtr->width) {
		    GC fgGC = chunkPtr->stylePtr->fgGC;
		    GC eolGC = chunkPtr->stylePtr->eolGC;
		    GC eotGC = chunkPtr->stylePtr->eotGC;
		    XGCValues gcValues;
		    unsigned long mask;

		    /* Setup graphic context with font of this chunk. */
		    mask = GCFont;
		    gcValues.font = Tk_FontId(chunkPtr->stylePtr->sValuePtr->tkfont);
		    XChangeGC(Tk_Display(textPtr->tkwin), dInfoPtr->insertFgGC, mask, &gcValues);

		    chunkPtr->stylePtr->fgGC = dInfoPtr->insertFgGC;
		    chunkPtr->stylePtr->eolGC = dInfoPtr->insertFgGC;
		    chunkPtr->stylePtr->eotGC = dInfoPtr->insertFgGC;
		    chunkPtr->layoutProcs->displayProc(textPtr, chunkPtr, x, yBase, height,
			    baseline, display, pixmap, screenY);
		    chunkPtr->stylePtr->fgGC = fgGC;
		    chunkPtr->stylePtr->eolGC = eolGC;
		    chunkPtr->stylePtr->eotGC = eotGC;
		}
	    }
	    XSetClipMask(display, dInfoPtr->insertFgGC, None);
#ifdef HAVE_XFT
	    TkUnixSetXftClipRegion(NULL);
#endif
	    TkDestroyRegion(clipRegion);
	}
    }

#ifndef TK_NO_DOUBLE_BUFFERING
    /*
     * Copy the pixmap onto the screen. If this is the first or last line on
     * the screen then copy a piece of the line, so that it doesn't overflow
     * into the border area.
     *
     * Another special trick: consider the padding area left/right of the line;
     * this is because the insertion cursor sometimes overflows onto that area
     * and we want to get as much of the cursor as possible.
     */

    ComputeCursorExtents(textPtr, &extent1, &extent2);
    xOffs = MAX(0, dInfoPtr->x - extent1);
    XCopyArea(display, pixmap, Tk_WindowId(textPtr->tkwin), dInfoPtr->copyGC,
	    xOffs, y + yOffs, dInfoPtr->maxX - dInfoPtr->x + extent1 + extent2, lineHeight,
	    xOffs, dlPtr->y + yOffs);
#else
    Tk_ClipDrawableToRect(display, pixmap, 0, 0, -1, -1);
#endif /* TK_NO_DOUBLE_BUFFERING */

    DEBUG(stats.linesRedrawn += 1);
}

/*
 *--------------------------------------------------------------
 *
 * DisplayLineBackground --
 *
 *	This function is called to fill in the background for a display line.
 *	It draws 3D borders cleverly so that adjacent chunks with the same
 *	style (whether on the same line or different lines) have a single 3D
 *	border around the whole region.
 *
 * Results:
 *	There is no return value. Pixmap is filled in with background
 *	information for dlPtr.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

/*
 * The following function determines whether two styles have the same background
 * so that, for example, no beveled border should be drawn between them.
 */

static int
SameBackground(
    const TextStyle *s1,
    const TextStyle *s2)
{
    return s1->sValuePtr->border == s2->sValuePtr->border
	&& s1->sValuePtr->borderWidth == s2->sValuePtr->borderWidth
	&& s1->sValuePtr->relief == s2->sValuePtr->relief
	&& s1->sValuePtr->bgStipple == s2->sValuePtr->bgStipple
	&& s1->sValuePtr->indentBg == s2->sValuePtr->indentBg;
}

static void
DisplayLineBackground(
    TkText *textPtr,		/* Text widget containing line. */
    DLine *dlPtr,		/* Information about line to draw. */
    DLine *prevPtr,		/* Line just above dlPtr, or NULL if dlPtr is the top-most line in
				 * the window. */
    Pixmap pixmap)		/* Pixmap to use for double-buffering. Caller must make sure it's
				 * large enough to hold line. Caller must also have filled it with
				 * the background color for the widget. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    TkTextDispChunk *chunkPtr;	/* Pointer to chunk in the current line. */
    TkTextDispChunk *chunkPtr2;	/* Pointer to chunk in the line above or below the current one. NULL
				 * if we're to the left of or to the right of the chunks in the line. */
    TkTextDispChunk *nextPtr2;	/* Next chunk after chunkPtr2 (it's not the same as chunkPtr2->nextPtr
				 * in the case where chunkPtr2 is NULL because the line is indented). */
    int leftX;			/* The left edge of the region we're currently working on. */
    int leftXIn;		/* 0 means beveled edge at leftX slopes right as it goes down,
				 * 1 means it slopes left as it goes down. */
    int rightX;			/* Right edge of chunkPtr. */
    int rightX2;		/* Right edge of chunkPtr2. */
    int matchLeft;		/* Does the style of this line match that of its neighbor just to the
				 * left of the current x coordinate? */
    int matchRight;		/* Does line's style match its neighbor just to the right of the
				 * current x-coord? */
    int minX, maxX, xOffset, xIndent, borderWidth;
    StyleValues *sValuePtr;
    Display *display;
#ifndef TK_NO_DOUBLE_BUFFERING
    const int y = 0;
#else
    const int y = dlPtr->y;
#endif /* TK_NO_DOUBLE_BUFFERING */

    /*
     * Pass 1: scan through dlPtr from left to right. For each range of chunks
     * with the same style, draw the main background for the style plus the
     * vertical parts of the 3D borders (the left and right edges).
     */

    display = Tk_Display(textPtr->tkwin);
    minX = dInfoPtr->curXPixelOffset;
    xOffset = dInfoPtr->x - minX;
    maxX = minX + dInfoPtr->maxX - dInfoPtr->x;
    chunkPtr = dlPtr->chunkPtr;
    xIndent = 0;

    /*
     * Note A: in the following statement, and a few others later in this file
     * marked with "See Note A above", the right side of the assignment was
     * replaced with 0 on 6/18/97. This has the effect of highlighting the
     * empty space to the left of a line whenever the leftmost character of
     * the line is highlighted. This way, multi-line highlights always line up
     * along their left edges. However, this may look funny in the case where
     * a single word is highlighted. To undo the change, replace "leftX = 0"
     * with "leftX = chunkPtr->x" and "rightX2 = 0" with "rightX2 =
     * nextPtr2->x" here and at all the marked points below. This restores the
     * old behavior where empty space to the left of a line is not
     * highlighted, leaving a ragged left edge for multi-line highlights.
     */

    for (leftX = 0; leftX < maxX; chunkPtr = chunkPtr->nextPtr) {
	if (chunkPtr->nextPtr && SameBackground(chunkPtr->nextPtr->stylePtr, chunkPtr->stylePtr)) {
	    continue;
	}
	sValuePtr = chunkPtr->stylePtr->sValuePtr;
	rightX = chunkPtr->x + chunkPtr->width;
	if (!chunkPtr->nextPtr && rightX < maxX) {
	    rightX = maxX;
	}
	if (chunkPtr->stylePtr->bgGC != NULL) {
	    int indent = 0;

	    /*
	     * Not visible - bail out now.
	     */

	    if (rightX + xOffset <= 0) {
		leftX = rightX;
		continue;
	    }

	    /*
	     * Compute additional offset if -indentbackground is set.
	     */

	    if (leftX == 0 && sValuePtr->indentBg) {
		xIndent = GetLeftLineMargin(dlPtr, sValuePtr);
		if (leftX + xIndent > rightX) {
		    xIndent = rightX - leftX;
		}
		indent = xIndent;
	    }

	    /*
	     * Trim the start position for drawing to be no further away than -borderWidth.
	     * The reason is that on many X servers drawing from -32768 (or less) to
	     * +something simply does not display correctly. [Patch #541999]
	     */

	    if (leftX + xOffset + indent < -sValuePtr->borderWidth) {
		leftX = -sValuePtr->borderWidth - xOffset - indent;
	    }
	    if (rightX - leftX - indent > 32767) {
		rightX = leftX + indent + 32767;
	    }

	    /*
	     * Prevent the borders from leaking on adjacent characters,
	     * which would happen for too large border width.
	     */

	    borderWidth = sValuePtr->borderWidth;
	    if (leftX + sValuePtr->borderWidth > rightX) {
		borderWidth = rightX - leftX;
	    }

	    XFillRectangle(display, pixmap, chunkPtr->stylePtr->bgGC,
		    leftX + xOffset + indent, y, rightX - leftX - indent, dlPtr->height);
	    if (sValuePtr->relief != TK_RELIEF_FLAT) {
		Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border,
			leftX + xOffset + indent, y, borderWidth,
			dlPtr->height, 1, sValuePtr->relief);
		Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border,
			rightX - borderWidth + xOffset, y, borderWidth,
			dlPtr->height, 0, sValuePtr->relief);
	    }
	}
	leftX = rightX;
    }

    /*
     * Pass 2: draw the horizontal bevels along the top of the line. To do
     * this, scan through dlPtr from left to right while simultaneously
     * scanning through the line just above dlPtr. ChunkPtr2 and nextPtr2
     * refer to two adjacent chunks in the line above.
     */

    chunkPtr = dlPtr->chunkPtr;
    leftX = 0;				/* See Note A above. */
    leftXIn = 1;
    rightX = chunkPtr->x + chunkPtr->width;
    if (!chunkPtr->nextPtr && rightX < maxX) {
	rightX = maxX;
    }
    chunkPtr2 = NULL;
    if (prevPtr && prevPtr->chunkPtr) {
	/*
	 * Find the chunk in the previous line that covers leftX.
	 */

	nextPtr2 = prevPtr->chunkPtr;
	rightX2 = 0;			/* See Note A above. */
	while (rightX2 <= leftX) {
	    if (!(chunkPtr2 = nextPtr2)) {
		break;
	    }
	    nextPtr2 = chunkPtr2->nextPtr;
	    rightX2 = chunkPtr2->x + chunkPtr2->width;
	    if (!nextPtr2) {
		rightX2 = INT_MAX;
	    }
	}
    } else {
	nextPtr2 = NULL;
	rightX2 = INT_MAX;
    }

    while (leftX < maxX) {
	matchLeft = chunkPtr2 && SameBackground(chunkPtr2->stylePtr, chunkPtr->stylePtr);
	sValuePtr = chunkPtr->stylePtr->sValuePtr;
	if (rightX <= rightX2) {
	    /*
	     * The chunk in our line is about to end. If its style changes
	     * then draw the bevel for the current style.
	     */

	    if (!chunkPtr->nextPtr
		    || !SameBackground(chunkPtr->stylePtr, chunkPtr->nextPtr->stylePtr)) {
		if (!matchLeft && sValuePtr->relief != TK_RELIEF_FLAT) {
		    int indent = (leftX == 0) ? xIndent : 0;
		    Tk_3DHorizontalBevel(textPtr->tkwin, pixmap,
			    sValuePtr->border, leftX + xOffset + indent, y,
			    rightX - leftX - indent, sValuePtr->borderWidth,
			    leftXIn, 1, 1, sValuePtr->relief);
		}
		leftX = rightX;
		leftXIn = 1;

		/*
		 * If the chunk in the line above is also ending at the same
		 * point then advance to the next chunk in that line.
		 */

		if (rightX == rightX2 && chunkPtr2) {
		    goto nextChunk2;
		}
	    }
	    chunkPtr = chunkPtr->nextPtr;
	    if (!chunkPtr) {
		break;
	    }
	    rightX = chunkPtr->x + chunkPtr->width;
	    if (!chunkPtr->nextPtr && rightX < maxX) {
		rightX = maxX;
	    }
	    continue;
	}

	/*
	 * The chunk in the line above is ending at an x-position where there
	 * is no change in the style of the current line. If the style above
	 * matches the current line on one side of the change but not on the
	 * other, we have to draw an L-shaped piece of bevel.
	 */

	matchRight = nextPtr2 && SameBackground(nextPtr2->stylePtr, chunkPtr->stylePtr);
	if (matchLeft && !matchRight) {
	    borderWidth = sValuePtr->borderWidth;
	    if (rightX2 - borderWidth < leftX) {
		borderWidth = rightX2 - leftX;
	    }
	    if (sValuePtr->relief != TK_RELIEF_FLAT) {
		Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border,
			rightX2 - borderWidth + xOffset, y, borderWidth,
			sValuePtr->borderWidth, 0, sValuePtr->relief);
	    }
	    leftX = rightX2 - borderWidth;
	    leftXIn = 0;
	} else if (!matchLeft && matchRight && sValuePtr->relief != TK_RELIEF_FLAT) {
	    int indent = (leftX == 0) ? xIndent : 0;
	    borderWidth = sValuePtr->borderWidth;
	    if (rightX2 + borderWidth > rightX) {
		borderWidth = rightX - rightX2;
	    }
	    Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border, rightX2 + xOffset,
		    y, borderWidth, sValuePtr->borderWidth, 1, sValuePtr->relief);
	    Tk_3DHorizontalBevel(textPtr->tkwin, pixmap, sValuePtr->border,
		    leftX + xOffset + indent, y,
		    rightX2 + borderWidth - leftX - indent,
		    sValuePtr->borderWidth, leftXIn, 0, 1,
		    sValuePtr->relief);
	}

    nextChunk2:
	chunkPtr2 = nextPtr2;
	if (!chunkPtr2) {
	    rightX2 = INT_MAX;
	} else {
	    nextPtr2 = chunkPtr2->nextPtr;
	    rightX2 = chunkPtr2->x + chunkPtr2->width;
	    if (!nextPtr2) {
		rightX2 = INT_MAX;
	    }
	}
    }

    /*
     * Pass 3: draw the horizontal bevels along the bottom of the line. This
     * uses the same approach as pass 2.
     */

    chunkPtr = dlPtr->chunkPtr;
    leftX = 0;				/* See Note A above. */
    leftXIn = 0;
    rightX = chunkPtr->x + chunkPtr->width;
    if (!chunkPtr->nextPtr && rightX < maxX) {
	rightX = maxX;
    }
    chunkPtr2 = NULL;
    if (dlPtr->nextPtr && dlPtr->nextPtr->chunkPtr) {
	/*
	 * Find the chunk in the next line that covers leftX.
	 */

	nextPtr2 = dlPtr->nextPtr->chunkPtr;
	rightX2 = 0;			/* See Note A above. */
	while (rightX2 <= leftX) {
	    chunkPtr2 = nextPtr2;
	    if (!chunkPtr2) {
		break;
	    }
	    nextPtr2 = chunkPtr2->nextPtr;
	    rightX2 = chunkPtr2->x + chunkPtr2->width;
	    if (!nextPtr2) {
		rightX2 = INT_MAX;
	    }
	}
    } else {
	nextPtr2 = NULL;
	rightX2 = INT_MAX;
    }

    while (leftX < maxX) {
	matchLeft = chunkPtr2 && SameBackground(chunkPtr2->stylePtr, chunkPtr->stylePtr);
	sValuePtr = chunkPtr->stylePtr->sValuePtr;
	if (rightX <= rightX2) {
	    if (!chunkPtr->nextPtr
		    || !SameBackground(chunkPtr->stylePtr, chunkPtr->nextPtr->stylePtr)) {
		if (!matchLeft && sValuePtr->relief != TK_RELIEF_FLAT) {
		    int indent = (leftX == 0) ? xIndent : 0;
		    Tk_3DHorizontalBevel(textPtr->tkwin, pixmap,
			    sValuePtr->border, leftX + xOffset + indent,
			    y + dlPtr->height - sValuePtr->borderWidth,
			    rightX - leftX - indent, sValuePtr->borderWidth,
			    leftXIn, 0, 0, sValuePtr->relief);
		}
		leftX = rightX;
		leftXIn = 0;
		if (rightX == rightX2 && chunkPtr2) {
		    goto nextChunk2b;
		}
	    }
	    chunkPtr = chunkPtr->nextPtr;
	    if (!chunkPtr) {
		break;
	    }
	    rightX = chunkPtr->x + chunkPtr->width;
	    if (!chunkPtr->nextPtr && rightX < maxX) {
		rightX = maxX;
	    }
	    continue;
	}

	matchRight = nextPtr2 && SameBackground(nextPtr2->stylePtr, chunkPtr->stylePtr);
	if (matchLeft && !matchRight) {
	    borderWidth = sValuePtr->borderWidth;
	    if (rightX2 - borderWidth < leftX) {
		borderWidth = rightX2 - leftX;
	    }
	    if (sValuePtr->relief != TK_RELIEF_FLAT) {
		Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border,
			rightX2 - borderWidth + xOffset,
			y + dlPtr->height - sValuePtr->borderWidth,
			borderWidth, sValuePtr->borderWidth, 0,
			sValuePtr->relief);
	    }
	    leftX = rightX2 - borderWidth;
	    leftXIn = 1;
	} else if (!matchLeft && matchRight && sValuePtr->relief != TK_RELIEF_FLAT) {
	    int indent = (leftX == 0) ? xIndent : 0;
	    borderWidth = sValuePtr->borderWidth;
	    if (rightX2 + borderWidth > rightX) {
		borderWidth = rightX - rightX2;
	    }
	    Tk_3DVerticalBevel(textPtr->tkwin, pixmap, sValuePtr->border,
		    rightX2 + xOffset, y + dlPtr->height - sValuePtr->borderWidth,
		    borderWidth, sValuePtr->borderWidth, 1, sValuePtr->relief);
	    Tk_3DHorizontalBevel(textPtr->tkwin, pixmap, sValuePtr->border,
		    leftX + xOffset + indent, y + dlPtr->height - sValuePtr->borderWidth,
		    rightX2 + borderWidth - leftX - indent, sValuePtr->borderWidth,
		    leftXIn, 1, 0, sValuePtr->relief);
	}

    nextChunk2b:
	chunkPtr2 = nextPtr2;
	if (!chunkPtr2) {
	    rightX2 = INT_MAX;
	} else {
	    nextPtr2 = chunkPtr2->nextPtr;
	    rightX2 = chunkPtr2->x + chunkPtr2->width;
	    if (!nextPtr2) {
		rightX2 = INT_MAX;
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * AsyncUpdateLineMetrics --
 *
 *	This function is invoked as a background handler to update the pixel-
 *	height calculations of individual lines in an asychronous manner.
 *
 *	Currently a timer-handler is used for this purpose, which continuously
 *	reschedules itself. It may well be better to use some other approach
 *	(e.g., a background thread). We can't use an idle-callback because of
 *	a known bug in Tcl/Tk in which idle callbacks are not allowed to
 *	re-schedule themselves. This just causes an effective infinite loop.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Line heights may be recalculated.
 *
 *----------------------------------------------------------------------
 */

static void
AsyncUpdateLineMetrics(
    void *clientData)	/* Information about widget. */
{
    TkText *textPtr = (TkText *)clientData;
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    dInfoPtr->lineUpdateTimer = NULL;

    if (TkTextReleaseIfDestroyed(textPtr)) {
	return;
    }

    if (!textPtr->sharedTextPtr->allowUpdateLineMetrics) {
	/* not yet configured */
    } else if (dInfoPtr->flags & REDRAW_PENDING) {
	dInfoPtr->flags |= ASYNC_PENDING|ASYNC_UPDATE;
    } else {
	/*
	 * Update the lines in blocks of about 24 recalculations, or 250+ lines
	 * examined, so we pass in 256 for 'doThisMuch'.
	 */

	UpdateLineMetrics(textPtr, 256);
	TK_TEXT_DEBUG(LogTextInvalidateLine(textPtr, 0));

	if (TkRangeListIsEmpty(dInfoPtr->lineMetricUpdateRanges)) {
	    /*
	     * We have looped over all lines, so we're done. We must release our
	     * refCount on the widget (the timer token was already set to NULL
	     * above). If there is a registered aftersync command, run that first.
	     */

	    if (!dInfoPtr->pendingUpdateLineMetricsFinished) {
		UpdateLineMetricsFinished(textPtr, 0);
		GetYView(textPtr->interp, textPtr, 1);
	    }
	} else {
	    /*
	     * Re-arm the timer. We already have a refCount on the text widget so no
	     * need to adjust that.
	     */

	    dInfoPtr->lineUpdateTimer = Tcl_CreateTimerHandler(1, AsyncUpdateLineMetrics, textPtr);
	    return;
	}
    }

    TkTextDecrRefCountAndTestIfDestroyed(textPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * UpdateLineMetrics --
 *
 *	This function updates the pixel height calculations of a range of
 *	lines in the widget. The range is from lineNum to endLine, but
 *	this function may return earlier, once a certain number of lines
 *	has been examined. The line counts are from 0.
 *
 * Results:
 *	The index of the last line examined (or zero if we are about to wrap
 *	around from end to beginning of the widget).
 *
 * Side effects:
 *	Line heights may be recalculated.
 *
 *----------------------------------------------------------------------
 */

static unsigned
NextLineNum(
    TkTextLine *linePtr,
    unsigned lineNum,
    const TkTextIndex *indexPtr)
{
    TkText *textPtr;

    assert(indexPtr->textPtr);

    if (linePtr->nextPtr == TkTextIndexGetLine(indexPtr)) {
	return lineNum + 1;
    }

    textPtr = indexPtr->textPtr;
    return TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, TkTextIndexGetLine(indexPtr), NULL);
}

static void
UpdateLineMetrics(
    TkText *textPtr,		/* Information about widget. */
    unsigned doThisMuch)	/* How many lines to check, or how many 10s of lines to recalculate. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    const TkRange *range = TkRangeListFirst(dInfoPtr->lineMetricUpdateRanges);
    unsigned maxDispLines = UINT_MAX;
    unsigned count = 0;

    assert(textPtr->sharedTextPtr->allowUpdateLineMetrics);

    while (range) {
	TkTextLine *linePtr;
	TkTextLine *logicalLinePtr;
	int lineNum = range->low;
	int high = range->high;

	assert(lineNum < TkrBTreeNumLines(textPtr->sharedTextPtr->tree, textPtr));

	linePtr = TkBTreeFindLine(textPtr->sharedTextPtr->tree, textPtr, lineNum);
	logicalLinePtr = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);

	if (linePtr != logicalLinePtr) {
	    lineNum = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, logicalLinePtr, NULL);
	    linePtr = logicalLinePtr;
	}

	while (lineNum <= high) {
	    TkTextPixelInfo *pixelInfo;

	    TK_TEXT_DEBUG(LogTextInvalidateLine(textPtr, count));

	    /*
	     * Now update the line's metrics if necessary.
	     */

	    pixelInfo = TkBTreeLinePixelInfo(textPtr, linePtr);

	    if (pixelInfo->epoch == dInfoPtr->lineMetricUpdateEpoch) {
		int firstLineNum = lineNum;

		/*
		 * This line is already up to date. That means there's nothing to do here.
		 */

		if (linePtr->nextPtr->logicalLine) {
		    linePtr = linePtr->nextPtr;
		    lineNum += 1;
		} else {
		    linePtr = TkBTreeNextLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
		    lineNum = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, linePtr, NULL);
		}

		TkRangeListRemove(dInfoPtr->lineMetricUpdateRanges, firstLineNum, lineNum - 1);
	    } else {
		TkTextIndex index;

		TkTextIndexClear(&index, textPtr);
		TkTextIndexSetToStartOfLine2(&index, linePtr);

		/*
		 * Update the line and update the counter, counting 8 for each display line
		 * we actually re-layout. But in case of synchronous update we do a full
		 * computation.
		 */

		if (textPtr->syncTime > 0) {
		    maxDispLines = (doThisMuch - count + 7)/8;
		}
		count += 8*UpdateOneLine(textPtr, linePtr, &index, maxDispLines);

		if (pixelInfo->epoch & PARTIAL_COMPUTED_BIT) {
		    /*
		     * We didn't complete the logical line, because it produced very many
		     * display lines - it must be a long line wrapped many times.
		     */
		    return;
		}

		/*
		 * We're done with this line.
		 */

		lineNum = NextLineNum(linePtr, lineNum, &index);
		linePtr = TkTextIndexGetLine(&index);
	    }

	    if ((++count >= doThisMuch)) {
		return;
	    }
	}

	/* The update process has removed the finished lines. */
	range = TkRangeListFirst(dInfoPtr->lineMetricUpdateRanges);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextUpdateLineMetrics --
 *
 *	This function updates the pixel height calculations of a range of
 *	lines in the widget. The range is from lineNum to endLine. The line
 *	counts are from 0.
 *
 *	All lines in the range will be updated. This will potentially take
 *	quite some time for a large range of lines.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Line heights may be recalculated.
 *
 *----------------------------------------------------------------------
 */

void
TkTextUpdateLineMetrics(
    TkText *textPtr,		/* Information about widget. */
    unsigned lineNum,		/* Start at this line. */
    unsigned endLine)		/* Go no further than this line. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    const TkRange *range;
    unsigned totalLines = TkrBTreeNumLines(textPtr->sharedTextPtr->tree, textPtr);
    int fullUpdateRequested = (lineNum == 0 && endLine == totalLines);

    assert(lineNum <= endLine);
    assert(endLine <= totalLines);
    assert(textPtr->sharedTextPtr->allowUpdateLineMetrics);

    dInfoPtr->insideLineMetricUpdate = 1;

    if ((range = TkRangeListFindNearest(dInfoPtr->lineMetricUpdateRanges, lineNum))) {
	TkTextLine *linePtr = NULL;
	unsigned count = 0;
	unsigned high = range->high;

	lineNum = range->low;
	endLine = MIN(endLine, totalLines - 1);
	assert(lineNum < totalLines);

	while (1) {
	    const TkTextPixelInfo *pixelInfo;
	    int firstLineNum;

	    if (lineNum > high) {
		/*
		 * Note that the update process has removed the finished lines.
		 */

		if (!(range = TkRangeListFindNearest(dInfoPtr->lineMetricUpdateRanges, lineNum))) {
		    break;
		}
		linePtr = NULL;
		lineNum = range->low;
		high = range->high;
	    }

	    if (lineNum > endLine) {
		break;
	    }

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

	    TK_TEXT_DEBUG(LogTextInvalidateLine(textPtr, count));
	    assert(linePtr->nextPtr);

	    pixelInfo = TkBTreeLinePixelInfo(textPtr, linePtr);

	    if (pixelInfo->epoch != dInfoPtr->lineMetricUpdateEpoch) {
		TkTextIndex index;

		/*
		 * This line is not (fully) up-to-date.
		 */

		TkTextIndexClear(&index, textPtr);
		TkTextIndexSetToStartOfLine2(&index, linePtr);
		UpdateOneLine(textPtr, linePtr, &index, UINT_MAX);
		assert(IsStartOfNotMergedLine(&index) || TkTextIndexIsEndOfText(&index));
		firstLineNum = -1; /* the update has removed the line numbers from range list */
	    } else {
		firstLineNum = lineNum;
	    }

	    if (linePtr->nextPtr->logicalLine) {
		linePtr = linePtr->nextPtr;
		lineNum += 1;
	    } else {
		linePtr = TkBTreeNextLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
		lineNum = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, linePtr, NULL);
	    }

	    if (firstLineNum >= 0) {
		TkRangeListRemove(dInfoPtr->lineMetricUpdateRanges, firstLineNum, lineNum - 1);
	    }
	}
    }

    dInfoPtr->insideLineMetricUpdate = 0;
    CheckIfLineMetricIsUpToDate(textPtr);
    if (fullUpdateRequested) {
	TkTextGenerateWidgetViewSyncEvent(textPtr, 1);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextInvalidateLineMetrics, TextInvalidateLineMetrics --
 *
 *	Mark a number of text lines as having invalid line metric
 *	calculations. Depending on 'action' which indicates whether
 *	the given lines are simply invalid or have been inserted or
 *	deleted, the pre-existing asynchronous line update range may
 *	need to be adjusted.
 *
 *	If linePtr is NULL then 'lineCount' and 'action' are ignored
 *	and all lines are invalidated.
 *
 *	If linePtr is the last (artificial) line, then do nothing.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	May schedule an asychronous callback.
 *
 *----------------------------------------------------------------------
 */

static void
ResetPixelInfo(
    TkTextPixelInfo *pixelInfo)
{
    TkTextDispLineInfo *dispLineInfo = pixelInfo->dispLineInfo;

    if (dispLineInfo) {
	if (pixelInfo->epoch & PARTIAL_COMPUTED_BIT) {
	    dispLineInfo->numDispLines = dispLineInfo->entry[dispLineInfo->numDispLines].pixels;
	}
    }
    pixelInfo->epoch = 0;
}

static void
StartAsyncLineCalculation(
    TkText *textPtr)
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    if (!textPtr->sharedTextPtr->allowUpdateLineMetrics) {
	return;
    }

    /*
     * Reset cached chunk.
     */

    dInfoPtr->currChunkPtr = NULL;
    InvokeAsyncUpdateLineMetrics(textPtr);

    if (!(dInfoPtr->flags & ASYNC_UPDATE)) {
	dInfoPtr->flags |= ASYNC_UPDATE;
	TkTextGenerateWidgetViewSyncEvent(textPtr, 0);
    }
}

static void
TextInvalidateLineMetrics(
    TkText *textPtr,		/* Widget record for text widget. */
    TkTextLine *linePtr,	/* Invalidation starts from this line; can be NULL, but only in
				 * case of simple invalidation. */
    unsigned lineCount,		/* And includes this amount of following lines. */
    TkTextInvalidateAction action)
				/* Indicates what type of invalidation occurred (insert, delete,
				 * or simple). */
{
    TkRangeList *ranges = textPtr->dInfoPtr->lineMetricUpdateRanges;
    unsigned totalLines = TkrBTreeNumLines(textPtr->sharedTextPtr->tree, textPtr);
    unsigned epoch = textPtr->dInfoPtr->lineMetricUpdateEpoch;
    int isMonospaced = UseMonospacedLineHeights(textPtr);
    unsigned lineNum = 0; /* suppress compiler warning */

    assert(linePtr || action == TK_TEXT_INVALIDATE_ONLY);
    assert(TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, linePtr, NULL) + lineCount
	    < totalLines + (action == TK_TEXT_INVALIDATE_INSERT
			    || action == TK_TEXT_INVALIDATE_DELETE
			    || action == TK_TEXT_INVALIDATE_REINSERTED));

    if (linePtr) {
	int deviation;

	lineNum = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, linePtr, &deviation);

	assert(deviation >= 0);

	if (deviation) {
	    lineCount -= MIN((int) lineCount, deviation);
	}
	if (action == TK_TEXT_INVALIDATE_INSERT
		&& !isMonospaced
		&& linePtr == TkBTreeGetStartLine(textPtr)
		&& lineCount + 1 >= totalLines) {
	    linePtr = NULL;
	}
    } else if (isMonospaced) {
	linePtr = TkBTreeGetStartLine(textPtr);
	lineCount = totalLines;
    }

    if (linePtr) {
	if (TkRangeListSize(ranges) >= 200) {
	    /*
	     * The range list is a great data structure for fast management of update
	     * information, but this list is not designed for a large amount of entries.
	     * If this arbitrarily chosen number of entries has been reached we will
	     * compact the list, because in this case the line traversal may be faster
	     * than the management of this list. Note that reaching this point is in
	     * general not expected, especially since the range list is amalgamating
	     * adjacent ranges automatically.
	     */

	    int low = TkRangeListLow(ranges);
	    int high = TkRangeListHigh(ranges);

	    TkRangeListClear(ranges);
	    ranges = TkRangeListAdd(ranges, low, high);
	}

	switch (action) {
	case TK_TEXT_INVALIDATE_REINSERTED: {
	    /*
	     * Special case: the very last line has been re-inserted.
	     */
	    assert(lineNum == totalLines);
	    assert(lineNum > 0);
	    TkRangeListTruncateAtEnd(ranges, lineNum - 1);
	    TkBTreeResetDisplayLineCounts(textPtr, linePtr, 1);
	    break;
	}
	case TK_TEXT_INVALIDATE_ONLY: {
	    int counter = MIN(lineCount, totalLines - lineNum);

	    if (isMonospaced) {
		TkBTreeUpdatePixelHeights(textPtr, linePtr, lineCount, epoch);
	    } else {
		TkTextLine *logicalLinePtr;

		ranges = TkRangeListAdd(ranges, lineNum, lineNum + lineCount);
		logicalLinePtr = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
		ResetPixelInfo(TkBTreeLinePixelInfo(textPtr, logicalLinePtr));

		if (!TkRangeListContainsRange(ranges, lineNum + 1, lineNum + counter)) {
		    /*
		     * Invalidate the height calculations of each line in the given range.
		     * Note that normally only a few lines will be invalidated (in current
		     * case with simple invalidation). Also note that the other cases
		     * (insert, delete) do not need invalidation of single lines, because
		     * inserted lines should be invalid per default, and deleted lines don't
		     * need invalidation at all.
		     */

		    for ( ; counter > 0; --counter) {
			linePtr = linePtr->nextPtr;
			if (linePtr->logicalLine) {
			    ResetPixelInfo(TkBTreeLinePixelInfo(textPtr, linePtr));
			}
		    }
		}
	    }
	    break;
	}
	case TK_TEXT_INVALIDATE_ELIDE: {
	    int counter = MIN(lineCount, totalLines - lineNum);

	    if (isMonospaced) {
		TkBTreeUpdatePixelHeights(textPtr, linePtr, lineCount, epoch);
	    } else {
		TkTextLine *mergedLinePtr = NULL;
		unsigned count;

		if (!linePtr->logicalLine) {
#if 1		    /* TODO: is this sufficient? */
		    assert(linePtr->prevPtr);
		    linePtr = linePtr->prevPtr;
		    lineNum -= 1;
		    lineCount += 1;
#else		    /* TODO: this is sufficient anyway! */
		    TkTextLine *logicalLinePtr =
			    TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);

		    count = TkBTreeCountLines(textPtr->sharedTextPtr->tree, logicalLinePtr, linePtr);
		    lineNum -= count;
		    lineCount += count;
#endif
		}

		ranges = TkRangeListAdd(ranges, lineNum, lineNum + lineCount);
		count = 1;

		/*
		 * Invalidate the height calculations of each line in the given range.
		 * For merged lines (any line which is not a logical line) we have to
		 * reset the display line count.
		 */

		for ( ; counter > 0; --counter, linePtr = linePtr->nextPtr) {
		    if (linePtr->logicalLine) {
			if (mergedLinePtr) {
			    TkBTreeResetDisplayLineCounts(textPtr, mergedLinePtr, count);
			    mergedLinePtr = NULL;
			}
			ResetPixelInfo(TkBTreeLinePixelInfo(textPtr, linePtr));
		    } else {
			if (!mergedLinePtr) {
			    mergedLinePtr = linePtr;
			    count = 1;
			} else {
			    count += 1;
			}
		    }
		}
		if (mergedLinePtr) {
		    TkBTreeResetDisplayLineCounts(textPtr, mergedLinePtr, count);
		}
	    }
	    break;
	}
	case TK_TEXT_INVALIDATE_DELETE:
	    textPtr->dInfoPtr->lastLineNo -= lineCount;
	    if (isMonospaced) {
		return;
	    }
	    if (lineCount > 0) {
		TkTextIndex index;
		DLine *dlPtr;

		TkRangeListDelete(ranges, lineNum + 1, lineNum + lineCount);

		/*
		 * Free all display lines in specified range. This is required, otherwise
		 * it may happen that we are accessing deleted (invalid) data (bug in
		 * old implementation).
		 */

		TkTextIndexClear(&index, textPtr);
		TkTextIndexSetToStartOfLine2(&index, linePtr->nextPtr);
		if ((dlPtr = FindDLine(textPtr, textPtr->dInfoPtr->dLinePtr, &index))) {
		    TkTextIndexSetToEndOfLine2(&index,
			    TkBTreeFindLine(textPtr->sharedTextPtr->tree, textPtr, lineNum + lineCount));
		    FreeDLines(textPtr, dlPtr, FindDLine(textPtr, dlPtr, &index), DLINE_UNLINK);
		}
	    }
	    if (lineNum + lineCount < totalLines) {
		ranges = TkRangeListAdd(ranges, lineNum, lineNum);
	    } else {
		TkRangeListTruncateAtEnd(ranges, lineNum - 1);
		ResetPixelInfo(TkBTreeLinePixelInfo(textPtr,
			textPtr->sharedTextPtr->endMarker->sectionPtr->linePtr));
	    }
	    ResetPixelInfo(TkBTreeLinePixelInfo(textPtr,
		    TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr)));
	    break;
	case TK_TEXT_INVALIDATE_INSERT:
	    if (lineCount > 0 && lineNum + 1 < totalLines) {
		int lastLine = MIN(lineNum + lineCount, totalLines - 1);
		ranges = TkRangeListInsert(ranges, lineNum + 1, lastLine);
	    }
	    textPtr->dInfoPtr->lastLineNo += lineCount;
	    if (isMonospaced) {
		TkBTreeUpdatePixelHeights(textPtr, linePtr, lineCount, epoch);
	    } else {
		ranges = TkRangeListAdd(ranges, lineNum, lineNum);
		ResetPixelInfo(TkBTreeLinePixelInfo(textPtr,
			TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr)));
	    }
	    break;
	}

	assert(TkRangeListIsEmpty(ranges) || TkRangeListHigh(ranges) < (int) totalLines);
    } else {
	/*
	 * This invalidates the height of all lines in the widget.
	 */

	textPtr->dInfoPtr->lineMetricUpdateEpoch += 1;
	textPtr->dInfoPtr->lastLineNo += lineCount;
	if (totalLines > 0) {
	    ranges = TkRangeListAdd(ranges, 0, totalLines - 1);
	}
    }

    FreeDLines(textPtr, NULL, NULL, DLINE_CACHE);  /* clear cache */
    FreeDLines(textPtr, NULL, NULL, DLINE_METRIC); /* clear cache */
    FreeDLines(textPtr, textPtr->dInfoPtr->savedDLinePtr, NULL, DLINE_FREE_TEMP);
    textPtr->dInfoPtr->lineMetricUpdateRanges = ranges;
    textPtr->dInfoPtr->currChunkPtr = NULL;

    if (textPtr->syncTime == 0) {
#if 0 /* TODO: is it required to update 'lastLineNo' at this place? */
	textPtr->dInfoPtr->lastLineNo = TkrBTreeNumLines(textPtr->sharedTextPtr->tree, NULL);
#endif
    } else {
	StartAsyncLineCalculation(textPtr);
    }
}

void
TkTextInvalidateLineMetrics(
    TkSharedText *sharedTextPtr,/* Shared widget section for all peers, or NULL. */
    TkText *textPtr,		/* Widget record for text widget. */
    TkTextLine *linePtr,	/* Invalidation starts from this line. */
    unsigned lineCount,		/* And includes this many following lines. */
    TkTextInvalidateAction action)
				/* Indicates what type of invalidation occurred (insert,
				 * delete, or simple). */
{
    if (!sharedTextPtr) {
	TextInvalidateLineMetrics(textPtr, linePtr, lineCount, action);
    } else {
	textPtr = sharedTextPtr->peers;

	while (textPtr) {
	    int numLines = lineCount;
	    TkTextLine *firstLinePtr = linePtr;

	    if (textPtr->startMarker != sharedTextPtr->startMarker) {
		TkTextLine *startLinePtr = TkBTreeGetStartLine(textPtr);
		unsigned lineNo = TkBTreeLinesTo(sharedTextPtr->tree, NULL, firstLinePtr, NULL);
		unsigned firstLineNo = TkBTreeLinesTo(sharedTextPtr->tree, NULL, startLinePtr, NULL);

		if (firstLineNo > lineNo) {
		    firstLinePtr = startLinePtr;
		    numLines -= firstLineNo - lineNo;
		}
	    }
	    if (textPtr->endMarker != sharedTextPtr->endMarker) {
		TkTextLine *lastLinePtr = TkBTreeGetLastLine(textPtr);
		unsigned lineNo = TkBTreeLinesTo(sharedTextPtr->tree, NULL, firstLinePtr, NULL);
		unsigned endLineNo = TkBTreeLinesTo(sharedTextPtr->tree, NULL, lastLinePtr, NULL);

		if (endLineNo <= lineNo + numLines) {
		    numLines = endLineNo - lineNo - 1;
		}
	    }

	    if (numLines >= 0) {
		TextInvalidateLineMetrics(textPtr, firstLinePtr, numLines, action);
	    }

	    textPtr = textPtr->next;
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextFindDisplayIndex -
 *
 *	This function is computing the index of display line start; the
 *	computation starts at given index, and is searching some display
 *	lines forward or backward, as specified with 'displayLineOffset'.
 *
 * Results:
 *	Modifies indexPtr to point to the wanted display line start.
 *
 *	If xOffset is non-NULL, it is set to the x-pixel offset of the given
 *	original index within the given display line.
 *
 * Side effects:
 *	See 'LayoutDLine' and 'FreeDLines'.
 *
 *----------------------------------------------------------------------
 */

void
TkTextFindDisplayIndex(
    TkText *textPtr,
    TkTextIndex *indexPtr,
    int displayLineOffset,
    int *xOffset)
{
    DisplayInfo info;
    TkTextLine *linePtr;
    TkTextLine *lastLinePtr;
    unsigned byteOffset;
    int upToDate;
    int myXOffset;

    assert(textPtr);

    if (!xOffset) {
	xOffset = &myXOffset;
    }

    lastLinePtr = TkBTreeGetLastLine(textPtr);
    linePtr = TkTextIndexGetLine(indexPtr);

    if (displayLineOffset >= 0 && linePtr == lastLinePtr) {
	*xOffset = 0;
	return;
    }
    if (displayLineOffset <= 0 && TkTextIndexIsStartOfText(indexPtr)) {
	*xOffset = 0;
	return;
    }

    if (linePtr == lastLinePtr) {
	displayLineOffset += 1;
	*xOffset = 0;
	xOffset = NULL;
	TkTextIndexSetToLastChar2(indexPtr, linePtr->prevPtr);
    }

    if (displayLineOffset > 0) {
	upToDate = TkRangeListIsEmpty(textPtr->dInfoPtr->lineMetricUpdateRanges);
    } else {
	upToDate = TestIfLinesUpToDate(indexPtr);
    }
    linePtr = ComputeDisplayLineInfo(textPtr, indexPtr, &info);

    if (xOffset) {
	if (IsStartOfNotMergedLine(indexPtr)) {
	    *xOffset = 0;
	} else {
	    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
	    DLine *dlPtr = info.lastDLinePtr;
	    TkTextIndex index = *indexPtr;

	    TkrTextIndexBackBytes(textPtr, &index, info.byteOffset, &index);

	    if (!dlPtr) {
		dlPtr = FindCachedDLine(textPtr, indexPtr);

		if (!dlPtr
			&& !(dInfoPtr->flags & DINFO_OUT_OF_DATE)
			&& TkTextIndexCompare(indexPtr, &textPtr->topIndex) >= 0) {
		    dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, indexPtr);
		}
		if (!dlPtr) {
		    dlPtr = LayoutDLine(&index, info.displayLineNo);
		    FreeDLines(textPtr, dlPtr, NULL, DLINE_CACHE);
		}
	    }

	    *xOffset = DLineXOfIndex(textPtr, dlPtr, TkTextIndexCountBytes(&dlPtr->index, indexPtr));
	}
    }

    if (upToDate) {
	const TkTextDispLineInfo *dispLineInfo;

	assert(!info.dLinePtr);

	/*
	 * The display line information is complete for the required range, so
	 * use it for finding the requested display line.
	 */

	if (displayLineOffset == 0) {
	    byteOffset = info.entry->byteOffset;
	} else {
	    if (displayLineOffset > 0) {
		linePtr = TkBTreeNextDisplayLine(textPtr, linePtr, &info.displayLineNo,
			displayLineOffset);
	    } else {
		linePtr = TkBTreePrevDisplayLine(textPtr, linePtr, &info.displayLineNo,
			-displayLineOffset);
	    }
	    dispLineInfo = TkBTreeLinePixelInfo(textPtr, linePtr)->dispLineInfo;
	    byteOffset = dispLineInfo ? dispLineInfo->entry[info.displayLineNo].byteOffset : 0;
	}
    } else {
	unsigned removedLines;

	/*
	 * We want to cache last produced display line, because it's likely that this
	 * line will be used afterwards.
	 */

	removedLines = 0;
	if (info.lastDLinePtr) {
	    DLine *prevPtr = info.lastDLinePtr->prevPtr;
	    FreeDLines(textPtr, info.lastDLinePtr, NULL, DLINE_CACHE);
	    if (info.dLinePtr == info.lastDLinePtr) { info.dLinePtr = NULL; }
	    info.lastDLinePtr = prevPtr;
	    info.numCachedLines -= 1;
	    removedLines = 1;
	}

	TkrTextIndexBackBytes(textPtr, indexPtr, info.byteOffset, indexPtr);

	if (displayLineOffset > 0) {
	    ComputeMissingMetric(textPtr, &info, THRESHOLD_LINE_OFFSET, displayLineOffset);
	    info.numDispLines -= info.displayLineNo;

	    while (1) {
		const TkTextDispLineEntry *last;

		if ((int) info.numDispLines >= displayLineOffset) {
		    last = info.entry + displayLineOffset;
		    byteOffset = last->byteOffset;
		    break;
		}
		last = info.entry + info.numDispLines;
		byteOffset = last->byteOffset;
		displayLineOffset -= info.numDispLines;
		TkrTextIndexForwBytes(textPtr, indexPtr, byteOffset, indexPtr);
		linePtr = TkTextIndexGetLine(indexPtr);
		if (linePtr == lastLinePtr) {
		    break;
		}
		FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
		ComputeDisplayLineInfo(textPtr, indexPtr, &info);
		ComputeMissingMetric(textPtr, &info, THRESHOLD_LINE_OFFSET, displayLineOffset);
	    }
	} else if (displayLineOffset < 0) {
	    info.numDispLines = info.displayLineNo + 1;

	    while (1) {
		TkTextLine *prevLine;

		if (-displayLineOffset < (int) info.numDispLines) {
		    int skipBack;

		    byteOffset = (info.entry + displayLineOffset)->byteOffset;
		    skipBack = displayLineOffset;

		    /*
		     * We want to cache this display line, because it's likely that this
		     * line will be used afterwards. Take into account that probably the
		     * last cached line has been removed.
		     */

		    if ((skipBack -= removedLines) >= 0 && (int) info.numCachedLines > skipBack) {
			DLine *dlPtr = info.lastDLinePtr;
			while (dlPtr && skipBack--) {
			    dlPtr = dlPtr->prevPtr;
			}
			if (dlPtr == info.dLinePtr) {
			    info.dLinePtr = dlPtr->nextPtr;
			}
			if (dlPtr == info.lastDLinePtr) {
			    info.lastDLinePtr = dlPtr->prevPtr;
			}
			FreeDLines(textPtr, dlPtr, NULL, DLINE_CACHE);
		    }
		    break;
		}
		displayLineOffset += info.numDispLines;
		if (!(prevLine = TkBTreePrevLine(textPtr, linePtr))) {
		    byteOffset = 0;
		    break;
		}
		TkTextIndexSetToLastChar2(indexPtr, linePtr = prevLine);
		FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
		linePtr = ComputeDisplayLineInfo(textPtr, indexPtr, &info);
		removedLines = 0;
	    }
	} else {
	    byteOffset = info.entry[0].byteOffset;
	}

	/*
	 * We want to cache last produced display line, because it's likely that this
	 * line will be used afterwards.
	 */

	if (info.lastDLinePtr) {
	    FreeDLines(textPtr, info.lastDLinePtr, NULL, DLINE_CACHE);
	    if (info.dLinePtr == info.lastDLinePtr) { info.dLinePtr = NULL; }
	}

	FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
    }

    /* set to first byte, not to start of line */
    DEBUG(indexPtr->discardConsistencyCheck = 1);
    TkTextIndexSetByteIndex2(indexPtr, linePtr, 0);
    DEBUG(indexPtr->discardConsistencyCheck = 0);
    TkrTextIndexForwBytes(textPtr, indexPtr, byteOffset, indexPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextCountDisplayLines -
 *
 *	This function is counting the number of visible display lines
 *	between given indices. This function will be used for computing
 *	"count -displaylines".
 *
 * Results:
 *	The number of visible display lines inside given range.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

unsigned
TkTextCountDisplayLines(
    TkText *textPtr,			/* Widget record for text widget. */
    const TkTextIndex *indexFrom,	/* Start counting at this index. */
    const TkTextIndex *indexTo)		/* Stop counting before this index. */
{
    const TkTextPixelInfo *pixelInfo1;
    const TkTextPixelInfo *pixelInfo2;
    TkTextDispLineInfo *dispLineInfo;
    TkTextDispLineEntry *entry;
    TkTextDispLineEntry *lastEntry;
    TkTextLine *linePtr1;
    TkTextLine *linePtr2;
    TkTextIndex index;
    unsigned byteOffset;
    int numLines;

    assert(TkTextIndexCompare(indexFrom, indexTo) <= 0);
    assert(textPtr->sharedTextPtr->allowUpdateLineMetrics);
    assert(TkTextIndexGetLine(indexFrom));
    assert(TkTextIndexGetLine(indexTo));

    TkTextUpdateLineMetrics(textPtr, TkTextIndexGetLineNumber(indexFrom, textPtr),
	    TkTextIndexGetLineNumber(indexTo, textPtr));

    linePtr1 = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, TkTextIndexGetLine(indexFrom));
    linePtr2 = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, TkTextIndexGetLine(indexTo));
    pixelInfo1 = linePtr1->pixelInfo;
    pixelInfo2 = linePtr2->pixelInfo;

    if (!pixelInfo1->dispLineInfo) {
	numLines = 0;
    } else {
	index = *indexFrom;
	TkTextIndexSetToStartOfLine2(&index, linePtr1);
	byteOffset = TkTextIndexCountBytes(&index, indexFrom);
	dispLineInfo = pixelInfo1->dispLineInfo;
	lastEntry = dispLineInfo->entry + dispLineInfo->numDispLines;
	entry = SearchDispLineEntry(dispLineInfo->entry, lastEntry, byteOffset);
	numLines = -(entry - dispLineInfo->entry);
    }

    while (1) {
	if (pixelInfo1->dispLineInfo) {
	    if (pixelInfo1 == pixelInfo2) {
		index = *indexTo;
		TkTextIndexSetToStartOfLine2(&index, linePtr2);
		byteOffset = TkTextIndexCountBytes(&index, indexTo);
		dispLineInfo = pixelInfo2->dispLineInfo;
		lastEntry = dispLineInfo->entry + dispLineInfo->numDispLines;
		entry = SearchDispLineEntry(dispLineInfo->entry, lastEntry, byteOffset);
		return numLines + (entry - dispLineInfo->entry);
	    }
	    numLines += pixelInfo1->dispLineInfo->numDispLines;
	} else if (pixelInfo1 == pixelInfo2) {
	    return numLines;
	} else {
	    numLines += 1;
	}
	linePtr1 = TkBTreeNextLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr1);
	pixelInfo1 = linePtr1->pixelInfo;
    }

    return 0; /* never reached */
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextFindDisplayLineStartEnd --
 *
 *	This function is invoked to find the index of the beginning or end of
 *	the particular display line on which the given index sits, whether
 *	that line is displayed or not.
 *
 *	If 'end' is 'false', we look for the start, and if 'end' is 'true'
 *	we look for the end.
 *
 *	If the beginning of the current display line is elided, and we are
 *	looking for the start of the line, then the returned index will be the
 *	first elided index on the display line.
 *
 *	Similarly if the end of the current display line is elided and we are
 *	looking for the end, then the returned index will be the last elided
 *	index on the display line.
 *
 * Results:
 *	Modifies indexPtr to point to the given end.
 *
 * Side effects:
 *	See 'LayoutDLine' and 'FreeDLines'.
 *
 *----------------------------------------------------------------------
 */

static void
FindDisplayLineStartEnd(
    TkText *textPtr,		/* Widget record for text widget. */
    TkTextIndex *indexPtr,	/* Index we will adjust to the display line start or end. */
    int end,			/* 'false' = start, 'true' = end. */
    int cacheType)		/* Argument for FreeDLines, either DLINE_CACHE or DLINE_METRIC. */
{
    DisplayInfo info;
    int byteCount;

    if (TkTextIndexGetLine(indexPtr) == TkBTreeGetLastLine(textPtr)
	    || (!end && IsStartOfNotMergedLine(indexPtr))) {
	/*
	 * Nothing to do, because we are at start/end of a display line.
	 */

	return;
    }

    ComputeDisplayLineInfo(textPtr, indexPtr, &info);
    byteCount = end ? -(info.nextByteOffset - 1) : info.byteOffset;
    TkrTextIndexBackBytes(textPtr, indexPtr, byteCount, indexPtr);

    if (end) {
	Tcl_Size offset;
	int skipBack = 0;
	TkTextSegment *segPtr = TkTextIndexGetContentSegment(indexPtr, &offset);
	char const *p = segPtr->body.chars + offset;

	/*
	 * We don't want an offset inside a multi-byte sequence, so find the start
	 * of the current character.
	 */

	while (p > segPtr->body.chars && (*p & 0xc0) == 0x80) {
	    p -= 1;
	    skipBack += 1;
	}
	TkrTextIndexBackBytes(textPtr, indexPtr, skipBack, indexPtr);
    }

    /*
     * We want to cache last produced display line, because it's likely that this
     * line will be used afterwards.
     */

    if (info.lastDLinePtr) {
	FreeDLines(textPtr, info.lastDLinePtr, NULL, (FreeDLineAction)cacheType);
	if (info.dLinePtr == info.lastDLinePtr) {
	    info.dLinePtr = NULL; /* don't release it twice */
	}
    }

    FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
}

void
TkTextFindDisplayLineStartEnd(
    TkText *textPtr,		/* Widget record for text widget. */
    TkTextIndex *indexPtr,	/* Index we will adjust to the display line start or end. */
    int end)			/* 'false' = start, 'true' = end. */
{
    FindDisplayLineStartEnd(textPtr, indexPtr, end, DLINE_CACHE);
}

/*
 *----------------------------------------------------------------------
 *
 * CalculateDisplayLineHeight --
 *
 *	This function is invoked to recalculate the height of the particular
 *	display line which starts with the given index, whether that line is
 *	displayed or not.
 *
 *	This function does not, in itself, update any cached information about
 *	line heights. That should be done, where necessary, by its callers.
 *
 *	The behaviour of this function is _undefined_ if indexPtr is not
 *	currently at the beginning of a display line.
 *
 * Results:
 *	The number of vertical pixels used by the display line.
 *
 *	If 'byteCountRef' is non-NULL, then returns in that pointer the number
 *	of byte indices on the given display line (which can be used to update
 *	indexPtr in a loop).
 *
 * Side effects:
 *	The same as LayoutDLine and FreeDLines.
 *
 *----------------------------------------------------------------------
 */

#ifndef NDEBUG
static int
IsAtStartOfDisplayLine(
    const TkTextIndex *indexPtr)
{
    TkTextIndex index2 = *indexPtr;

    assert(indexPtr->textPtr);

    FindDisplayLineStartEnd(indexPtr->textPtr, &index2, DISP_LINE_START, DLINE_METRIC);
    return TkTextIndexCompare(&index2, indexPtr) == 0;
}
#endif /* NDEBUG */

static int
CalculateDisplayLineHeight(
    TkText *textPtr,		/* Widget record for text widget. */
    const TkTextIndex *indexPtr,/* The index at the beginning of the display line of interest. */
    unsigned *byteCountRef)	/* NULL or used to return the number of byte indices on the given
				 * display line. */
{
    DisplayInfo info;

    assert(!TkTextIndexIsEndOfText(indexPtr));
    assert(IsAtStartOfDisplayLine(indexPtr));

    /*
     * Special case for artificial last line.
     */

    if (TkTextIndexGetLine(indexPtr) == TkBTreeGetLastLine(textPtr)) {
	if (byteCountRef) { *byteCountRef = 0; }
	return 0;
    }

    ComputeDisplayLineInfo(textPtr, indexPtr, &info);

    /*
     * Last computed line has to be cached temporarily.
     */

    if (info.lastDLinePtr) {
	FreeDLines(textPtr, info.lastDLinePtr, NULL, DLINE_METRIC);
	if (info.dLinePtr == info.lastDLinePtr) {
	    info.dLinePtr = NULL; /* don't release it twice */
	}
    }

    FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
    if (byteCountRef) { *byteCountRef = info.nextByteOffset + info.byteOffset; }
    assert(info.entry->height != 0xffffffff);
    return info.entry->height;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetViewOffset --
 *
 *	This function returns the x and y offset of the current view.
 *
 * Results:
 *	The pixel offset of the current view.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextGetViewOffset(
    TkText *textPtr,		/* Widget record for text widget. */
    int *x,			/* X offset */
    int *y)			/* Y offset */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    if (dInfoPtr && dInfoPtr->dLinePtr) {
	*x = dInfoPtr->curXPixelOffset;
	*y = dInfoPtr->curYPixelOffset;
    } else {
	*x = 0;
	*y = 0;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetXPixelFromChunk --
 *
 *	Return the left most x pixel index from given chunk.
 *
 * Results:
 *	Returns the left most x pixel index from given chunk.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextGetXPixelFromChunk(
    const TkText *textPtr,
    const TkTextDispChunk *chunkPtr)
{
    const TextDInfo *dInfoPtr;

    assert(textPtr);
    assert(chunkPtr);

    dInfoPtr = textPtr->dInfoPtr;
    return chunkPtr->x + dInfoPtr->x + dInfoPtr->curXPixelOffset;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetYPixelFromChunk --
 *
 *	Return the top most y pixel index from given chunk.
 *
 * Results:
 *	Returns the top most y pixel index from given chunk.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextGetYPixelFromChunk(
    const TkText *textPtr,
    const TkTextDispChunk *chunkPtr)
{
    const DLine *dlPtr;

    assert(textPtr);
    assert(chunkPtr);

    dlPtr = chunkPtr->dlPtr;
    /* Note that dInfoPtr->y is already included in dlPtr->y. */
    return dlPtr->y + textPtr->dInfoPtr->curYPixelOffset;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetTagSetFromChunk --
 *
 *	This function returns the tag information from given chunk.
 *	It must be ensured that this chunk contains any content
 *	(character, hyphen, image, window).
 *
 * Results:
 *	The tag information of this chunk.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

TkTextTagSet *
TkTextGetTagSetFromChunk(
    const TkTextDispChunk *chunkPtr)
{
    assert(chunkPtr);

    switch (chunkPtr->layoutProcs->type) {
    case TEXT_DISP_CHAR:   /* fallthru */
    case TEXT_DISP_HYPHEN: return CHAR_CHUNK_GET_SEGMENT(chunkPtr)->tagInfoPtr;
    case TEXT_DISP_IMAGE:  /* fallthru */
    case TEXT_DISP_WINDOW: return ((TkTextSegment *) chunkPtr->clientData)->tagInfoPtr;
    case TEXT_DISP_ELIDED: /* fallthru */
    case TEXT_DISP_CURSOR: return NULL;
    }

    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * GetPixelsTo --
 *
 *	This function computes the pixels between the first display line
 *	of the logical line (belonging to given position), and the display
 *	line at the specified position.
 *
 *	If the line metric computation of the specified logical line is
 *	not yet finished, and 'info' is not NULL, then ComputeMissingMetric
 *	will be used to compute the missing metric compuation.
 *
 * Results:
 *	The pixels from first display line (belonging to given position) to
 *	specified display line.
 *
 * Side effects:
 *	Just the ones of ComputeMissingMetric.
 *
 *----------------------------------------------------------------------
 */

static unsigned
GetPixelsTo(
    TkText *textPtr,
    const TkTextIndex *indexPtr,
    int inclusiveLastLine,
    DisplayInfo *info)		/* can be NULL */
{
    TkTextLine *logicalLinePtr;
    const TkTextPixelInfo *pixelInfo;
    TkTextDispLineInfo *dispLineInfo;
    const TkTextDispLineEntry *lastEntry;
    const TkTextDispLineEntry *entry;
    TkTextIndex index;
    unsigned byteOffset;

    assert(TkTextIndexGetLine(indexPtr));

    logicalLinePtr = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr,
	    TkTextIndexGetLine(indexPtr));
    if (logicalLinePtr == TkBTreeGetLastLine(textPtr)) {
	return 0;
    }
    pixelInfo = TkBTreeLinePixelInfo(textPtr, logicalLinePtr);

    if (!info && (pixelInfo->epoch & EPOCH_MASK) != textPtr->dInfoPtr->lineMetricUpdateEpoch) {
	return 0;
    }

    if (!(dispLineInfo = pixelInfo->dispLineInfo)) {
	return inclusiveLastLine ? pixelInfo->height : 0;
    }

    index = *indexPtr;
    TkTextIndexSetToStartOfLine2(&index, logicalLinePtr);
    byteOffset = TkTextIndexCountBytes(&index, indexPtr);
    lastEntry = dispLineInfo->entry + dispLineInfo->numDispLines;
    entry = SearchDispLineEntry(dispLineInfo->entry, lastEntry, byteOffset);

    if (entry == lastEntry) {
	/*
	 * This happens if the line metric calculation for this logical line is not yet complete.
	 */

	if (info) {
	    unsigned numDispLinesSoFar = dispLineInfo->numDispLines;

	    ComputeMissingMetric(textPtr, info, THRESHOLD_BYTE_OFFSET, byteOffset);
	    lastEntry = dispLineInfo->entry + dispLineInfo->numDispLines;
	    entry = SearchDispLineEntry(dispLineInfo->entry + numDispLinesSoFar, lastEntry, byteOffset);
	    if (entry == lastEntry) {
		entry -= 1;
	    }
	} else {
	    assert(dispLineInfo->numDispLines > 0);
	    entry -= 1;
	}
    } else if (!inclusiveLastLine && entry-- == dispLineInfo->entry) {
	return 0;
    }

    return entry->pixels;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexYPixels --
 *
 *	This function is invoked to calculate the number of vertical pixels
 *	between the first index of the text widget and the given index. The
 *	range from first logical line to given logical line is determined
 *	using the cached values, and the range inside the given logical line
 *	is calculated on the fly.
 *
 * Results:
 *	The pixel distance between first pixel in the widget and the
 *	top of the index's current display line (could be zero).
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextIndexYPixels(
    TkText *textPtr,		/* Widget record for text widget. */
    const TkTextIndex *indexPtr)/* The index of which we want the pixel distance from top of
				 * text widget to top of index. */
{
    /* Note that TkBTreePixelsTo is computing up to start of the logical line. */
    return TkBTreePixelsTo(textPtr, TkTextIndexGetLine(indexPtr)) +
	    GetPixelsTo(textPtr, indexPtr, 0, NULL);
}

/*
 *----------------------------------------------------------------------
 *
 * UpdateOneLine --
 *
 *	This function is invoked to recalculate the height of a particular
 *	logical line, whether that line is displayed or not.
 *
 *	It must NEVER be called for the artificial last TkTextLine which is
 *	used internally for administrative purposes only. That line must
 *	retain its initial height of 0 otherwise the pixel height calculation
 *	maintained by the B-tree will be wrong.
 *
 * Results:
 *	The number of display lines in the logical line. This could be zero if
 *	the line is totally elided.
 *
 * Side effects:
 *	Line heights may be recalculated, and a timer to update the scrollbar
 *	may be installed. Also see the called function CalculateDisplayLineHeight
 *	for its side effects.
 *
 *----------------------------------------------------------------------
 */

static int
UpdateOneLine(
    TkText *textPtr,		/* Widget record for text widget. */
    TkTextLine *linePtr,	/* The line of which to calculate the height. */
    TkTextIndex *indexPtr,	/* Either NULL or an index at the start of a display line belonging
				 * to linePtr, at which we wish to start (e.g. up to which we have
				 * already calculated). On return this will be set to the first index
				 * on the next line. */
    unsigned maxDispLines)	/* Don't compute more than this number of display lines. */
{
    TkTextIndex index;
    TkTextLine *logicalLinePtr;
    TkTextPixelInfo *pixelInfo;
    unsigned displayLines;
    unsigned updateCounter;
    unsigned pixelHeight;

    assert(linePtr != TkBTreeGetLastLine(textPtr));
    assert(TkTextIndexGetLine(indexPtr));

    if (!indexPtr) {
	TkTextIndexClear(&index, textPtr);
	TkTextIndexSetToStartOfLine2(&index, linePtr);
	indexPtr = &index;
    }

    linePtr = TkTextIndexGetLine(indexPtr);
    logicalLinePtr = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
    pixelInfo = TkBTreeLinePixelInfo(textPtr, logicalLinePtr);

    if (pixelInfo->epoch == (textPtr->dInfoPtr->lineMetricUpdateEpoch | PARTIAL_COMPUTED_BIT)) {
	const TkTextDispLineInfo *dispLineInfo = pixelInfo->dispLineInfo;
	unsigned bytes;

	/*
	 * We are inside a partial computation. Continue with next display line.
	 */

	assert(dispLineInfo);
	assert(dispLineInfo->numDispLines > 0);
	bytes = dispLineInfo->entry[dispLineInfo->numDispLines].byteOffset;
	bytes -= dispLineInfo->entry[0].byteOffset;
	TkTextIndexSetToStartOfLine2(indexPtr, logicalLinePtr);
	TkrTextIndexForwBytes(textPtr, indexPtr, bytes, indexPtr);
	linePtr = TkTextIndexGetLine(indexPtr);
	assert(!linePtr->logicalLine || !TkTextIndexIsStartOfLine(indexPtr));
    } else if (!linePtr->logicalLine || !TkTextIndexIsStartOfLine(indexPtr)) {
	/*
	 * CalculateDisplayLineHeight must be called with an index at the beginning
	 * of a display line. Force this to happen. This is needed when
	 * UpdateOneLine is called with a line that is merged with its
	 * previous line: the number of merged logical lines in a display line is
	 * calculated correctly only when CalculateDisplayLineHeight receives
	 * an index at the beginning of a display line. In turn this causes the
	 * merged lines to receive their correct zero pixel height in
	 * TkBTreeAdjustPixelHeight.
	 */

	FindDisplayLineStartEnd(textPtr, indexPtr, DISP_LINE_START, DLINE_METRIC);
	linePtr = TkTextIndexGetLine(indexPtr);
    }

    assert(linePtr->nextPtr);
    updateCounter = textPtr->dInfoPtr->lineMetricUpdateCounter;
    pixelHeight = 0;
    displayLines = 0;

    /*
     * Iterate through all display-lines corresponding to the single logical
     * line 'linePtr' (and lines merged into this line due to eol elision),
     * adding up the pixel height of each such display line as we go along.
     * The final total is, therefore, the total height of all display lines
     * made up by the logical line 'linePtr' and subsequent logical lines
     * merged into this line.
     */

    while (1) {
	unsigned bytes, height;
	int atEnd;

	/*
	 * Currently this call doesn't have many side-effects. However, if in
	 * the future we change the code so there are side-effects (such as
	 * adjusting linePtr->pixelHeight), then the code might not quite work
	 * as intended.
	 */

	height = CalculateDisplayLineHeight(textPtr, indexPtr, &bytes);
	atEnd = TkrTextIndexForwBytes(textPtr, indexPtr, bytes, indexPtr) == 1
		|| TkTextIndexIsEndOfText(indexPtr);

	assert(bytes > 0);

	if (height > 0) {
	    pixelHeight += height;
	    displayLines += 1;
	}

	if (atEnd) {
	    break; /* we are at the end */
	}

	if (linePtr != TkTextIndexGetLine(indexPtr)) {
	    if (TkTextIndexGetLine(indexPtr)->logicalLine) {
		break; /* we've reached the end of the logical line */
	    }
	    linePtr = TkTextIndexGetLine(indexPtr);
	} else {
	    /*
	     * We must still be on the same wrapped line, on a new logical
	     * line merged with the logical line 'linePtr'.
	     */
	}

	if (displayLines == maxDispLines) {
	    /*
	     * We are calculating a limited number of display lines at a time, to avoid huge delays.
	     */

	    /* check that LayoutUpdateLineHeightInformation has set this bit */
	    assert(pixelInfo->epoch & PARTIAL_COMPUTED_BIT);
	    break;
	}
    }

    if (updateCounter != textPtr->dInfoPtr->lineMetricUpdateCounter) {
	/*
	 * Otherwise nothing relevant has changed.
	 */

	if (tkTextDebug) {
	    char buffer[2*TCL_INTEGER_SPACE + 1];

	    if (!TkBTreeNextLine(textPtr, linePtr)) {
		Tcl_Panic("Must never ever update line height of last artificial line");
	    }

	    pixelHeight = TkBTreeNumPixels(textPtr);
	    snprintf(buffer, sizeof(buffer), "%u %u",
		    TkBTreeLinesTo(indexPtr->tree, textPtr, linePtr, NULL), pixelHeight);
	    LOG("tk_textNumPixels", buffer);
	}

	if (!textPtr->dInfoPtr->scrollbarTimer) {
	    InvokeAsyncUpdateYScrollbar(textPtr);
	}
    }

    return displayLines;
}

/*
 *----------------------------------------------------------------------
 *
 * DisplayText --
 *
 *	This function is invoked as a when-idle handler to update the display.
 *	It only redisplays the parts of the text widget that are out of date.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Information is redrawn on the screen.
 *
 *----------------------------------------------------------------------
 */

static void
DisplayText(
    void *clientData)	/* Information about widget. */
{
    TkText *textPtr = (TkText *)clientData;
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    DLine *dlPtr;
    Pixmap pixmap;
    int maxHeight, borders;
    int bottomY = 0;		/* Initialization needed only to stop compiler warnings. */
    int extent1, extent2;
    Tcl_Interp *interp;
    DRegion* invalidRegion = &dInfoPtr->invalidRegion;

    if (textPtr->flags & DESTROYED) {
	return; /* the widget has been deleted */
    }

    interp = textPtr->interp;
    Tcl_Preserve(interp);

    TK_TEXT_DEBUG(CLEAR("tk_textRelayout"));

    if (!Tk_IsMapped(textPtr->tkwin) || dInfoPtr->maxX <= dInfoPtr->x || dInfoPtr->maxY <= dInfoPtr->y) {
	UpdateDisplayInfo(textPtr);
	dInfoPtr->flags &= ~REDRAW_PENDING;
	ClearRegion(invalidRegion);
	goto doScrollbars;
    }
    DEBUG(stats.numRedisplays += 1);
    TK_TEXT_DEBUG(CLEAR("tk_textRedraw"));

    /*
     * Choose a new current item if that is needed (this could cause event
     * handlers to be invoked, hence the refcount management and the loop,
     * since the handlers could conceivably necessitate yet another current
     * item calculation). The textPtr check is because the whole window could go
     * away in the meanwhile.
     */

    if (dInfoPtr->flags & REPICK_NEEDED) {
	/*
	 * TODD XXX
	 * Either this is the wrong place, or a repick should also happen after
	 * the text has been redisplayed, because the repick function is working
	 * on the displayed chunks.
	 */
	textPtr->refCount += 1;
	dInfoPtr->flags &= ~REPICK_NEEDED;
	dInfoPtr->currChunkPtr = NULL;
	TkTextPickCurrent(textPtr, &textPtr->pickEvent);
	if (TkTextDecrRefCountAndTestIfDestroyed(textPtr)) {
	    goto end;
	}
    }

    /*
     * First recompute what's supposed to be displayed.
     */

    UpdateDisplayInfo(textPtr);
    dInfoPtr->dLinesInvalidated = 0;

    /*
     * TkScrollWindow must consider the insertion cursor.
     */

    ComputeCursorExtents(textPtr, &extent1, &extent2);

    /*
     * See if it's possible to bring some parts of the screen up-to-date by
     * scrolling (copying from other parts of the screen). We have to be
     * particularly careful with the top and bottom lines of the display,
     * since these may only be partially visible and therefore not helpful for
     * some scrolling purposes.
     */

    for (dlPtr = dInfoPtr->dLinePtr; dlPtr; dlPtr = dlPtr->nextPtr) {
	DLine *dlPtr2;
	int offset, height, y, oldY;
	TkRegion damageRgn;

	/*
	 * These tests are, in order:
	 *
	 * 1. If the line is already marked as invalid
	 * 2. If the line hasn't moved
	 * 3. If the line overlaps the bottom of the window and we are scrolling up.
	 * 4. If the line overlaps the top of the window and we are scrolling down.
	 * 5. If the line overlaps any invalidated region.
	 *
	 * If any of these tests are true, then we can't scroll this line's
	 * part of the display.
	 *
	 * Note that even if tests 3 or 4 aren't true, we may be able to
	 * scroll the line, but we still need to be sure to call embedded
	 * window display procs on top and bottom lines if they have any
	 * portion non-visible (see below).
	 */

	if ((dlPtr->flags & OLD_Y_INVALID)
		|| dlPtr->y == dlPtr->oldY
		|| ((dlPtr->oldY + dlPtr->height) > dInfoPtr->maxY && dlPtr->y < dlPtr->oldY)
		|| (dlPtr->oldY < dInfoPtr->y && dlPtr->y > dlPtr->oldY)
		|| RegionIntersects(invalidRegion, dlPtr->oldY, dlPtr->oldY + dlPtr->height)) {
	    continue;
	}

	/*
	 * This line is already drawn somewhere in the window so it only needs
	 * to be copied to its new location. See if there's a group of lines
	 * that can all be copied together.
	 */

	offset = dlPtr->y - dlPtr->oldY;
	height = dlPtr->height;
	y = dlPtr->y;
	for (dlPtr2 = dlPtr->nextPtr; dlPtr2; dlPtr2 = dlPtr2->nextPtr) {
	    if ((dlPtr2->flags & OLD_Y_INVALID)
		    || dlPtr2->oldY + offset != dlPtr2->y
		    || dlPtr2->oldY + dlPtr2->height > dInfoPtr->maxY
		    || RegionIntersects(invalidRegion, dlPtr2->oldY, dlPtr2->oldY + dlPtr2->height)){
		break;
	    }
	    height += dlPtr2->height;
	}

	/*
	 * Reduce the height of the area being copied if necessary to avoid
	 * overwriting the border area.
	 */

	if (y + height > dInfoPtr->maxY) {
	    height = dInfoPtr->maxY - y;
	}
	oldY = dlPtr->oldY;
	if (y < dInfoPtr->y) {
	    /*
	     * Adjust if the area being copied is going to overwrite the top
	     * border of the window (so the top line is only half onscreen).
	     */

	    int y_off = dInfoPtr->y - dlPtr->y;
	    height -= y_off;
	    oldY += y_off;
	    y = dInfoPtr->y;
	}

#if 0 /* TODO: this can happen in certain situations, but shouldn't happen */
	assert(height > 0); /* otherwise dInfoPtr->topPixelOffset is wrong */
#else
	if (height <= 0) {
	    fprintf(stderr, "DisplayText: height <= 0 is unexpected\n");
	}
#endif

	/*
	 * Update the lines we are going to scroll to show that they have been copied.
	 */

	while (1) {
	    /*
	     * The DLine already has OLD_Y_INVALID cleared.
	     */

	    dlPtr->oldY = dlPtr->y;
	    if (dlPtr->nextPtr == dlPtr2) {
		break;
	    }
	    dlPtr = dlPtr->nextPtr;
	}

	/*
	 * Scan through the lines following the copied ones to see if we are
	 * going to overwrite them with the copy operation. If so, mark them
	 * for redisplay.
	 */

	for ( ; dlPtr2; dlPtr2 = dlPtr2->nextPtr) {
	    if (!(dlPtr2->flags & OLD_Y_INVALID)
		    && dlPtr2->oldY + dlPtr2->height > y
		    && dlPtr2->oldY < y + height) {
		dlPtr2->flags |= OLD_Y_INVALID;
	    }
	}

	/*
	 * Now scroll the lines. This may generate damage which we handle by
	 * calling TextInvalidateRegion to mark the display blocks as stale.
	 */

	damageRgn = TkCreateRegion();
	if (TkScrollWindow(textPtr->tkwin, dInfoPtr->scrollGC, MAX(0, dInfoPtr->x - extent1), oldY,
		dInfoPtr->maxX - dInfoPtr->x + extent1 + extent2, height, 0, y - oldY, damageRgn)) {
	    TextInvalidateRegion(textPtr, damageRgn);
	}
	DEBUG(stats.numCopies += 1);
	TkDestroyRegion(damageRgn);
    }

    /*
     * Clear the REDRAW_PENDING flag here. This is actually pretty tricky. We want to
     * wait until *after* doing the scrolling, since that could generate more areas to
     * redraw and don't want to reschedule a redisplay for them. On the other hand, we
     * can't wait until after all the redisplaying, because the act of redisplaying
     * could actually generate more redisplays (e.g. in the case of a nested window
     * with event bindings triggered by redisplay).
     */

    dInfoPtr->flags &= ~REDRAW_PENDING;

    /*
     * Also clear the region of invalidated lines, no longer needed, scrolling has
     * been done.
     */

    ClearRegion(invalidRegion);

    /*
     * Redraw the borders if that's needed.
     */

    if (dInfoPtr->flags & REDRAW_BORDERS) {
	TK_TEXT_DEBUG(LOG("tk_textRedraw", "borders"));

	if (!textPtr->tkwin) {
	    /*
	     * The widget has been deleted. Don't do anything.
	     */

	    goto end;
	}

	Tk_Draw3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin),
		textPtr->border, textPtr->highlightWidth,
		textPtr->highlightWidth,
		Tk_Width(textPtr->tkwin) - 2*textPtr->highlightWidth,
		Tk_Height(textPtr->tkwin) - 2*textPtr->highlightWidth,
		textPtr->borderWidth, textPtr->relief);
	if (textPtr->highlightWidth > 0) {
	    GC fgGC, bgGC;

	    bgGC = Tk_GCForColor(textPtr->highlightBgColorPtr, Tk_WindowId(textPtr->tkwin));
	    if (textPtr->flags & GOT_FOCUS) {
		fgGC = Tk_GCForColor(textPtr->highlightColorPtr, Tk_WindowId(textPtr->tkwin));
		Tk_DrawHighlightBorder(textPtr->tkwin, fgGC, bgGC,
			textPtr->highlightWidth, Tk_WindowId(textPtr->tkwin));
	    } else {
		Tk_DrawHighlightBorder(textPtr->tkwin, bgGC, bgGC,
			textPtr->highlightWidth, Tk_WindowId(textPtr->tkwin));
	    }
	}
	borders = textPtr->borderWidth + textPtr->highlightWidth;
	if (textPtr->padY > 0) {
	    Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin),
		    textPtr->border, borders, borders,
		    Tk_Width(textPtr->tkwin) - 2*borders, textPtr->padY,
		    0, TK_RELIEF_FLAT);
	    Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin),
		    textPtr->border, borders,
		    Tk_Height(textPtr->tkwin) - borders - textPtr->padY,
		    Tk_Width(textPtr->tkwin) - 2*borders,
		    textPtr->padY, 0, TK_RELIEF_FLAT);
	}
	if (textPtr->padX > 0) {
	    Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin),
		    textPtr->border, borders, borders + textPtr->padY,
		    textPtr->padX,
		    Tk_Height(textPtr->tkwin) - 2*borders -2*textPtr->padY,
		    0, TK_RELIEF_FLAT);
	    Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin),
		    textPtr->border,
		    Tk_Width(textPtr->tkwin) - borders - textPtr->padX,
		    borders + textPtr->padY, textPtr->padX,
		    Tk_Height(textPtr->tkwin) - 2*borders -2*textPtr->padY,
		    0, TK_RELIEF_FLAT);
	}
	dInfoPtr->flags &= ~REDRAW_BORDERS;
    }

    /*
     * Now we have to redraw the lines that couldn't be updated by scrolling.
     * First, compute the height of the largest line and allocate an off-
     * screen pixmap to use for double-buffered displays.
     */

    maxHeight = -1;
    for (dlPtr = dInfoPtr->dLinePtr; dlPtr; dlPtr = dlPtr->nextPtr) {
	if (dlPtr->height > maxHeight && ((dlPtr->flags & OLD_Y_INVALID) || dlPtr->oldY != dlPtr->y)) {
	    maxHeight = dlPtr->height;
	}
	bottomY = dlPtr->y + dlPtr->height;
    }

    /*
     * There used to be a line here which restricted 'maxHeight' to be no
     * larger than 'dInfoPtr->maxY', but this is incorrect for the case where
     * individual lines may be taller than the widget _and_ we have smooth
     * scrolling. What we can do is restrict maxHeight to be no larger than
     * 'dInfoPtr->maxY + dInfoPtr->topPixelOffset'.
     */

    if (maxHeight > dInfoPtr->maxY + dInfoPtr->topPixelOffset) {
	maxHeight = (dInfoPtr->maxY + dInfoPtr->topPixelOffset);
    }

    if (maxHeight > 0) {
#ifndef TK_NO_DOUBLE_BUFFERING
	pixmap = Tk_GetPixmap(Tk_Display(textPtr->tkwin),
		Tk_WindowId(textPtr->tkwin), Tk_Width(textPtr->tkwin),
		maxHeight, Tk_Depth(textPtr->tkwin));
#else
	pixmap = Tk_WindowId(textPtr->tkwin);
#endif /* TK_NO_DOUBLE_BUFFERING */

	for (dlPtr = dInfoPtr->dLinePtr; dlPtr && dlPtr->y < dInfoPtr->maxY; dlPtr = dlPtr->nextPtr) {
	    if (!dlPtr->chunkPtr) {
		continue;
	    }
	    if ((dlPtr->flags & OLD_Y_INVALID) || dlPtr->oldY != dlPtr->y) {
		if (tkTextDebug) {
		    char string[TK_POS_CHARS];

		    TkrTextPrintIndex(textPtr, &dlPtr->index, string);
		    LOG("tk_textRedraw", string);
		}
		DisplayDLine(textPtr, dlPtr, dlPtr->prevPtr, pixmap);
		if ((textPtr->tkwin == NULL) || (textPtr->flags & DESTROYED)) {
		    /*
		     * DisplayDLine called a displayProc which invoked a binding
		     * that caused the widget to be deleted. Don't do anything.
		     */
		    goto end;
		}
		if (dInfoPtr->dLinesInvalidated) {
#ifndef TK_NO_DOUBLE_BUFFERING
		    Tk_FreePixmap(Tk_Display(textPtr->tkwin), pixmap);
#endif /* TK_NO_DOUBLE_BUFFERING */
		    goto doScrollbars;
		}
		dlPtr->oldY = dlPtr->y;
		dlPtr->flags &= ~(NEW_LAYOUT | OLD_Y_INVALID);
#ifdef MAC_OSX_TK
	    } else if (dInfoPtr->countWindows > 0 && dlPtr->chunkPtr) {
		/*
		 * On macOS we need to redisplay all embedded windows which
		 * were moved by the call to TkScrollWindows above.  This is
		 * not necessary on Unix or Windows because XScrollWindow will
		 * have included the bounding rectangles of all of these
		 * windows in the damage region.  The macosx implementation of
		 * TkScrollWindow does not do this.  It simply generates a
		 * damage region which is the scroll source rectangle minus
		 * the scroll destination rectangle.  This is because there is
		 * no efficient process available for iterating through the
		 * subwindows which meet the scrolled area.  (On Unix this is
		 * handled by GraphicsExpose events generated by XCopyArea and
		 * on Windows by ScrollWindowEx.  On macOS the low level
		 * scrolling is accomplished by calling [view scrollRect:by:].
		 * This method does not provide any damage information and, in
		 * any case, could not be aware of Tk windows which were not
		 * based on NSView objects.
		 *
		 * On the other hand, this loop is already iterating through
		 * all embedded windows which could possibly have been moved
		 * by the scrolling.  So it is as efficient to redisplay them
		 * here as it would have been if they had been redisplayed by
		 * the call to TextInvalidateRegion above.
		 */
#else
	    } else if (dInfoPtr->countWindows > 0
		    && dlPtr->chunkPtr
		    && (dlPtr->y < 0 || dlPtr->y + dlPtr->height > dInfoPtr->maxY)) {

		/*
		 * On platforms other than the Mac:
		 *
		 * It's the first or last DLine which are also overlapping the
		 * top or bottom of the window, but we decided above it wasn't
		 * necessary to display them (we were able to update them by
		 * scrolling). This is fine, except that if the lines contain
		 * any embedded windows, we must still call the display proc
		 * on them because they might need to be unmapped or they
		 * might need to be moved to reflect their new position.
		 * Otherwise, everything else moves, but the embedded window
		 * doesn't!
		 *
		 * So, we loop through all the chunks, calling the display
		 * proc of embedded windows only.
		 */
#endif
		TkTextDispChunk *chunkPtr;

		for (chunkPtr = dlPtr->chunkPtr; chunkPtr; chunkPtr = chunkPtr->nextPtr) {
		    int x;

		    if (chunkPtr->layoutProcs->type != TEXT_DISP_WINDOW) {
			continue;
		    }
		    x = chunkPtr->x + dInfoPtr->x - dInfoPtr->curXPixelOffset;
		    if (x + chunkPtr->width <= 0 || x >= dInfoPtr->maxX) {
			/*
			 * Note: we have to call the displayProc even for
			 * chunks that are off-screen. This is needed, for
			 * example, so that embedded windows can be unmapped
			 * in this case. Display the chunk at a coordinate
			 * that can be clearly identified by the displayProc
			 * as being off-screen to the left (the displayProc
			 * may not be able to tell if something is off to the
			 * right).
			 */

			x = -chunkPtr->width;
		    }
		    if (tkTextDebug) {
			char string[TK_POS_CHARS];

			TkrTextPrintIndex(textPtr, &dlPtr->index, string);
			LOG("tk_textEmbWinDisplay", string);
		    }
		    chunkPtr->layoutProcs->displayProc(textPtr, chunkPtr, x,
			    dlPtr->spaceAbove,
			    dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow,
			    dlPtr->baseline - dlPtr->spaceAbove, NULL,
			    (Drawable) None, dlPtr->y + dlPtr->spaceAbove);
		}
	    }
	}
#ifndef TK_NO_DOUBLE_BUFFERING
	Tk_FreePixmap(Tk_Display(textPtr->tkwin), pixmap);
#endif /* TK_NO_DOUBLE_BUFFERING */
    }

    /*
     * See if we need to refresh the part of the window below the last line of
     * text (if there is any such area). Refresh the padding area on the left
     * too, since the insertion cursor might have been displayed there
     * previously).
     */

    if (dInfoPtr->topOfEof > dInfoPtr->maxY) {
	dInfoPtr->topOfEof = dInfoPtr->maxY;
    }
    if (bottomY < dInfoPtr->topOfEof) {
	TK_TEXT_DEBUG(LOG("tk_textRedraw", "eof"));

	if (textPtr->flags & DESTROYED) {
	    goto end; /* the widget has been deleted */
	}

	Tk_Fill3DRectangle(textPtr->tkwin, Tk_WindowId(textPtr->tkwin),
		textPtr->border, dInfoPtr->x - textPtr->padX, bottomY,
		dInfoPtr->maxX - (dInfoPtr->x - textPtr->padX),
		dInfoPtr->topOfEof - bottomY, 0, TK_RELIEF_FLAT);
    }
    dInfoPtr->topOfEof = bottomY;

    /*
     * Update the vertical scrollbar, if there is one. Note: it's important to
     * clear REDRAW_PENDING here, just in case the scroll function does
     * something that requires redisplay.
     */

  doScrollbars:
    if (textPtr->flags & UPDATE_SCROLLBARS) {

	/*
	 * Update the vertical scrollbar, if any.
	 */

	textPtr->flags &= ~UPDATE_SCROLLBARS;
	if (textPtr->yScrollCmdObj || textPtr->watchCmd) {
	    GetYView(textPtr->interp, textPtr, 1);
	}

	/*
	 * Update the horizontal scrollbar, if any.
	 */

	if (textPtr->xScrollCmdObj || textPtr->watchCmd) {
	    GetXView(textPtr->interp, textPtr, 1);
	}

	if (!(TriggerWatchCursor(textPtr))) {
	    goto end; /* the widget has been deleted */
	}
    }

    if (dInfoPtr->flags & ASYNC_PENDING) {
	assert(dInfoPtr->flags & ASYNC_UPDATE);
	dInfoPtr->flags &= ~ASYNC_PENDING;
	/* continue with asynchronous pixel-height calculation */
	InvokeAsyncUpdateLineMetrics(textPtr);
    }

  end:
    Tcl_Release(interp);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextEventuallyRepick --
 *
 *	This function is invoked whenever something happens that could change
 *	the current character or the tags associated with it.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	A repick is scheduled as an idle handler.
 *
 *----------------------------------------------------------------------
 */

void
TkTextEventuallyRepick(
    TkText *textPtr)		/* Widget record for text widget. */
{
    textPtr->dInfoPtr->flags |= REPICK_NEEDED;
    DisplayTextWhenIdle(textPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextRedrawRegion --
 *
 *	This function is invoked to schedule a redisplay for a given region of
 *	a text widget. The redisplay itself may not occur immediately: it's
 *	scheduled as a when-idle handler.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Information will eventually be redrawn on the screen.
 *
 *----------------------------------------------------------------------
 */

void
TkTextRedrawRegion(
    TkText *textPtr,		/* Widget record for text widget. */
    int x, int y,		/* Coordinates of upper-left corner of area to be redrawn, in
				 * pixels relative to textPtr's window. */
    int width, int height)	/* Width and height of area to be redrawn. */
{
    TkRegion damageRgn = TkCreateRegion();
    XRectangle rect;

    rect.x = x;
    rect.y = y;
    rect.width = width;
    rect.height = height;
    TkUnionRectWithRegion(&rect, damageRgn, damageRgn);
    TextInvalidateRegion(textPtr, damageRgn);
    TkDestroyRegion(damageRgn);

    DisplayTextWhenIdle(textPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TextInvalidateRegion --
 *
 *	Mark a region of text as invalid.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Updates the display information for the text widget.
 *
 *----------------------------------------------------------------------
 */

static void
TextInvalidateRegion(
    TkText *textPtr,		/* Widget record for text widget. */
    TkRegion region)		/* Region of area to redraw. */
{
    DLine *dlPtr;
    TextDInfo *dInfoPtr;
    int inset, extent1, extent2, maxY;
    XRectangle clipRect;
    DRect textRect;	/* includes cursor extents */

    TkClipBox(region, &clipRect);
    if (RectIsEmpty(&clipRect)) {
	return;
    }

    dInfoPtr = textPtr->dInfoPtr;
    ComputeCursorExtents(textPtr, &extent1, &extent2);
    inset = textPtr->borderWidth + textPtr->highlightWidth;

    textRect.x = inset + textPtr->padX - extent1;
    textRect.width = Tk_Width(textPtr->tkwin) - 2 * (inset + textPtr->padX) + extent1 + extent2;
    textRect.y = inset + textPtr->padY;
    textRect.height = Tk_Height(textPtr->tkwin) - 2 * (inset + textPtr->padY);

    /*
     * Find all lines that overlap the given region and mark them for redisplay.
     */

    if (RectIntersects(&clipRect, &textRect)) {
	for (dlPtr = dInfoPtr->dLinePtr; dlPtr; dlPtr = dlPtr->nextPtr) {
	    if (!(dlPtr->flags & OLD_Y_INVALID)) {
		int test = TkRectInRegion(region, clipRect.x, dlPtr->y, clipRect.width, dlPtr->height);

		if (test != RectangleOut) {
		    dlPtr->flags |= OLD_Y_INVALID;
		    RegionUnion(&dInfoPtr->invalidRegion, dlPtr->y, dlPtr->y + dlPtr->height);
		}
	    }
	}
    }

    if (dInfoPtr->topOfEof < (maxY = clipRect.y + clipRect.height)) {
	dInfoPtr->topOfEof = maxY;
    }

    /*
     * Also figure out whether the border needs a redraw.
     *
     * TODO: is it really neccessary to refresh the padding area, otherwise
     * we could simply check the border zone. But probably this part has to
     * consider a possible increasement of the padding area.
     */

    if (!RectContainsRect(&textRect, &clipRect)) {
	dInfoPtr->flags |= REDRAW_BORDERS;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkrTextChanged --
 *
 *	This function is invoked when info in a text widget is about to be
 *	modified in a way that changes how it is displayed (e.g. characters
 *	were inserted or deleted, or tag information was changed). This
 *	function must be called *before* a change is made, so that indexes in
 *	the display information are still valid.
 *
 *	Note: if the range of indices may change geometry as well as simply
 *	requiring redisplay, then the caller should also call
 *	TkTextInvalidateLineMetrics.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The range of character between index1Ptr (inclusive) and index2Ptr
 *	(exclusive) will be redisplayed at some point in the future (the
 *	actual redisplay is scheduled as a when-idle handler).
 *
 *----------------------------------------------------------------------
 */

static void
TextChanged(
    TkText *textPtr,			/* Widget record for text widget, or NULL. */
    const TkTextIndex *index1Ptr,	/* Index of first character to redisplay. */
    const TkTextIndex *index2Ptr)	/* Index of character just after last one to redisplay. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    TkTextLine *lastLinePtr = TkBTreeGetLastLine(textPtr);
    DLine *firstPtr = NULL;
    DLine *lastPtr= NULL;
    TkTextIndex rounded;
    TkTextLine *linePtr;

    assert(TkTextIndexGetLine(index1Ptr));

    /*
     * Find the DLines corresponding to index1Ptr and index2Ptr. There is one
     * tricky thing here, which is that we have to relayout in units of whole
     * text lines: This is necessary because the indices stored in the display
     * lines will no longer be valid. It's also needed because any edit could
     * change the way lines wrap.
     * To relayout in units of whole text (logical) lines, round index1Ptr
     * back to the beginning of its text line (or, if this line start is
     * elided, to the beginning of the text line that starts the display line
     * it is included in), and include all the display lines after index2Ptr,
     * up to the end of its text line (or, if this line end is elided, up to
     * the end of the first non elided text line after this line end).
     */

    if ((linePtr = TkTextIndexGetLine(index1Ptr)) != lastLinePtr) {
	rounded = *index1Ptr;
	TkTextIndexSetLine(&rounded, TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr));

	if (!(firstPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, &rounded))) {
	    /*
	     * index1Ptr pertains to no display line, i.e this index is after
	     * the last display line. Since index2Ptr is after index1Ptr, there
	     * is no display line to free/redisplay and we can return early.
	     */
	} else {
	    rounded = *index2Ptr;
	    linePtr = TkTextIndexGetLine(index2Ptr);
	    if (linePtr == lastLinePtr) {
		linePtr = NULL;
	    } else {
		linePtr = TkBTreeNextLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr);
		TkTextIndexSetLine(&rounded, linePtr);
	    }

	    if (!linePtr) {
		lastPtr = NULL;
	    } else {
		/*
		 * 'rounded' now points to the start of a display line as well as the
		 * start of a logical line not merged with its previous line, and
		 * this index is the closest after index2Ptr.
		 */

		lastPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, &rounded);

#if 0
		/*
		 * NOTE: In revised implementation this seems not to be useful,
		 * it is only causing superfluous redrawings.
		 */

		/*
		 * At least one display line is supposed to change. This makes the
		 * redisplay OK in case the display line we expect to get here was
		 * unlinked by a previous call to TkrTextChanged and the text widget
		 * did not update before reaching this point. This happens for
		 * instance when moving the cursor up one line.
		 * Note that lastPtr != NULL here, otherwise we would have returned
		 * earlier when we tested for firstPtr being NULL.
		 */

		if (lastPtr && lastPtr == firstPtr) {
		    lastPtr = lastPtr->nextPtr;
		}
#endif
	    }
	}
    }

    /*
     * Schedule both a redisplay and a recomputation of display information.
     * It's done here rather than the end of the function for two reasons:
     *
     * 1. If there are no display lines to update we'll want to return
     *	  immediately, well before the end of the function.
     *
     * 2. It's important to arrange for the redisplay BEFORE calling
     *	  FreeDLines. The reason for this is subtle and has to do with
     *	  embedded windows. The chunk delete function for an embedded window
     *	  will schedule an idle handler to unmap the window. However, we want
     *	  the idle handler for redisplay to be called first, so that it can
     *	  put the embedded window back on the screen again (if appropriate).
     *	  This will prevent the window from ever being unmapped, and thereby
     *	  avoid flashing.
     */

    DisplayTextWhenIdle(textPtr);
    dInfoPtr->flags |= DINFO_OUT_OF_DATE|REPICK_NEEDED;
    dInfoPtr->currChunkPtr = NULL;

    /*
     * Delete all the DLines from firstPtr up to but not including lastPtr.
     */

    FreeDLines(textPtr, firstPtr, lastPtr, DLINE_UNLINK_KEEP_BRKS);
}

void
TkrTextChanged(
    TkSharedText *sharedTextPtr,	/* Shared widget section, or NULL. */
    TkText *textPtr,			/* Widget record for text widget, or NULL. */
    const TkTextIndex *index1Ptr,	/* Index of first character to redisplay. */
    const TkTextIndex *index2Ptr)	/* Index of character just after last one to redisplay. */
{
    assert(!sharedTextPtr != !textPtr);

    if (!sharedTextPtr) {
	TextChanged(textPtr, index1Ptr, index2Ptr);
    } else {
	TkTextIndex index1 = *index1Ptr;
	TkTextIndex index2 = *index2Ptr;

	for (textPtr = sharedTextPtr->peers; textPtr; textPtr = textPtr->next) {
	    DEBUG(index1.discardConsistencyCheck = 1);
	    DEBUG(index2.discardConsistencyCheck = 1);
	    TkTextIndexSetPeer(&index1, textPtr);
	    TkTextIndexSetPeer(&index2, textPtr);
	    TextChanged(textPtr, &index1, &index2);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextRedrawTag --
 *
 *	This function is invoked to request a redraw of all characters in a
 *	given range that have a particular tag on or off. It's called, for
 *	example, when tag options change.
 *
 * Results:
 *	Return whether any redraw will happen.
 *
 * Side effects:
 *	Information on the screen may be redrawn, and the layout of the screen
 *	may change.
 *
 *----------------------------------------------------------------------
 */

static void
TextRedrawTag(
    TkText *textPtr,		/* Widget record for text widget. */
    const TkTextIndex *index1Ptr,
				/* First character in range to consider for redisplay. NULL
				 * means start at beginning of text. */
    const TkTextIndex *index2Ptr,
				/* Character just after last one to consider for redisplay.
				 * NULL means process all the characters in the text. */
    int affectsDisplayGeometry)/* Whether the display geometry is affected. */
{
    TextDInfo *dInfoPtr;
    DLine *dlPtr;
    DLine *endPtr;

    if (textPtr->flags & DESTROYED) {
	return;
    }

    assert(index1Ptr);
    assert(index2Ptr);
    assert(textPtr);

    dInfoPtr = textPtr->dInfoPtr;
    dlPtr = dInfoPtr->dLinePtr;

    if (!dlPtr) {
	return;
    }

    /*
     * Invalidate the pixel calculation of all lines in the given range.
     */

    if (affectsDisplayGeometry) {
	TkTextLine *startLine, *endLine;
	unsigned lineCount;

	dInfoPtr->currChunkPtr = NULL; /* reset cached chunk */
	endLine = TkTextIndexGetLine(index2Ptr);
	if (endLine == textPtr->endMarker->sectionPtr->linePtr) {
	    assert(endLine->prevPtr);
	    endLine = endLine->prevPtr;
	}
	lineCount = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, endLine, NULL);
	startLine = TkTextIndexGetLine(index1Ptr);
	lineCount -= TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, startLine, NULL);
	TkTextInvalidateLineMetrics(NULL, textPtr, startLine, lineCount, TK_TEXT_INVALIDATE_ONLY);
    }

    /*
     * Round up the starting position if it's before the first line visible on
     * the screen (we only care about what's on the screen).
     */

    if (TkTextIndexCompare(&dlPtr->index, index1Ptr) > 0) {
	index1Ptr = &dlPtr->index;
    }

    /*
     * Schedule a redisplay and layout recalculation if they aren't already
     * pending. This has to be done before calling FreeDLines, for the reason
     * given in TkrTextChanged.
     */

    DisplayTextWhenIdle(textPtr);
    dInfoPtr->flags |= DINFO_OUT_OF_DATE|REPICK_NEEDED;

    /*
     * Each loop through the loop below is for one range of characters where
     * the tag's current state is different than its eventual state. At the
     * top of the loop, search contains information about the first character
     * in the range.
     */

    dlPtr = FindDLine(textPtr, dlPtr, index1Ptr);

    if (dlPtr) {
	/*
	 * Find the first DLine structure that's past the end of the range.
	 */

	endPtr = FindDLine(textPtr, dlPtr, index2Ptr);
	if (endPtr && TkTextIndexCompare(&endPtr->index, index2Ptr) < 0) {
	    endPtr = endPtr->nextPtr;
	}

	/*
	 * Delete all of the display lines in the range, so that they'll be
	 * re-layed out and redrawn.
	 */

	FreeDLines(textPtr, dlPtr, endPtr, DLINE_UNLINK);
    }
}

static void
RedrawTagsInPeer(
    const TkSharedText *sharedTextPtr,
    TkText *textPtr,
    TkTextIndex *indexPtr1,
    TkTextIndex *indexPtr2,
    int affectsDisplayGeometry)
{
    TkTextIndex start, end;

    if (!textPtr->dInfoPtr || !textPtr->dInfoPtr->dLinePtr) {
	return;
    }

    if (textPtr->startMarker != sharedTextPtr->startMarker) {
	TkTextIndexSetupToStartOfText(&start, textPtr, sharedTextPtr->tree);
	if (TkTextIndexCompare(indexPtr1, &start) <= 0) {
	    indexPtr1 = &start;
	}
    }

    if (textPtr->endMarker != sharedTextPtr->endMarker) {
	TkTextIndexSetupToEndOfText(&end, textPtr, sharedTextPtr->tree);
	if (TkTextIndexCompare(indexPtr2, &end) <= 0) {
	    indexPtr2 = &end;
	}
    }

    TkTextIndexSetPeer(indexPtr1, textPtr);
    TkTextIndexSetPeer(indexPtr2, textPtr);
    TextRedrawTag(textPtr, indexPtr1, indexPtr2, affectsDisplayGeometry);
}

int
TkTextRedrawTag(
    const TkSharedText *sharedTextPtr,
				/* Shared widget section, or NULL if textPtr is not NULL. */
    TkText *textPtr,		/* Widget record for text widget, or NULL if sharedTextPtr is not
				 * NULL. */
    const TkTextIndex *index1Ptr,
				/* First character in range to consider for redisplay. NULL means
				 * start at beginning of text. */
    const TkTextIndex *index2Ptr,
				/* Character just after last one to consider for redisplay. NULL
				 * means process all the characters in the text. Note that either
				 * both indices are NULL, or both are non-Null. */
    const TkTextTag *tagPtr,	/* Information about tag, can be NULL, but only if the indices are
				 * non-NULL*/
    int affectsDisplayGeometry)/* Whether the display geometry is affected. If argument tagPtr is
				 * given, then also this tag will be tested if the display geometry
				 * is affected. */
{
    assert(!index1Ptr == !index2Ptr);
    assert(index1Ptr || tagPtr);
    assert(sharedTextPtr || textPtr);

    if (!sharedTextPtr && !textPtr->dInfoPtr->dLinePtr) {
	return 0;
    }

    if (tagPtr && tagPtr->affectsDisplayGeometry) {
	affectsDisplayGeometry = 1;
    }

    if (!index1Ptr) {
	TkTextSegment *endMarker;
	TkTextSearch search;
	TkTextIndex startIndex, endIndex;

	if (!sharedTextPtr) {
	    TkTextIndexClear2(&startIndex, NULL, textPtr->sharedTextPtr->tree);
	    TkTextIndexClear2(&endIndex, NULL, textPtr->sharedTextPtr->tree);
	    TkTextIndexSetSegment(&startIndex, textPtr->startMarker);
	    TkTextIndexSetSegment(&endIndex, textPtr->endMarker);
	    endMarker = textPtr->endMarker;
	} else {
	    TkTextIndexClear2(&startIndex, NULL, sharedTextPtr->tree);
	    TkTextIndexClear2(&endIndex, NULL, sharedTextPtr->tree);
	    TkTextIndexSetSegment(&startIndex, sharedTextPtr->startMarker);
	    TkTextIndexSetSegment(&endIndex, sharedTextPtr->endMarker);
	    endMarker = sharedTextPtr->endMarker;
	}

	/*
	 * Now we try to restrict the range, because redrawing is in general an expensive
	 * operation.
	 */

	if (tagPtr) {
	    int found = 0;

	    TkBTreeStartSearch(&startIndex, &endIndex, tagPtr, &search, SEARCH_EITHER_TAGON_TAGOFF);

	    while (1) {
		if (!TkBTreeNextTag(&search)) {
		    return found;
		}
		if (search.tagon) {
		    /* we need end of range */
		    startIndex = search.curIndex;
		    TkBTreeNextTag(&search);
		    assert(search.segPtr); /* search must not fail */
		} else {
		    assert(!found);
		}
		found = 1;
		assert(!search.tagon);
		if (!sharedTextPtr) {
		    TextRedrawTag(textPtr, &startIndex, &search.curIndex, affectsDisplayGeometry);
		} else {
		    for (textPtr = sharedTextPtr->peers; textPtr; textPtr = textPtr->next) {
			RedrawTagsInPeer(sharedTextPtr, textPtr, &startIndex, &search.curIndex,
				affectsDisplayGeometry);
		    }
		}
	    }
	} else {
	    const TkBitField *discardTags = NULL;
	    TkTextSegment *segPtr;
	    TkTextIndex index2;

	    if (affectsDisplayGeometry) {
		if (sharedTextPtr) {
		    discardTags = sharedTextPtr->notAffectDisplayTags;
		} else {
		    discardTags = textPtr->sharedTextPtr->notAffectDisplayTags;
		}
	    }
	    if (!(segPtr = TkBTreeFindNextTagged(&startIndex, &endIndex, discardTags))) {
		return 0;
	    }
	    index2 = endIndex;

	    while (segPtr) {
		TkTextSegment *endPtr;

		TkTextIndexSetSegment(&startIndex, segPtr);
		endPtr = TkBTreeFindNextUntagged(&startIndex, &endIndex, discardTags);

		if (!endPtr) {
		    endPtr = endMarker;
		}

		TkTextIndexSetSegment(&index2, endPtr);

		if (!sharedTextPtr) {
		    TextRedrawTag(textPtr, &startIndex, &index2, affectsDisplayGeometry);
		} else {
		    for (textPtr = sharedTextPtr->peers; textPtr; textPtr = textPtr->next) {
			RedrawTagsInPeer(sharedTextPtr, textPtr, &startIndex, &index2,
				affectsDisplayGeometry);
		    }
		}
	    }
	}
    } else if (!sharedTextPtr) {
	TextRedrawTag(textPtr, index1Ptr, index2Ptr, affectsDisplayGeometry);
    } else {
	TkTextIndex index1 = *index1Ptr;
	TkTextIndex index2 = *index2Ptr;

	for (textPtr = sharedTextPtr->peers; textPtr; textPtr = textPtr->next) {
	    RedrawTagsInPeer(sharedTextPtr, textPtr, &index1, &index2, affectsDisplayGeometry);
	}
    }

    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextRelayoutWindow --
 *
 *	This function is called when something has happened that invalidates
 *	the whole layout of characters on the screen, such as a change in a
 *	configuration option for the overall text widget or a change in the
 *	window size. It causes all display information to be recomputed and
 *	the window to be redrawn.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	All the display information will be recomputed for the window and the
 *	window will be redrawn.
 *
 *----------------------------------------------------------------------
 */

void
TkTextRelayoutWindow(
    TkText *textPtr,		/* Widget record for text widget. */
    int mask)			/* OR'd collection of bits showing what has changed. */
{
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    XGCValues gcValues;
    GC newGC;
    int recomputeGeometry;
    int asyncLineCalculation;
    unsigned firstLineNo;
    unsigned lastLineNo;
    int maxX;

    if ((mask & TK_TEXT_LINE_REDRAW_BOTTOM_LINE) && dInfoPtr->lastDLinePtr) {
	dInfoPtr->lastDLinePtr->flags |= OLD_Y_INVALID;
    }

    /*
     * Schedule the window redisplay. See TkrTextChanged for the reason why
     * this has to be done before any calls to FreeDLines.
     */

    DisplayTextWhenIdle(textPtr);
    dInfoPtr->flags |= REDRAW_BORDERS|DINFO_OUT_OF_DATE|REPICK_NEEDED;

    /*
     * (Re-)create the graphics context for drawing the traversal highlight.
     */

    gcValues.graphics_exposures = False;
    newGC = Tk_GetGC(textPtr->tkwin, GCGraphicsExposures, &gcValues);
    if (dInfoPtr->copyGC != NULL) {
	Tk_FreeGC(textPtr->display, dInfoPtr->copyGC);
    }
    dInfoPtr->copyGC = newGC;

    /*
     * (Re-)create the graphics context for drawing the characters "behind" the block cursor.
     */

    if (dInfoPtr->insertFgGC != NULL) {
	Tk_FreeGC(textPtr->display, dInfoPtr->insertFgGC);
	dInfoPtr->insertFgGC = NULL;
    }
    if (textPtr->state == TK_TEXT_STATE_NORMAL
	    && textPtr->blockCursorType
	    && textPtr->showInsertFgColor) {
	gcValues.foreground = textPtr->insertFgColor->pixel;
	dInfoPtr->insertFgGC = Tk_GetGC(textPtr->tkwin, GCForeground, &gcValues);
    }

    maxX = MAX(Tk_Width(textPtr->tkwin) - dInfoPtr->x, dInfoPtr->x + 1);
    firstLineNo = TkBTreeLinesTo(sharedTextPtr->tree, NULL, TkBTreeGetStartLine(textPtr), NULL);
    lastLineNo = TkBTreeLinesTo(sharedTextPtr->tree, NULL, TkBTreeGetLastLine(textPtr), NULL);
    recomputeGeometry = (maxX != dInfoPtr->maxX) || (mask & TK_TEXT_LINE_GEOMETRY);

    /*
     * Throw away all the current display lines, except the visible ones if
     * they will not change.
     */

    if (recomputeGeometry || (mask & TK_TEXT_LINE_REDRAW)) {
	FreeDLines(textPtr, dInfoPtr->dLinePtr, NULL, DLINE_UNLINK_KEEP_BRKS);
    }

    FreeDLines(textPtr, NULL, NULL, DLINE_CACHE);  /* release cached display lines */
    FreeDLines(textPtr, NULL, NULL, DLINE_METRIC); /* release cached lines */
    FreeDLines(textPtr, dInfoPtr->savedDLinePtr, NULL, DLINE_FREE_TEMP);

    /*
     * Recompute some overall things for the layout. Even if the window gets very small,
     * pretend that there's at least one pixel of drawing space in it.
     */

    assert(textPtr->highlightWidth >= 0);
    assert(textPtr->borderWidth >= 0);

    dInfoPtr->x = textPtr->highlightWidth + textPtr->borderWidth + textPtr->padX;
    dInfoPtr->y = textPtr->highlightWidth + textPtr->borderWidth + textPtr->padY;

    dInfoPtr->maxX = MAX(Tk_Width(textPtr->tkwin) - dInfoPtr->x, dInfoPtr->x + 1);

    /*
     * This is the only place where dInfoPtr->maxY is set.
     */

    dInfoPtr->maxY = MAX(Tk_Height(textPtr->tkwin) - dInfoPtr->y, dInfoPtr->y + 1);
    dInfoPtr->topOfEof = dInfoPtr->maxY;

    /*
     * If the upper-left character isn't the first in a line, recompute it.
     * This is necessary because a change in the window's size or options
     * could change the way lines wrap.
     */

    if (!IsStartOfNotMergedLine(&textPtr->topIndex)) {
	TkTextFindDisplayLineStartEnd(textPtr, &textPtr->topIndex, DISP_LINE_START);
    }

    /*
     * Invalidate cached scrollbar positions, so that scrollbars sliders will be udpated.
     */

    dInfoPtr->xScrollFirst = dInfoPtr->xScrollLast = -1;
    dInfoPtr->yScrollFirst = dInfoPtr->yScrollLast = -1;

    /*
     * Invalidate cached cursor chunk.
     */

    dInfoPtr->currChunkPtr = NULL;

    if (mask & TK_TEXT_LINE_GEOMETRY) {
	/* Setup end of line segment. */
	SetupEolSegment(textPtr, dInfoPtr);
	SetupEotSegment(textPtr, dInfoPtr);
    }

    asyncLineCalculation = 0;

#if SPEEDUP_MONOSPACED_LINE_HEIGHTS
    if (TestMonospacedLineHeights(textPtr)) {
	TkRangeList *ranges = textPtr->dInfoPtr->lineMetricUpdateRanges;

	if (!TkRangeListIsEmpty(ranges)) {
	    TkBTreeUpdatePixelHeights(textPtr,
		    TkBTreeFindLine(sharedTextPtr->tree, textPtr, TkRangeListLow(ranges)),
		    TkRangeListSpan(ranges), dInfoPtr->lineMetricUpdateEpoch);
	    TkRangeListClear(ranges);
	}
	if (dInfoPtr->lineHeight != textPtr->lineHeight) {
	    TkBTreeUpdatePixelHeights(textPtr, TkBTreeGetStartLine(textPtr), lastLineNo - firstLineNo,
		    dInfoPtr->lineMetricUpdateEpoch);
	    dInfoPtr->lineHeight = textPtr->lineHeight;
	}
    } else
#endif
    if (recomputeGeometry) {
	/*
	 * Set up line metric recalculation.
	 */

	dInfoPtr->lineHeight = 0;
	TkRangeListClear(dInfoPtr->lineMetricUpdateRanges);
	if (lastLineNo > firstLineNo) {
	    dInfoPtr->lineMetricUpdateRanges =
		    TkRangeListAdd(dInfoPtr->lineMetricUpdateRanges, 0, lastLineNo - firstLineNo - 1);
	    dInfoPtr->lineMetricUpdateEpoch += 1;
	    asyncLineCalculation = 1;
	}
    } else {
	TkTextIndex index;
	DLine *dlPtr;
	int numLines;

	dInfoPtr->lineHeight = 0;

	/*
	 * We have to handle -startindex, -endIndex.
	 */

	if (lastLineNo == firstLineNo) {
	    FreeDLines(textPtr, dInfoPtr->dLinePtr, NULL, DLINE_UNLINK);
	    TkRangeListClear(dInfoPtr->lineMetricUpdateRanges);
	} else if (dInfoPtr->lastLineNo <= firstLineNo || lastLineNo <= dInfoPtr->firstLineNo) {
	    FreeDLines(textPtr, dInfoPtr->dLinePtr, NULL, DLINE_UNLINK);
	    TkRangeListClear(dInfoPtr->lineMetricUpdateRanges);
	    dInfoPtr->lineMetricUpdateRanges = TkRangeListAdd(
		    dInfoPtr->lineMetricUpdateRanges, 0, lastLineNo - firstLineNo - 1);
	    asyncLineCalculation = 1;
	} else {
	    if (firstLineNo < dInfoPtr->firstLineNo) {
		dInfoPtr->lineMetricUpdateRanges = TkRangeListInsert(
			dInfoPtr->lineMetricUpdateRanges, 0, dInfoPtr->firstLineNo - firstLineNo - 1);
		asyncLineCalculation = 1;
	    } else if (dInfoPtr->firstLineNo < firstLineNo) {
		TkTextIndexSetupToStartOfText(&index, textPtr, sharedTextPtr->tree);
		dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, &index);
		FreeDLines(textPtr, dInfoPtr->dLinePtr, dlPtr, DLINE_UNLINK);
		numLines = firstLineNo - dInfoPtr->firstLineNo;
		TkRangeListDelete(dInfoPtr->lineMetricUpdateRanges, 0, numLines - 1);
	    }
	    if (dInfoPtr->lastLineNo < lastLineNo) {
		dInfoPtr->lineMetricUpdateRanges = TkRangeListAdd(
			dInfoPtr->lineMetricUpdateRanges,
			dInfoPtr->lastLineNo - dInfoPtr->firstLineNo,
			lastLineNo - firstLineNo - 1);
		asyncLineCalculation = 1;
	    } else if (lastLineNo < dInfoPtr->lastLineNo) {
		TkTextIndexSetupToEndOfText(&index, textPtr, sharedTextPtr->tree);
		dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, &index);
		FreeDLines(textPtr, dlPtr, NULL, DLINE_UNLINK);
		TkRangeListTruncateAtEnd(dInfoPtr->lineMetricUpdateRanges, lastLineNo - firstLineNo - 1);
	    }
	}
    }

    dInfoPtr->firstLineNo = firstLineNo;
    dInfoPtr->lastLineNo = lastLineNo;

    if (asyncLineCalculation) {
	StartAsyncLineCalculation(textPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextSetYView --
 *
 *	This function is called to specify what lines are to be displayed in a
 *	text widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The display will (eventually) be updated so that the position given by
 *	"indexPtr" is visible on the screen at the position determined by
 *	"pickPlace".
 *
 *----------------------------------------------------------------------
 */

void
TkTextSetYView(
    TkText *textPtr,		/* Widget record for text widget. */
    TkTextIndex *indexPtr,	/* Position that is to appear somewhere in the view. */
    int pickPlace)		/* 0 means the given index must appear exactly at the top of the
				 * screen. TK_TEXT_PICKPLACE (-1) means we get to pick where it
				 * appears: minimize screen motion or else display line at center
				 * of screen. TK_TEXT_NOPIXELADJUST (-2) indicates to make the
				 * given index the top line, but if it is already the top line,
				 * don't nudge it up or down by a few pixels just to make sure
				 * it is entirely displayed. Positive numbers indicate the number
				 * of pixels of the index's line which are to be off the top of
				 * the screen. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    DLine *dlPtr;
    int bottomY, close;
    TkTextIndex tmpIndex;
    TkTextLine *linePtr;
    int lineHeight;
    int topLineNo;
    int topByteIndex;
    int32_t overlap;

    if (TkTextIsDeadPeer(textPtr)) {
	textPtr->topIndex = *indexPtr;
	TkTextIndexMakePersistent(&textPtr->topIndex);
	TkTextIndexSetPeer(&textPtr->topIndex, textPtr);
	return;
    }

    /*
     * If the specified position is the extra line at the end of the text,
     * round it back to the last real line.
     */

    linePtr = TkTextIndexGetLine(indexPtr);

    if (linePtr == TkBTreeGetLastLine(textPtr) && TkTextIndexGetByteIndex(indexPtr) == 0) {
	assert(linePtr->prevPtr);
	assert(TkBTreeGetStartLine(textPtr) != linePtr);
	TkTextIndexSetToEndOfLine2(indexPtr, linePtr->prevPtr);
    }

    if (pickPlace == TK_TEXT_NOPIXELADJUST) {
	pickPlace = TkTextIndexIsEqual(&textPtr->topIndex, indexPtr) ? dInfoPtr->topPixelOffset : 0;
    }

    if (pickPlace != TK_TEXT_PICKPLACE) {
	/*
	 * The specified position must go at the top of the screen. Just leave
	 * all the DLine's alone: we may be able to reuse some of the information
	 * that's currently on the screen without redisplaying it all.
	 */

	textPtr->topIndex = *indexPtr;
	TkTextIndexMakePersistent(&textPtr->topIndex);
	TkTextIndexSetPeer(&textPtr->topIndex, textPtr);
	if (!IsStartOfNotMergedLine(indexPtr)) {
	    TkTextFindDisplayLineStartEnd(textPtr, &textPtr->topIndex, DISP_LINE_START);
	}
	dInfoPtr->newTopPixelOffset = pickPlace;
	goto scheduleUpdate;
    }

    /*
     * We have to pick where to display the index. First, bring the display
     * information up to date and see if the index will be completely visible
     * in the current screen configuration. If so then there's nothing to do.
     */

    if (dInfoPtr->flags & DINFO_OUT_OF_DATE) {
	UpdateDisplayInfo(textPtr);
    }

    if ((dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, indexPtr))) {
	int x, y, width, height;

	if (TkTextIndexCompare(&dlPtr->index, indexPtr) <= 0
		&& GetBbox(textPtr, dlPtr, indexPtr, &x, &y, &width, &height, NULL, NULL)) {
	    assert(TkTextIndexCountBytes(&dlPtr->index, indexPtr) <= dlPtr->byteCount);
	    if (dInfoPtr->y <= y && y + height <= dInfoPtr->maxY - dInfoPtr->y) {
		return; /* this character is fully visible, so we don't need to scroll */
	    }
	    if (dlPtr->height > dInfoPtr->maxY - dInfoPtr->y) {
		/*
		 * This line has more height than the view, so either center the char,
		 * or position at top of view.
		 */
		textPtr->topIndex = *indexPtr;
		TkTextIndexMakePersistent(&textPtr->topIndex);
		dInfoPtr->newTopPixelOffset = MAX(0, y - dlPtr->y - (dInfoPtr->maxY - height)/2);
		goto scheduleUpdate;
	    }
	}
	if (dlPtr->y + dlPtr->height > dInfoPtr->maxY) {
	    /*
	     * Part of the line hangs off the bottom of the screen; pretend
	     * the whole line is off-screen.
	     */
	    dlPtr = NULL;
	} else {
	    if (TkTextIndexCompare(&dlPtr->index, indexPtr) <= 0) {
		if (dInfoPtr->dLinePtr == dlPtr && dInfoPtr->topPixelOffset != 0) {
		    /*
		     * It is on the top line, but that line is hanging off the top
		     * of the screen. Change the top overlap to zero and update.
		     */
		    dInfoPtr->newTopPixelOffset = 0;
		    goto scheduleUpdate;
		}
		return; /* the line is already on screen, with no need to scroll */
	    }
	}
    }

    /*
     * The desired line isn't already on-screen. Figure out what it means to
     * be "close" to the top or bottom of the screen. Close means within 1/3
     * of the screen height or within three lines, whichever is greater.
     *
     * If the line is not close, place it in the center of the window.
     */

    tmpIndex = *indexPtr;
    FindDisplayLineStartEnd(textPtr, &tmpIndex, DISP_LINE_START, DLINE_METRIC);
    lineHeight = CalculateDisplayLineHeight(textPtr, &tmpIndex, NULL);

    if (lineHeight > dInfoPtr->maxY - dInfoPtr->y) {
	int x, y, width, height;
	DisplayInfo info;

	/*
	 * In this case we have either to center the char, or to bring it to
	 * the top position, otherwise it may happen that it will not be visible.
	 */

	FreeDLines(textPtr, dInfoPtr->dLinePtr, NULL, DLINE_UNLINK); /* not needed anymore */
	ComputeDisplayLineInfo(textPtr, indexPtr, &info);
	if (!info.dLinePtr) {
	    tmpIndex = *indexPtr;
	    TkrTextIndexBackBytes(textPtr, &tmpIndex, info.byteOffset, &tmpIndex);
	    dlPtr = info.dLinePtr = info.lastDLinePtr = LayoutDLine(&tmpIndex, info.displayLineNo);
	    SaveDisplayLines(textPtr, &info, 1);
	}
	GetBbox(textPtr, dlPtr, indexPtr, &x, &y, &width, &height, NULL, NULL);
	dInfoPtr->newTopPixelOffset = MAX(0, y - dlPtr->y - (dInfoPtr->maxY - height)/2);
	textPtr->topIndex = *indexPtr;
	TkTextIndexMakePersistent(&textPtr->topIndex);
    } else {
	/*
	 * It would be better if 'bottomY' were calculated using the actual height
	 * of the given line, not 'textPtr->lineHeight'.
	 */

	bottomY = (dInfoPtr->y + dInfoPtr->maxY + lineHeight)/2;
	close = (dInfoPtr->maxY - dInfoPtr->y)/3;
	if (close < 3*textPtr->lineHeight) {
	    close = 3*textPtr->lineHeight;
	}
	if (dlPtr) {

	    /*
	     * The desired line is above the top of screen. If it is "close" to
	     * the top of the window then make it the top line on the screen.
	     * MeasureUp counts from the bottom of the given index upwards, so we
	     * add an extra half line to be sure we count far enough.
	     */

	    MeasureUp(textPtr, &textPtr->topIndex, close + textPtr->lineHeight/2, &tmpIndex, &overlap);
	    if (TkTextIndexCompare(&tmpIndex, indexPtr) <= 0) {
		textPtr->topIndex = *indexPtr;
		TkTextIndexMakePersistent(&textPtr->topIndex);
		TkTextIndexSetPeer(&textPtr->topIndex, textPtr);
		TkTextFindDisplayLineStartEnd(textPtr, &textPtr->topIndex, DISP_LINE_START);
		dInfoPtr->newTopPixelOffset = 0;
		goto scheduleUpdate;
	    }
	} else {
	    /*
	     * The desired line is below the bottom of the screen. If it is
	     * "close" to the bottom of the screen then position it at the bottom
	     * of the screen.
	     */

	    MeasureUp(textPtr, indexPtr, close + lineHeight - textPtr->lineHeight/2, &tmpIndex,
		    &overlap);
	    if (FindDLine(textPtr, dInfoPtr->dLinePtr, &tmpIndex)) {
		bottomY = dInfoPtr->maxY - dInfoPtr->y;
	    }
	}

	/*
	 * If the window height is smaller than the line height, prefer to make
	 * the top of the line visible.
	 */

	if (dInfoPtr->maxY - dInfoPtr->y < lineHeight) {
	    bottomY = lineHeight;
	}

	/*
	 * Our job now is to arrange the display so that indexPtr appears as low
	 * on the screen as possible but with its bottom no lower than bottomY.
	 * BottomY is the bottom of the window if the desired line is just below
	 * the current screen, otherwise it is a half-line lower than the center
	 * of the window.
	 */

	MeasureUp(textPtr, indexPtr, bottomY, &textPtr->topIndex, &dInfoPtr->newTopPixelOffset);
    }

  scheduleUpdate:
    topLineNo = TkTextIndexGetLineNumber(&textPtr->topIndex, NULL);
    topByteIndex = TkTextIndexGetByteIndex(&textPtr->topIndex);

    if (dInfoPtr->newTopPixelOffset != dInfoPtr->topPixelOffset
	    || dInfoPtr->topLineNo != topLineNo
	    || dInfoPtr->topByteIndex != topByteIndex) {
	DisplayTextWhenIdle(textPtr);
	dInfoPtr->flags |= DINFO_OUT_OF_DATE|REPICK_NEEDED;
	dInfoPtr->topLineNo = topLineNo;
	dInfoPtr->topByteIndex = topByteIndex;
    }
}

/*
 *--------------------------------------------------------------
 *
 * FindDisplayLineOffset --
 *
 *	Given a line pointer to a logical line, and a distance in
 *	pixels, find the byte offset of the corresponding display
 *	line. If only one display line belongs to the given logical
 *	line, then the offset is always zero.
 *
 * Results:
 *	Returns the offset to the display line at specified pixel
 *	position, relative to the given logical line. 'distance'
 *	will be set to the vertical distance in pixels measured
 *	from the top pixel in specified display line (this means,
 *	that all the display lines pixels between the top of the
 *	logical line and the corresponding display line will be
 *	subtracted).
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static const TkTextDispLineEntry *
SearchPixelEntry(
    const TkTextDispLineEntry *first,
    const TkTextDispLineEntry *last,
    unsigned pixels)
{
    assert(first != last);

    if ((last - 1)->pixels < pixels) {
	return last - 1; /* catch a frequent case */
    }

    do {
	const TkTextDispLineEntry *mid = first + (last - first)/2;

	if (mid->pixels <= pixels) {
	    first = mid + 1;
	} else {
	    last = mid;
	}
    } while (first != last);

    return first;
}

static unsigned
FindDisplayLineOffset(
    TkText *textPtr,
    TkTextLine *linePtr,
    int32_t *distance)	/* IN:  distance in pixels to logical line
			 * OUT: distance in pixels of specified display line. */
{
    const TkTextPixelInfo *pixelInfo = TkBTreeLinePixelInfo(textPtr, linePtr);
    const TkTextDispLineInfo *dispLineInfo = pixelInfo->dispLineInfo;
    const TkTextDispLineEntry *lastEntry;
    const TkTextDispLineEntry *entry;

    assert(distance);
    assert(*distance >= 0);
    assert(linePtr->logicalLine);

    if (!dispLineInfo) {
	return 0;
    }

    lastEntry = dispLineInfo->entry + dispLineInfo->numDispLines;
    entry = SearchPixelEntry(dispLineInfo->entry, lastEntry, *distance);
    assert(entry != lastEntry);
    if (entry == dispLineInfo->entry) {
	return 0;
    }

    *distance -= (entry - 1)->pixels;
    return entry->byteOffset;
}

/*
 *--------------------------------------------------------------
 *
 * MeasureDown --
 *
 *	Given one index, find the index of the first character on the highest
 *	display line that would be displayed no more than "distance" pixels
 *	below the top of the given index.
 *
 * Results:
 *	The srcPtr is manipulated in place to reflect the new position. We
 *	return the number of pixels by which 'distance' overlaps the srcPtr
 *	in 'overlap'. The return valus is 'false' if we are already at top
 *	of view, otherwise the return valus is 'true'.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
AlreadyAtBottom(
    const TkText *textPtr)
{
    const TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    DLine *dlPtr = dInfoPtr->lastDLinePtr;
    TkTextIndex index;

    if (!dlPtr) {
	return 1;
    }
    if (dlPtr->y + dlPtr->height != dInfoPtr->maxY) {
	return 0;
    }

    index = dlPtr->index;
    TkrTextIndexForwBytes(textPtr, &index, dlPtr->byteCount, &index);
    return TkTextIndexIsEndOfText(&index);
}

static int
MeasureDown(
    TkText *textPtr,		/* Text widget in which to measure. */
    TkTextIndex *srcPtr,	/* Index of character from which to start measuring. */
    int distance,		/* Vertical distance in pixels measured from the top pixel in
				 * srcPtr's logical line. */
    int32_t *overlap,		/* The number of pixels by which 'distance' overlaps the srcPtr. */
    int saveDisplayLines)	/* Save produced display line for re-use in UpdateDisplayInfo? */
{
    const TkTextLine *lastLinePtr;
    TkTextLine *linePtr;
    TkTextIndex index;
    int byteOffset;
    int32_t myOverlap;

    if (AlreadyAtBottom(textPtr)) {
	return 0;
    }

    if (!overlap) {
	overlap = &myOverlap;
    }

    linePtr = TkTextIndexGetLine(srcPtr);
    lastLinePtr = TkBTreeGetLastLine(textPtr);

    if (TkRangeListIsEmpty(textPtr->dInfoPtr->lineMetricUpdateRanges)) {
	int pixelHeight;

	/*
	 * No display line metric calculation is pending, this is fine,
	 * now we can use the B-Tree for the measurement.
	 *
	 * Note that TkBTreePixelsTo is measuring up to the logical line.
	 */

	pixelHeight = TkBTreePixelsTo(textPtr, linePtr);
	pixelHeight += GetPixelsTo(textPtr, srcPtr, 0, NULL);
	pixelHeight += distance;
	linePtr = TkBTreeFindPixelLine(srcPtr->tree, textPtr, pixelHeight, overlap);

	if (linePtr == lastLinePtr) {
	    TkTextLine *prevLinePtr = TkBTreePrevLine(textPtr, linePtr);
	    if (prevLinePtr) {
		linePtr = prevLinePtr;
	    }
	}

	/*
	 * We have the logical line, and the overlap, now search for the display line.
	 */

	byteOffset = FindDisplayLineOffset(textPtr, linePtr, overlap);
    } else {
	DisplayInfo info;

	/*
	 * Search down line by line until we'e found the bottom line for given distance.
	 */

	linePtr = ComputeDisplayLineInfo(textPtr, srcPtr, &info);
	distance += GetPixelsTo(textPtr, srcPtr, 0, &info);
	index = *srcPtr;

	while (1) {
	    ComputeMissingMetric(textPtr, &info, THRESHOLD_PIXEL_DISTANCE, distance);
	    if (saveDisplayLines) {
		SaveDisplayLines(textPtr, &info, 1);
	    } else {
		FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
	    }

	    if (distance < info.pixels) {
		const TkTextDispLineInfo *dispLineInfo = info.pixelInfo->dispLineInfo;

		if (dispLineInfo) {
		    const TkTextDispLineEntry *entry, *last;

		    last = dispLineInfo->entry + dispLineInfo->numDispLines;
		    entry = SearchPixelEntry(dispLineInfo->entry, last, distance);
		    assert(entry < last);
		    byteOffset = entry->byteOffset;
		    if (entry != dispLineInfo->entry) {
			distance -= (entry - 1)->pixels;
		    }
		} else {
		    byteOffset = 0;
		}
		break;
	    }

	    if (TkTextIndexGetLine(&info.index) == lastLinePtr) {
		byteOffset = 0;
		distance = *overlap;
		break;
	    }
	    linePtr = TkTextIndexGetLine(&info.index);
	    if ((distance -= info.pixels) == 0) {
		byteOffset = 0;
		break;
	    }
	    TkTextIndexSetToStartOfLine2(&index, linePtr);
	    linePtr = ComputeDisplayLineInfo(textPtr, &index, &info);
	}

	*overlap = distance;
    }

    assert(linePtr != lastLinePtr);

    TkTextIndexSetToStartOfLine2(srcPtr, linePtr);
    TkrTextIndexForwBytes(textPtr, srcPtr, byteOffset, srcPtr);

    return 1;
}

/*
 *--------------------------------------------------------------
 *
 * MeasureUp --
 *
 *	Given one index, find the index of the first character on the highest
 *	display line that would be displayed no more than "distance" pixels
 *	above the given index.
 *
 *	If this function is called with distance=0, it simply finds the first
 *	index on the same display line as srcPtr. However, there is a another
 *	function TkTextFindDisplayLineStartEnd designed just for that task
 *	which is probably better to use.
 *
 * Results:
 *	*dstPtr is filled in with the index of the first character on a
 *	display line. The display line is found by measuring up "distance"
 *	pixels above the pixel just below an imaginary display line that
 *	contains srcPtr. If the display line that covers this coordinate
 *	actually extends above the coordinate, then return any excess pixels
 *	in *overlap. The return valus is 'false' if we are already at top
 *	of view, otherwise the return valus is 'false'.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
AlreadyAtTop(
    const TkText *textPtr)
{
    const TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    if (!dInfoPtr->dLinePtr) {
	return 1;
    }
    return dInfoPtr->topPixelOffset == 0 && TkTextIndexIsStartOfText(&dInfoPtr->dLinePtr->index);
}

static int
MeasureUp(
    TkText *textPtr,		/* Text widget in which to measure. */
    const TkTextIndex *srcPtr,	/* Index of character from which to start measuring. */
    int distance,		/* Vertical distance in pixels measured from the pixel just below
				 * the lowest one in srcPtr's line. */
    TkTextIndex *dstPtr,	/* Index to fill in with result. */
    int32_t *overlap)		/* Used to store how much of the final index returned was not covered
				 * by 'distance'. */
{
    TkTextLine *linePtr;
    TkTextLine *startLinePtr;
    unsigned byteOffset;

    assert(overlap);
    assert(dstPtr);

    if (TkTextIndexIsStartOfText(srcPtr) && AlreadyAtTop(textPtr)) {
	return 0;
    }

    if (dstPtr != srcPtr) {
	*dstPtr = *srcPtr;
    }
    startLinePtr = TkBTreeGetStartLine(textPtr);
    linePtr = TkTextIndexGetLine(srcPtr);

    if (TestIfLinesUpToDate(srcPtr)) {
	int pixelHeight;

	/*
	 * No display line height calculation is pending (not in required range),
	 * this is fine, now we can use the B-Tree for the measurement.
	 *
	 * Note that TkBTreePixelsTo is measuring up to the logical line.
	 */

	pixelHeight  = TkBTreePixelsTo(textPtr, linePtr);
	pixelHeight += GetPixelsTo(textPtr, srcPtr, 1, NULL);
	pixelHeight -= distance;

	if (pixelHeight <= 0) {
	    linePtr = startLinePtr;
	    byteOffset = *overlap = 0;
	} else {
	    linePtr = TkBTreeFindPixelLine(srcPtr->tree, textPtr, pixelHeight, overlap);
	    byteOffset = FindDisplayLineOffset(textPtr, linePtr, overlap);
	}
    } else {
	DisplayInfo info;

	/*
	 * Search up line by line until we have found the start line for given distance.
	 */

	linePtr = ComputeDisplayLineInfo(textPtr, srcPtr, &info);
	SaveDisplayLines(textPtr, &info, 0);
	distance -= GetPixelsTo(textPtr, srcPtr, 1, &info);

	while (linePtr != startLinePtr && distance > 0) {
	    TkTextIndexSetToLastChar2(dstPtr, linePtr->prevPtr);
	    linePtr = ComputeDisplayLineInfo(textPtr, dstPtr, &info);
	    SaveDisplayLines(textPtr, &info, 0);
	    distance -= info.pixels;
	}

	if (distance < 0) {
	    *overlap = -distance;
	    byteOffset = FindDisplayLineOffset(textPtr, linePtr, overlap);
	} else {
	    byteOffset = *overlap = 0;
	}
    }

    TkTextIndexSetToStartOfLine2(dstPtr, linePtr);
    TkrTextIndexForwBytes(textPtr, dstPtr, byteOffset, dstPtr);
    return 1;
}
/*
 *--------------------------------------------------------------
 *
 * GetBbox --
 *
 *	Given an index, find the bounding box of the screen area occupied by
 *	the entity (character, window, image) at that index.
 *
 * Results:
 *	The byte count inside the chunk is returned if the index is on the screen.
 *	'false' means the index is not on the screen. If the return value is true,
 *	then the bounding box of the part of the index that's visible on the screen
 *	is returned to *xPtr, *yPtr, *widthPtr, and *heightPtr.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
GetBbox(
    TkText *textPtr,		/* Information about text widget. */
    const DLine *dlPtr,		/* Display line for given index. */
    const TkTextIndex *indexPtr,/* Index whose bounding box is desired. */
    int *xPtr, int *yPtr,	/* Filled with index's upper-left coordinate. */
    int *widthPtr, int *heightPtr,
				/* Filled in with index's dimensions. */
    int *isLastCharInLine,	/* Last char in display line? Can be NULL. */
    Tcl_UniChar *thisChar)	/* The character at specified position, can be NULL. Will be zero if
				 * this is not a char chunk. */
{
    TkTextDispChunkSection *sectionPtr;
    TkTextDispChunk *chunkPtr;
    unsigned byteCount;

    assert(xPtr);
    assert(yPtr);
    assert(widthPtr);
    assert(heightPtr);
    assert(dlPtr);
    assert(TkTextIndexCompare(&dlPtr->index, indexPtr) <= 0);

    /*
     * Find the chunk within the display line that contains the desired
     * index. The chunks making the display line are skipped up to but not
     * including the one crossing indexPtr. Skipping is done based on
     * a byteCount offset possibly spanning several logical lines in case
     * they are elided.
     */

    byteCount = TkTextIndexCountBytes(&dlPtr->index, indexPtr);
    sectionPtr = dlPtr->chunkPtr->sectionPtr;

    while (byteCount >= sectionPtr->numBytes) {
	byteCount -= sectionPtr->numBytes;
	if (!(sectionPtr = sectionPtr->nextPtr)) {
	    if (thisChar) { *thisChar = 0; }
	    return 0;
	}
    }

    chunkPtr = sectionPtr->chunkPtr;

    while (byteCount >= chunkPtr->numBytes) {
	byteCount -= chunkPtr->numBytes;
	if (!(chunkPtr = chunkPtr->nextPtr)) {
	    if (thisChar) { *thisChar = 0; }
	    return 0;
	}
    }

    /*
     * Call a chunk-specific function to find the horizontal range of the
     * character within the chunk, then fill in the vertical range. The
     * x-coordinate returned by bboxProc is a coordinate within a line, not a
     * coordinate on the screen. Translate it to reflect horizontal scrolling.
     */

    chunkPtr->layoutProcs->bboxProc(
	    textPtr, chunkPtr, byteCount,
	    dlPtr->y + dlPtr->spaceAbove,
	    dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow,
	    dlPtr->baseline - dlPtr->spaceAbove,
	    xPtr, yPtr, widthPtr, heightPtr);

    if (isLastCharInLine) {
	*isLastCharInLine = (byteCount == chunkPtr->numBytes - 1 && !chunkPtr->nextPtr);
    }

    if (thisChar) {
	if (IsCharChunk(chunkPtr)) {
	    const TkTextSegment *segPtr = CHAR_CHUNK_GET_SEGMENT(chunkPtr);
	    assert((int) byteCount < segPtr->size);
	    Tcl_UtfToUniChar(segPtr->body.chars + byteCount, thisChar);
	} else {
	    *thisChar = 0;
	}
    }

    return 1;
}

/*
 *--------------------------------------------------------------
 *
 * TkTextSeeCmd --
 *
 *	This function is invoked to process the "see" option for the widget
 *	command for text widgets. See the user documentation for details on
 *	what it does.
 *
 *	TODO: the current implementation does not consider that the position
 *	has to be fully visible.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

int
TkTextSeeCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    Tcl_Size objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. Someone else has already parsed this command
				 * enough to know that objv[1] is "see". */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    TkTextIndex index;
    int x, y, width, height, oneThird, delta;
    unsigned lineWidth;
    DLine *dlPtr;

    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 2, objv, "index");
	return TCL_ERROR;
    }
    if (!TkTextGetIndexFromObj(interp, textPtr, objv[2], &index)) {
	return TCL_ERROR;
    }
    if (TkTextIsDeadPeer(textPtr)) {
	return TCL_OK;
    }

    /*
     * If the specified position is the extra line at the end of the text,
     * round it back to the last real line.
     */

    if (TkTextIndexGetLine(&index) == TkBTreeGetLastLine(textPtr)) {
	TkTextIndexSetToLastChar2(&index, TkTextIndexGetLine(&index)->prevPtr);
    }

    /*
     * First get the desired position into the vertical range of the window.
     */

    TkTextSetYView(textPtr, &index, TK_TEXT_PICKPLACE);

    /*
     * Now make sure that the character is in view horizontally.
     */

    if (dInfoPtr->flags & DINFO_OUT_OF_DATE) {
	UpdateDisplayInfo(textPtr);
    }

    assert(dInfoPtr->maxX >= dInfoPtr->x);
    lineWidth = dInfoPtr->maxX - dInfoPtr->x;

    if (dInfoPtr->maxLength < lineWidth) {
	return TCL_OK;
    }

    /*
     * Take into account that the desired index is past the visible text.
     * It's also possible that the widget is not yet mapped.
     */

    if (!(dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, &index))
	    || TkTextIndexCompare(&dInfoPtr->dLinePtr->index, &index) > 0) {
	return TCL_OK;
    }

    if (GetBbox(textPtr, dlPtr, &index, &x, &y, &width, &height, NULL, NULL)) {
	delta = x - dInfoPtr->curXPixelOffset;
	oneThird = lineWidth/3;
	if (delta < 0) {
	    if (delta < -oneThird) {
		dInfoPtr->newXPixelOffset = x - lineWidth/2;
	    } else {
		dInfoPtr->newXPixelOffset += delta;
	    }
	} else {
	    delta -= lineWidth - width;
	    if (delta <= 0) {
		return TCL_OK;
	    }
	    if (delta > oneThird) {
		dInfoPtr->newXPixelOffset = x - lineWidth/2;
	    } else {
		dInfoPtr->newXPixelOffset += delta;
	    }
	}
    }

    dInfoPtr->flags |= DINFO_OUT_OF_DATE;
    DisplayTextWhenIdle(textPtr);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TkrTextXviewCmd --
 *
 *	This function is invoked to process the "xview" option for the 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.
 *
 *--------------------------------------------------------------
 */

int
TkrTextXviewCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    Tcl_Size objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. Someone else has already parsed this command
				 * enough to know that objv[1] is "xview". */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    int count;
    double fraction;

    if (dInfoPtr->flags & DINFO_OUT_OF_DATE) {
	UpdateDisplayInfo(textPtr);
    }

    if (objc == 2) {
	GetXView(interp, textPtr, 0);
	return TCL_OK;
    }

    switch (TextGetScrollInfoObj(interp, textPtr, objc, objv, &fraction, &count)) {
    case SCROLL_ERROR:
	return TCL_ERROR;
    case SCROLL_MOVETO:
	dInfoPtr->newXPixelOffset = (int) (MIN(1.0, MAX(0.0, fraction))*dInfoPtr->maxLength + 0.5);
	break;
    case SCROLL_PAGES: {
	int pixelsPerPage;

	pixelsPerPage = dInfoPtr->maxX - dInfoPtr->x - 2*textPtr->charWidth;
	dInfoPtr->newXPixelOffset += count*MAX(1, pixelsPerPage);
	break;
    }
    case SCROLL_UNITS:
	dInfoPtr->newXPixelOffset += count*textPtr->charWidth;
	break;
    case SCROLL_PIXELS:
	dInfoPtr->newXPixelOffset += count;
	break;
    }

    dInfoPtr->flags |= DINFO_OUT_OF_DATE;
    DisplayTextWhenIdle(textPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * YScrollByPixels --
 *
 *	This function is called to scroll a text widget up or down by a given
 *	number of pixels.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The view in textPtr's window changes to reflect the value of "offset".
 *
 *----------------------------------------------------------------------
 */

static void
YScrollByPixels(
    TkText *textPtr,	/* Widget to scroll. */
    int offset)		/* Amount by which to scroll, in pixels. Positive means that
			 * information later in text becomes visible, negative means
			 * that information earlier in the text becomes visible. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    if (offset < 0) {
	/*
	 * Now we want to measure up this number of pixels from the top of the
	 * screen. But the top line may not be totally visible.
	 */

	offset -= CalculateDisplayLineHeight(textPtr, &textPtr->topIndex, NULL);
	offset += dInfoPtr->topPixelOffset;

	if (!MeasureUp(textPtr, &textPtr->topIndex, -offset,
		&textPtr->topIndex, &dInfoPtr->newTopPixelOffset)) {
	    return; /* already at top, we cannot scroll */
	}
    } else if (offset > 0) {
	/*
	 * Scrolling down by pixels. Layout lines starting at the top index
	 * and count through the desired vertical distance.
	 */

	offset += dInfoPtr->topPixelOffset;
	if (!MeasureDown(textPtr, &textPtr->topIndex, offset, &dInfoPtr->newTopPixelOffset, 1)) {
	    return; /* already at end, we cannot scroll */
	}
	TkTextIndexToByteIndex(&textPtr->topIndex);
    } else {
	/*
	 * offset = 0, so no scrolling required.
	 */
	return;
    }

    assert(dInfoPtr->newTopPixelOffset < CalculateDisplayLineHeight(textPtr, &textPtr->topIndex, NULL));

    DisplayTextWhenIdle(textPtr);
    dInfoPtr->flags |= DINFO_OUT_OF_DATE|REPICK_NEEDED;
}

/*
 *----------------------------------------------------------------------
 *
 * YScrollByLines --
 *
 *	This function is called to scroll a text widget up or down by a given
 *	number of lines.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The view in textPtr's window changes to reflect the value of "offset".
 *
 *----------------------------------------------------------------------
 */

static int
ScrollUp(
    TkText *textPtr,	/* Widget to scroll. */
    unsigned offset)	/* Amount by which to scroll, in display lines. */
{
    TkTextLine *linePtr;
    unsigned byteOffset;
    DisplayInfo info;
    int upToDate;

    assert(offset > 0);

    /*
     * Scrolling up, to show earlier information in the text.
     */

    if (AlreadyAtTop(textPtr)) {
	return 0;
    }

    if (TkTextIndexIsStartOfText(&textPtr->dInfoPtr->dLinePtr->index)) {
	textPtr->dInfoPtr->newTopPixelOffset = 0;
	return 1;
    }

    upToDate = TestIfLinesUpToDate(&textPtr->topIndex);
    linePtr = ComputeDisplayLineInfo(textPtr, &textPtr->topIndex, &info);

    if (upToDate) {
	const TkTextDispLineInfo *dispLineInfo;

	assert(!info.dLinePtr);

	/*
	 * The display line information is complete for the required range, so
	 * use it for finding the requested display line.
	 */

	linePtr = TkBTreePrevDisplayLine(textPtr, linePtr, &info.displayLineNo, offset);
	dispLineInfo = TkBTreeLinePixelInfo(textPtr, linePtr)->dispLineInfo;
	byteOffset = dispLineInfo ? dispLineInfo->entry[info.displayLineNo].byteOffset : 0;
    } else {
	TkTextLine *firstLinePtr;
	TkTextIndex index;

	/*
	 * The display line information is incomplete, so we do a search line by line.
	 * The computed display lines will be saved for displaying.
	 */

	firstLinePtr = TkBTreeGetStartLine(textPtr);
	index = textPtr->topIndex;
	SaveDisplayLines(textPtr, &info, 0);
	info.numDispLines = info.displayLineNo + 1;

	while (1) {
	    if (info.numDispLines > offset) {
		byteOffset = (info.entry - offset)->byteOffset;
		break;
	    }
	    offset -= info.numDispLines;
	    if (linePtr == firstLinePtr) {
		byteOffset = 0;
		break;
	    }
	    TkTextIndexSetToLastChar2(&index, linePtr->prevPtr);
	    linePtr = ComputeDisplayLineInfo(textPtr, &index, &info);
	    SaveDisplayLines(textPtr, &info, 0);
	    assert(!TkBTreeLinePixelInfo(textPtr, linePtr)->dispLineInfo
		    || info.entry == TkBTreeLinePixelInfo(textPtr, linePtr)->dispLineInfo->entry +
			    info.numDispLines - 1);
	}
    }

    TkTextIndexSetToStartOfLine2(&textPtr->topIndex, linePtr);
    TkrTextIndexForwBytes(textPtr, &textPtr->topIndex, byteOffset, &textPtr->topIndex);

    return 1;
}

static int
ScrollDown(
    TkText *textPtr,	/* Widget to scroll. */
    unsigned offset)	/* Amount by which to scroll, in display lines. */
{
    TkTextLine *linePtr;
    unsigned byteOffset;
    DisplayInfo info;
    int upToDate;

    assert(offset > 0);

    /*
     * Scrolling down, to show later information in the text.
     */

    if (AlreadyAtBottom(textPtr)) {
	return 0;
    }

    upToDate = TkRangeListIsEmpty(textPtr->dInfoPtr->lineMetricUpdateRanges);
    linePtr = ComputeDisplayLineInfo(textPtr, &textPtr->topIndex, &info);

    if (upToDate) {
	const TkTextDispLineInfo *dispLineInfo;

	assert(!info.dLinePtr);

	/*
	 * The display line information is complete for the required range, so
	 * use it for finding the requested display line.
	 */

	linePtr = TkBTreeNextDisplayLine(textPtr, linePtr, &info.displayLineNo, offset);
	dispLineInfo = TkBTreeLinePixelInfo(textPtr, linePtr)->dispLineInfo;
	byteOffset = dispLineInfo ? dispLineInfo->entry[info.displayLineNo].byteOffset : 0;
    } else {
	TkTextLine *lastLinePtr;

	/*
	 * The display line information is incomplete, so we do a search line by line.
	 * The computed display lines will be saved for displaying.
	 */

	lastLinePtr = TkBTreeGetLastLine(textPtr);
	ComputeMissingMetric(textPtr, &info, THRESHOLD_LINE_OFFSET, offset);
	SaveDisplayLines(textPtr, &info, 1);
	info.numDispLines -= info.displayLineNo;

	while (1) {
	    if (info.numDispLines == offset) {
		byteOffset = 0;
		linePtr = linePtr->nextPtr;
		break;
	    }
	    if (info.numDispLines > offset) {
		byteOffset = (info.entry + offset)->byteOffset;
		break;
	    }
	    offset -= info.numDispLines;
	    if (TkTextIndexGetLine(&info.index) == lastLinePtr) {
		byteOffset = (info.entry + info.numDispLines - 1)->byteOffset;
		break;
	    }
	    linePtr = ComputeDisplayLineInfo(textPtr, &info.index, &info);
	    ComputeMissingMetric(textPtr, &info, THRESHOLD_LINE_OFFSET, offset);
	    SaveDisplayLines(textPtr, &info, 1);
	}
    }

    TkTextIndexSetToStartOfLine2(&textPtr->topIndex, linePtr);
    TkrTextIndexForwBytes(textPtr, &textPtr->topIndex, byteOffset, &textPtr->topIndex);
    return 1;
}

static void
YScrollByLines(
    TkText *textPtr,	/* Widget to scroll. */
    int offset)		/* Amount by which to scroll, in display lines. Positive means
			 * that information later in text becomes visible, negative
			 * means that information earlier in the text becomes visible. */
{
    assert(textPtr);

    if (offset < 0) {
	if (!ScrollUp(textPtr, -offset)) {
	    return;
	}
    } else if (offset > 0) {
	if (!ScrollDown(textPtr, offset)) {
	    return;
	}
    } else {
	return;
    }

    DisplayTextWhenIdle(textPtr);
    textPtr->dInfoPtr->flags |= DINFO_OUT_OF_DATE|REPICK_NEEDED;
}

/*
 *--------------------------------------------------------------
 *
 * TkTextYviewCmd --
 *
 *	This function is invoked to process the "yview" option for the 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
MakePixelIndex(
    TkText *textPtr,		/* The text widget. */
    unsigned pixelIndex,	/* Pixel-index of desired line (0 means first pixel of first
				 * line of text). */
    TkTextIndex *indexPtr)	/* Structure to fill in. */
{
    TkTextLine *linePtr;
    TkTextLine *lastLinePtr;
    int32_t pixelOffset;

    assert(!TkTextIsDeadPeer(textPtr));

    TkTextIndexClear(indexPtr, textPtr);
    linePtr = TkBTreeFindPixelLine(textPtr->sharedTextPtr->tree, textPtr, pixelIndex, &pixelOffset);
    lastLinePtr = TkBTreeGetLastLine(textPtr);

    if (linePtr != lastLinePtr) {
	int byteOffset = FindDisplayLineOffset(textPtr, linePtr, &pixelOffset);
	TkTextIndexSetByteIndex2(indexPtr, linePtr, byteOffset);
    } else {
	assert(lastLinePtr->prevPtr); /* MakePixelIndex will not be called if peer is empty */
	assert(linePtr->prevPtr);
	linePtr = TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr, linePtr->prevPtr);
	TkTextIndexSetToLastChar2(indexPtr, linePtr);
	FindDisplayLineStartEnd(textPtr, indexPtr, DISP_LINE_START, DLINE_CACHE);
	pixelOffset = CalculateDisplayLineHeight(textPtr, indexPtr, NULL) - 1;
    }

    return MAX(0, pixelOffset);
}

static void
Repick(
    void *clientData)	/* Information about widget. */
{
    TkText *textPtr = (TkText *) clientData;

    if (!TkTextDecrRefCountAndTestIfDestroyed(textPtr)) {
	textPtr->dInfoPtr->flags &= ~REPICK_NEEDED;
	textPtr->dInfoPtr->currChunkPtr = NULL;
	textPtr->dInfoPtr->repickTimer = NULL;
	textPtr->dontRepick = 0;
	TkTextPickCurrent(textPtr, &textPtr->pickEvent);
    }
}

static void
DelayRepick(
    TkText *textPtr)
{
    assert(textPtr->dInfoPtr->flags & REPICK_NEEDED);

    if (textPtr->responsiveness > 0) {
	TextDInfo *dInfoPtr = textPtr->dInfoPtr;

	if (dInfoPtr->repickTimer) {
	    Tcl_DeleteTimerHandler(dInfoPtr->repickTimer);
	} else {
	    textPtr->refCount += 1;
	}
	textPtr->dontRepick = 1;
	dInfoPtr->flags &= ~REPICK_NEEDED;
	dInfoPtr->repickTimer = Tcl_CreateTimerHandler(textPtr->responsiveness, Repick, textPtr);
    }
}

int
TkTextYviewCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    Tcl_Size objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. Someone else has already parsed this command
				 * enough to know that objv[1] is "yview". */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    int pickPlace;
    int pixels, count;
    Tcl_Size switchLength;
    double fraction;
    TkTextIndex index;

    if (dInfoPtr->flags & DINFO_OUT_OF_DATE) {
	UpdateDisplayInfo(textPtr);
    }

    if (objc == 2) {
	GetYView(interp, textPtr, 0);
	return TCL_OK;
    }

    /*
     * Next, handle the old syntax: "pathName yview ?-pickplace? where"
     */

    pickPlace = 0;
    if (Tcl_GetString(objv[2])[0] == '-') {
	const char *switchStr =
		Tcl_GetStringFromObj(objv[2], &switchLength);

	if (switchLength >= 2 && strncmp(switchStr, "-pickplace", switchLength) == 0) {
	    pickPlace = 1;
	    if (objc != 4) {
		Tcl_WrongNumArgs(interp, 3, objv, "lineNum|index");
		return TCL_ERROR;
	    }
	}
    }

    if (objc == 3 || pickPlace) {
	int lineNum;

	if (Tcl_GetIntFromObj(interp, objv[2 + pickPlace], &lineNum) == TCL_OK) {
	    TkrTextMakeByteIndex(textPtr->sharedTextPtr->tree, textPtr, lineNum, 0, &index);
	    TkTextSetYView(textPtr, &index, 0);
	} else {
	    /*
	     * The argument must be a regular text index.
	     */

	    Tcl_ResetResult(interp);
	    if (!TkTextGetIndexFromObj(interp, textPtr, objv[2 + pickPlace], &index)) {
		return TCL_ERROR;
	    }
	    TkTextSetYView(textPtr, &index, pickPlace ? TK_TEXT_PICKPLACE : 0);
	}
    } else {
	/*
	 * New syntax: dispatch based on objv[2].
	 */

	switch (TextGetScrollInfoObj(interp, textPtr, objc, objv, &fraction, &count)) {
	case SCROLL_ERROR:
	    return TCL_ERROR;
	case SCROLL_MOVETO: {
	    int numPixels = TkBTreeNumPixels(textPtr);
	    int topMostPixel;

	    if (numPixels == 0 || TkTextIsDeadPeer(textPtr)) {
		/*
		 * If the window is totally empty no scrolling is needed, and the
		 * MakePixelIndex call below will fail.
		 */
		break;
	    }
	    if (fraction > 1.0) {
		fraction = 1.0;
	    } else if (fraction < 0.0) {
		fraction = 0.0;
	    }

	    /*
	     * Calculate the pixel count for the new topmost pixel in the topmost
	     * line of the window. Note that the interpretation of 'fraction' is
	     * that it counts from 0 (top pixel in buffer) to 1.0 (one pixel past
	     * the last pixel in buffer).
	     */

	    topMostPixel = MAX(0, MIN((int) (fraction*numPixels + 0.5), numPixels - 1));

	    /*
	     * This function returns the number of pixels by which the given line
	     * should overlap the top of the visible screen.
	     *
	     * This is then used to provide smooth scrolling.
	     */

	    pixels = MakePixelIndex(textPtr, topMostPixel, &index);
	    TkTextSetYView(textPtr, &index, pixels);
	    break;
	}
	case SCROLL_PAGES: {
	    /*
	     * Scroll up or down by screenfuls. Actually, use the window height
	     * minus two lines, so that there's some overlap between adjacent
	     * pages.
	     */

	    int height = dInfoPtr->maxY - dInfoPtr->y;

	    if (textPtr->lineHeight*4 >= height) {
		/*
		 * A single line is more than a quarter of the display. We choose
		 * to scroll by 3/4 of the height instead.
		 */

		pixels = 3*height/4;
		if (pixels < textPtr->lineHeight) {
		    /*
		     * But, if 3/4 of the height is actually less than a single
		     * typical character height, then scroll by the minimum of the
		     * linespace or the total height.
		     */

		    if (textPtr->lineHeight < height) {
			pixels = textPtr->lineHeight;
		    } else {
			pixels = height;
		    }
		}
		pixels *= count;
	    } else {
		pixels = (height - 2*textPtr->lineHeight)*count;
	    }
	    YScrollByPixels(textPtr, pixels);
	    break;
	}
	case SCROLL_PIXELS:
	    YScrollByPixels(textPtr, count);
	    break;
	case SCROLL_UNITS:
	    YScrollByLines(textPtr, count);
	    break;
	}
    }

    if (dInfoPtr->flags & REPICK_NEEDED) {
	DelayRepick(textPtr);
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TkTextScanCmd --
 *
 *	This function is invoked to process the "scan" option for the 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.
 *
 *--------------------------------------------------------------
 */

int
TkTextScanCmd(
    TkText *textPtr,		/* Information about text widget. */
    Tcl_Interp *interp,		/* Current interpreter. */
    Tcl_Size objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. Someone else has already parsed this command
				 * enough to know that objv[1] is "scan". */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    TkTextIndex index;
    int c, x, y, totalScroll, gain=10;
    Tcl_Size length;

    if (objc != 5 && objc != 6) {
	Tcl_WrongNumArgs(interp, 2, objv, "mark x y");
	Tcl_AppendResult(interp, " or \"", Tcl_GetString(objv[0]), " scan dragto x y ?gain?\"", (char *)NULL);
	/*
	 * Ought to be: Tcl_WrongNumArgs(interp, 2, objc, "dragto x y ?gain?");
	 */
	return TCL_ERROR;
    }
    if (Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK) {
	return TCL_ERROR;
    }
    if (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK) {
	return TCL_ERROR;
    }
    if (objc == 6 && Tcl_GetIntFromObj(interp, objv[5], &gain) != TCL_OK) {
	return TCL_ERROR;
    }
    c = Tcl_GetStringFromObj(objv[2], &length)[0];
    if (c == 'd' && strncmp(Tcl_GetString(objv[2]), "dragto", length) == 0) {
	int newX, maxX;

	/*
	 * Amplify the difference between the current position and the mark
	 * position to compute how much the view should shift, then update the
	 * mark position to correspond to the new view. If we run off the edge
	 * of the text, reset the mark point so that the current position
	 * continues to correspond to the edge of the window. This means that
	 * the picture will start dragging as soon as the mouse reverses
	 * direction (without this reset, might have to slide mouse a long
	 * ways back before the picture starts moving again).
	 */

	newX = dInfoPtr->scanMarkXPixel + gain*(dInfoPtr->scanMarkX - x);
	maxX = 1 + dInfoPtr->maxLength - (dInfoPtr->maxX - dInfoPtr->x);
	if (newX < 0) {
	    newX = 0;
	    dInfoPtr->scanMarkXPixel = 0;
	    dInfoPtr->scanMarkX = x;
	} else if (newX > maxX) {
	    newX = maxX;
	    dInfoPtr->scanMarkXPixel = maxX;
	    dInfoPtr->scanMarkX = x;
	}
	dInfoPtr->newXPixelOffset = newX;

	totalScroll = gain*(dInfoPtr->scanMarkY - y);
	if (totalScroll != dInfoPtr->scanTotalYScroll) {
	    index = textPtr->topIndex;
	    YScrollByPixels(textPtr, totalScroll - dInfoPtr->scanTotalYScroll);
	    dInfoPtr->scanTotalYScroll = totalScroll;
	    if (TkTextIndexIsEqual(&index, &textPtr->topIndex)) {
		dInfoPtr->scanTotalYScroll = 0;
		dInfoPtr->scanMarkY = y;
	    }
	}
	dInfoPtr->flags |= DINFO_OUT_OF_DATE;
	DisplayTextWhenIdle(textPtr);
    } else if (c == 'm' && strncmp(Tcl_GetString(objv[2]), "mark", length) == 0) {
	dInfoPtr->scanMarkXPixel = dInfoPtr->newXPixelOffset;
	dInfoPtr->scanMarkX = x;
	dInfoPtr->scanTotalYScroll = 0;
	dInfoPtr->scanMarkY = y;
    } else {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"bad scan option \"%s\": must be dragto or mark", Tcl_GetString(objv[2])));
	Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "INDEX", "scan option", Tcl_GetString(objv[2]), (char *)NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetXView --
 *
 *	This function computes the fractions that indicate what's visible in a
 *	text window and, optionally, evaluates a Tcl script to report them to
 *	the text's associated scrollbar.
 *
 * Results:
 *	If report is zero, then the interp's result is filled in with two real
 *	numbers separated by a space, giving the position of the left and
 *	right edges of the window as fractions from 0 to 1, where 0 means the
 *	left edge of the text and 1 means the right edge. If report is
 *	non-zero, then the interp's result isn't modified directly, but
 *	instead a script is evaluated in interp to report the new horizontal
 *	scroll position to the scrollbar (if the scroll position hasn't
 *	changed then no script is invoked).
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
GetXView(
    Tcl_Interp *interp,		/* If "report" is FALSE, string describing visible range gets stored
				 * in the interp's result. */
    const TkText *textPtr,		/* Information about text widget. */
    int report)		/* 'true' means report info to scrollbar if it has changed. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    double first, last;
    int xMin, xMax;
    int code;
    Tcl_Obj *listObj;

    if (dInfoPtr->maxLength > 0) {
	first = ((double) dInfoPtr->curXPixelOffset)/dInfoPtr->maxLength;
	last = ((double) (dInfoPtr->curXPixelOffset + dInfoPtr->maxX - dInfoPtr->x))/dInfoPtr->maxLength;
	if (last > 1.0) {
	    last = 1.0;
	}
	xMin = dInfoPtr->curXPixelOffset;
	xMax = xMin + dInfoPtr->maxX - dInfoPtr->x;
    } else {
	first = 0.0;
	last = 1.0;
	xMin = xMax = dInfoPtr->curXPixelOffset;
    }
    if (!report) {
	listObj = Tcl_NewObj();
	Tcl_ListObjAppendElement(interp, listObj, Tcl_NewDoubleObj(first));
	Tcl_ListObjAppendElement(interp, listObj, Tcl_NewDoubleObj(last));
	Tcl_SetObjResult(interp, listObj);
	return;
    }
    if (FP_EQUAL_SCALE(first, dInfoPtr->xScrollFirst, dInfoPtr->maxLength) &&
	    FP_EQUAL_SCALE(last, dInfoPtr->xScrollLast, dInfoPtr->maxLength)) {
	return;
    }

    dInfoPtr->xScrollFirst = first;
    dInfoPtr->xScrollLast = last;
    dInfoPtr->curPixelPos.xFirst = xMin;
    dInfoPtr->curPixelPos.xLast = xMax;

    if (textPtr->xScrollCmdObj) {
	char buf1[TCL_DOUBLE_SPACE + 1];
	char buf2[TCL_DOUBLE_SPACE + 1];
	Tcl_DString buf;

	buf1[0] = ' ';
	buf2[0] = ' ';
	Tcl_PrintDouble(NULL, first, buf1 + 1);
	Tcl_PrintDouble(NULL, last, buf2 + 1);
	Tcl_DStringInit(&buf);
	Tcl_DStringAppend(&buf, Tcl_GetString(textPtr->xScrollCmdObj), TCL_INDEX_NONE);
	Tcl_DStringAppend(&buf, buf1, TCL_INDEX_NONE);
	Tcl_DStringAppend(&buf, buf2, TCL_INDEX_NONE);
	code = Tcl_EvalEx(interp, Tcl_DStringValue(&buf), TCL_INDEX_NONE, 0);
	Tcl_DStringFree(&buf);
	if (code != TCL_OK) {
	    Tcl_AddErrorInfo(interp,
		    "\n    (horizontal scrolling command executed by text)");
	    Tcl_BackgroundException(interp, code);
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetYPixelCount --
 *
 *	How many pixels are there between the absolute top of the widget and
 *	the top of the given DLine.
 *
 *	While this function will work for any valid DLine, it is only ever
 *	called when dlPtr is the first display line in the widget (by
 *	'GetYView'). This means that usually this function is a very quick
 *	calculation, since it can use the pre-calculated linked-list of DLines
 *	for height information.
 *
 *	The only situation where this breaks down is if dlPtr's logical line
 *	wraps enough times to fill the text widget's current view - in this
 *	case we won't have enough dlPtrs in the linked list to be able to
 *	subtract off what we want.
 *
 * Results:
 *	The number of pixels.
 *
 *	This value has a valid range between '0' (the very top of the widget)
 *	and the number of pixels in the total widget minus the pixel-height of
 *	the last line.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static unsigned
GetYPixelCount(
    TkText *textPtr,	/* Information about text widget. */
    DLine *dlPtr)	/* Information about the layout of a given index. */
{
    TkTextLine *linePtr;
    DisplayInfo info;

    linePtr = ComputeDisplayLineInfo(textPtr, &dlPtr->index, &info);
    FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
    return TkBTreePixelsTo(textPtr, linePtr) + info.entry->pixels - info.entry->height;
}

/*
 *----------------------------------------------------------------------
 *
 * GetYView --
 *
 *	This function computes the fractions that indicate what's visible in a
 *	text window and, optionally, evaluates a Tcl script to report them to
 *	the text's associated scrollbar.
 *
 * Results:
 *	If report is zero, then the interp's result is filled in with two real
 *	numbers separated by a space, giving the position of the top and
 *	bottom of the window as fractions from 0 to 1, where 0 means the
 *	beginning of the text and 1 means the end. If report is non-zero, then
 *	the interp's result isn't modified directly, but a script is evaluated
 *	in interp to report the new scroll position to the scrollbar (if the
 *	scroll position hasn't changed then no script is invoked).
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
GetYView(
    Tcl_Interp *interp,		/* If "report" is 'false', string describing visible range gets
				 * stored in the interp's result. */
    TkText *textPtr,		/* Information about text widget. */
    int report)		/* 'true' means report info to scrollbar if it has changed. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    double first, last;
    DLine *dlPtr;
    int totalPixels, code, count;
    int yMin, yMax;
    Tcl_Obj *listObj;

    dlPtr = dInfoPtr->dLinePtr;

    if (!dlPtr) {
	return;
    }

    totalPixels = TkBTreeNumPixels(textPtr);

    if (totalPixels == 0) {
	first = 0.0;
	last = 1.0;
	yMin = yMax = dInfoPtr->topPixelOffset;
    } else {
	/*
	 * Get the pixel count for the first visible pixel of the first
	 * visible line. If the first visible line is only partially visible,
	 * then we use 'topPixelOffset' to get the difference.
	 */

	count = yMin = GetYPixelCount(textPtr, dlPtr);
	first = (count + dInfoPtr->topPixelOffset) / (double) totalPixels;

	/*
	 * Add on the total number of visible pixels to get the count to one
	 * pixel _past_ the last visible pixel. This is how the 'yview'
	 * command is documented, and also explains why we are dividing by
	 * 'totalPixels' and not 'totalPixels-1'.
	 */

	while (dlPtr) {
	    int extra;

	    count += dlPtr->height;
	    extra = dlPtr->y + dlPtr->height - dInfoPtr->maxY;
	    if (extra > 0) {
		/*
		 * This much of the last line is not visible, so don't count
		 * these pixels. Since we've reached the bottom of the window,
		 * we break out of the loop.
		 */

		count -= extra;
		break;
	    }
	    dlPtr = dlPtr->nextPtr;
	}

	if (count > totalPixels) {
	    /*
	     * It can be possible, if we do not update each line's pixelHeight
	     * cache when we lay out individual DLines that the count
	     * generated here is more up-to-date than that maintained by the
	     * BTree. In such a case, the best we can do here is to fix up
	     * 'count' and continue, which might result in small, temporary
	     * perturbations to the size of the scrollbar. This is basically
	     * harmless, but in a perfect world we would not have this
	     * problem.
	     *
	     * For debugging purposes, if anyone wishes to improve the text
	     * widget further, the following 'panic' can be activated. In
	     * principle it should be possible to ensure the BTree is always
	     * at least as up to date as the display, so in the future we
	     * might be able to leave the 'panic' in permanently when we
	     * believe we have resolved the cache synchronisation issue.
	     *
	     * However, to achieve that goal would, I think, require a fairly
	     * substantial refactorisation of the code in this file so that
	     * there is much more obvious and explicit coordination between
	     * calls to LayoutDLine and updating of each TkTextLine's
	     * pixelHeight. The complicated bit is that LayoutDLine deals with
	     * individual display lines, but pixelHeight is for a logical
	     * line.
	     */

#if 0
	    Tcl_Panic("Counted more pixels (%d) than expected (%d) total "
		    "pixels in text widget scroll bar calculation.", count,
		    totalPixels);
#elif 0 /* TODO: still happens sometimes, why? */
	    fprintf(stderr, "warning: Counted more pixels (%d) than expected (%d)\n",
		    count, totalPixels);
#endif

	    count = totalPixels;
	}

	yMax = count;
	last = ((double) count)/((double) totalPixels);
    }

    if (!report) {
	listObj = Tcl_NewObj();
	Tcl_ListObjAppendElement(interp, listObj, Tcl_NewDoubleObj(first));
	Tcl_ListObjAppendElement(interp, listObj, Tcl_NewDoubleObj(last));
	Tcl_SetObjResult(interp, listObj);
    } else {
	dInfoPtr->curPixelPos.yFirst = yMin + dInfoPtr->topPixelOffset;
	dInfoPtr->curPixelPos.yLast = yMax + dInfoPtr->topPixelOffset;

	if (!FP_EQUAL_SCALE(first, dInfoPtr->yScrollFirst, totalPixels) ||
		!FP_EQUAL_SCALE(last, dInfoPtr->yScrollLast, totalPixels)) {
	    dInfoPtr->yScrollFirst = first;
	    dInfoPtr->yScrollLast = last;

	    if (textPtr->yScrollCmdObj) {
		char buf1[TCL_DOUBLE_SPACE + 1];
		char buf2[TCL_DOUBLE_SPACE + 1];
		Tcl_DString buf;

		buf1[0] = ' ';
		buf2[0] = ' ';
		Tcl_PrintDouble(NULL, first, buf1 + 1);
		Tcl_PrintDouble(NULL, last, buf2 + 1);
		Tcl_DStringInit(&buf);
		Tcl_DStringAppend(&buf, Tcl_GetString(textPtr->yScrollCmdObj), TCL_INDEX_NONE);
		Tcl_DStringAppend(&buf, buf1, TCL_INDEX_NONE);
		Tcl_DStringAppend(&buf, buf2, TCL_INDEX_NONE);
		code = Tcl_EvalEx(interp, Tcl_DStringValue(&buf), TCL_INDEX_NONE, 0);
		Tcl_DStringFree(&buf);
		if (code != TCL_OK) {
		    Tcl_AddErrorInfo(interp,
			    "\n    (vertical scrolling command executed by text)");
		    Tcl_BackgroundException(interp, code);
		}
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * AsyncUpdateYScrollbar --
 *
 *	This function is called to update the vertical scrollbar asychronously
 *	as the pixel height calculations progress for lines in the widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	See 'GetYView'. In particular the scrollbar position and size may be
 *	changed.
 *
 *----------------------------------------------------------------------
 */

static void
AsyncUpdateYScrollbar(
    void *clientData)	/* Information about widget. */
{
    TkText *textPtr = (TkText *)clientData;
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;

    dInfoPtr->scrollbarTimer = NULL;

    if (!TkTextDecrRefCountAndTestIfDestroyed(textPtr) && !dInfoPtr->insideLineMetricUpdate) {
	GetYView(textPtr->interp, textPtr, 1);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * FindCachedDLine --
 *
 *	This function is called to find the cached line for given text
 *	index.
 *
 * Results:
 *	The return value is a pointer to the cached DLine found, or NULL
 *	if not available.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static DLine *
FindCachedDLine(
    TkText *textPtr,
    const TkTextIndex *indexPtr)
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    DLine *dlPtr;

    for (dlPtr = dInfoPtr->cachedDLinePtr; dlPtr; dlPtr = dlPtr->nextPtr) {
	if (TkBTreeLinePixelInfo(textPtr, TkTextIndexGetLine(&dlPtr->index))->epoch
		    == dInfoPtr->lineMetricUpdateEpoch
		&& TkTextIndexCompare(indexPtr, &dlPtr->index) >= 0) {
	    TkTextIndex index = dlPtr->index;

	    TkrTextIndexForwBytes(textPtr, &index, dlPtr->byteCount, &index);
	    if (TkTextIndexCompare(indexPtr, &index) < 0) {
		DEBUG(stats.numHits++);
		return dlPtr;
	    }
	}
    }

    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * FindDLine --
 *
 *	This function is called to find the DLine corresponding to a given
 *	text index.
 *
 * Results:
 *	The return value is a pointer to the first DLine found in the list
 *	headed by dlPtr that displays information at or after the specified
 *	position. If there is no such line in the list then NULL is returned.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static DLine *
FindDLine(
    TkText *textPtr,		/* Widget record for text widget. */
    DLine *dlPtr,		/* Pointer to first in list of DLines to search. */
    const TkTextIndex *indexPtr)/* Index of desired character. */
{
    DLine *lastDlPtr;

    if (!dlPtr) {
	return NULL;
    }

    if (TkTextIndexGetLineNumber(indexPtr, NULL) < TkTextIndexGetLineNumber(&dlPtr->index, NULL)) {
	/*
	 * The first display line is already past the desired line.
	 */
	return dlPtr;
    }

    /*
     * The display line containing the desired index is such that the index
     * of the first character of this display line is at or before the
     * desired index, and the index of the first character of the next
     * display line is after the desired index.
     */

    while (TkTextIndexCompare(&dlPtr->index, indexPtr) < 0) {
	lastDlPtr = dlPtr;
	dlPtr = dlPtr->nextPtr;
	if (!dlPtr) {
	    TkTextIndex index2;
	    /*
	     * We're past the last display line, either because the desired
	     * index lies past the visible text, or because the desired index
	     * is on the last display line showing the last logical line.
	     */
	    index2 = lastDlPtr->index;
	    TkrTextIndexForwBytes(textPtr, &index2, lastDlPtr->byteCount, &index2);
	    if (TkTextIndexCompare(&index2, indexPtr) > 0) {
		/*
		 * The desired index is on the last display line, hence return this display line.
		 */
		dlPtr = lastDlPtr;
		break;
	    } else {
		/*
		 * The desired index is past the visible text. There is no display line
		 * displaying something at the desired index, hence return NULL.
		 */
		return NULL;
	    }
	}
	if (TkTextIndexCompare(&dlPtr->index, indexPtr) > 0) {
	    /*
	     * If we're here then we would normally expect that:
	     *   lastDlPtr->index <= indexPtr < dlPtr->index
	     * i.e. we have found the searched display line being dlPtr.
	     * However it is possible that some DLines were unlinked
	     * previously, leading to a situation where going through
	     * the list of display lines skips display lines that did
	     * exist just a moment ago.
	     */

	    TkTextIndex index;
	    TkrTextIndexForwBytes(textPtr, &lastDlPtr->index, lastDlPtr->byteCount, &index);
	    if (TkTextIndexCompare(&index, indexPtr) > 0) {
		/*
		 * Confirmed: lastDlPtr->index <= indexPtr < dlPtr->index
		 */
		dlPtr = lastDlPtr;
	    } else {
		/*
		 * The last (rightmost) index shown by dlPtrPrev is still before the desired
		 * index. This may be because there was previously a display line between
		 * dlPtrPrev and dlPtr and this display line has been unlinked.
		 */
	    }
	    break;
	}
    }

    return dlPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetFirstXPixel --
 *
 *	Get first x-pixel position in current widget.
 *
 * Results:
 *	Returns first x-pixel.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextGetFirstXPixel(
    const TkText *textPtr)	/* Widget record for text widget. */
{
    assert(textPtr);
    return textPtr->dInfoPtr->x;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetFirstYPixel --
 *
 *	Get first y-pixel position in current widget.
 *
 * Results:
 *	Returns first y-pixel.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextGetFirstYPixel(
    const TkText *textPtr)	/* Widget record for text widget. */
{
    assert(textPtr);
    return textPtr->dInfoPtr->y;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetLastXPixel --
 *
 *	Get last x-pixel position in current widget.
 *
 * Results:
 *	Returns last x-pixel.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextGetLastXPixel(
    const TkText *textPtr)	/* Widget record for text widget. */
{
    assert(textPtr);
    return textPtr->dInfoPtr->maxX - 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextGetLastYPixel --
 *
 *	Get last y-pixel position in current widget.
 *
 * Results:
 *	Returns last y-pixel.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextGetLastYPixel(
    const TkText *textPtr)	/* Widget record for text widget. */
{
    assert(textPtr);
    return textPtr->dInfoPtr->maxY - 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextCountVisibleImages --
 *
 *	Return the number of visible embedded images.
 *
 * Results:
 *	Returns number of visible embedded images.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

unsigned
TkTextCountVisibleImages(
    const TkText *textPtr)	/* Widget record for text widget. */
{
    assert(textPtr);
    return textPtr->dInfoPtr->countImages;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextCountVisibleWindows --
 *
 *	Return the number of visible embedded windows.
 *
 * Results:
 *	Returns number of visible embedded windows.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

unsigned
TkTextCountVisibleWindows(
    const TkText *textPtr)	/* Widget record for text widget. */
{
    assert(textPtr);
    return textPtr->dInfoPtr->countWindows;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextPixelIndex --
 *
 *	Given an (x,y) coordinate on the screen, find the location of the
 *	character closest to that location.
 *
 * Results:
 *	The index at *indexPtr is modified to refer to the character on the
 *	display that is closest to (x,y). It returns the affected display
 *	chunk.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static TkTextDispChunk *
FindNextTagInfoChunk(
    TkTextDispChunk *chunkPtr)
{
    assert(chunkPtr);

    for ( ; chunkPtr->nextPtr; chunkPtr = chunkPtr->nextPtr) {
	switch (chunkPtr->layoutProcs->type) {
	case TEXT_DISP_CHAR:   /* fallthru */
	case TEXT_DISP_HYPHEN: /* fallthru */
	case TEXT_DISP_IMAGE:  /* fallthru */
	case TEXT_DISP_WINDOW: return chunkPtr;
	case TEXT_DISP_ELIDED: /* fallthru */
	case TEXT_DISP_CURSOR: break;
	}
    }

    return chunkPtr;
}

const TkTextDispChunk *
TkTextPixelIndex(
    TkText *textPtr,		/* Widget record for text widget. */
    int x, int y,		/* Pixel coordinates of point in widget's window. */
    TkTextIndex *indexPtr,	/* This index gets filled in with the index of the character
				 * nearest to (x,y). */
    int *nearest)		/* If non-NULL then gets set to false if (x,y) is actually over the
				 * returned index, and true if it is just nearby (e.g. if x,y is on
				 * the border of the widget). */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    DLine *dlPtr = NULL;
    DLine *currDLinePtr;
    TkTextDispChunk *currChunkPtr;
    int nearby = 0;
    Tcl_Size epoch;

    /*
     * Make sure that all of the layout information about what's displayed
     * where on the screen is up-to-date.
     */

    if (dInfoPtr->flags & DINFO_OUT_OF_DATE) {
	UpdateDisplayInfo(textPtr);
    }

    /*
     * If the coordinates are above the top of the window, then adjust them to
     * refer to the upper-right corner of the window. If they're off to one
     * side or the other, then adjust to the closest side.
     */

    if (y < dInfoPtr->y) {
	y = dInfoPtr->y;
	x = dInfoPtr->x; /* we want a line-based result, not a geometrical result */
	nearby = 1;
    }
    if (x >= dInfoPtr->maxX) {
	x = dInfoPtr->maxX - 1;
	nearby = 1;
    }
    if (x < dInfoPtr->x) {
	x = dInfoPtr->x;
	nearby = 1;
    }

    /*
     * Find the display line containing the desired y-coordinate.
     */

    if (!dInfoPtr->dLinePtr) {
	if (nearest) {
	    *nearest = 1;
	}
	*indexPtr = textPtr->topIndex;
	return NULL;
    }

    epoch = TkBTreeEpoch(textPtr->sharedTextPtr->tree);
    currChunkPtr = dInfoPtr->currChunkPtr;

    if (currChunkPtr && dInfoPtr->currChunkIndex.stateEpoch == epoch) {
	currDLinePtr = dInfoPtr->currDLinePtr;

	assert(currChunkPtr->stylePtr); /* otherwise the chunk has been expired */

	if (currDLinePtr->y <= y && y < currDLinePtr->y + currDLinePtr->height) {
	    int rx = x - dInfoPtr->x + dInfoPtr->curXPixelOffset;

	    if (currChunkPtr->x <= rx && rx < currChunkPtr->x + currChunkPtr->width) {
		/*
		 * We have luck, it's inside the cache.
		 */

		*indexPtr = dInfoPtr->currChunkIndex;
		DLineIndexOfX(textPtr, currChunkPtr, x, indexPtr);
		if (nearest) {
		    *nearest = nearby;
		}
		return FindNextTagInfoChunk(currChunkPtr);
	    }

	    dlPtr = currDLinePtr;
	}
    }

    if (!dlPtr) {
	DLine *validDlPtr = dInfoPtr->dLinePtr;

	for (dlPtr = validDlPtr; y >= dlPtr->y + dlPtr->height; dlPtr = dlPtr->nextPtr) {
	    if (dlPtr->chunkPtr) {
		validDlPtr = dlPtr;
	    }
	    if (!dlPtr->nextPtr) {
		/*
		 * Y-coordinate is off the bottom of the displayed text. Use the
		 * last character on the last line.
		 */

		if (nearest) {
		    *nearest = 1;
		}
		dInfoPtr->currChunkPtr = NULL;
		*indexPtr = dlPtr->index;
		assert(dlPtr->byteCount > 0);
		TkrTextIndexForwBytes(textPtr, indexPtr, dlPtr->byteCount - 1, indexPtr);
		return NULL;
	    }
	}
	if (!dlPtr->chunkPtr) {
	    dlPtr = validDlPtr;
	}
    }

    currChunkPtr = DLineChunkOfX(textPtr, dlPtr, x, indexPtr, &nearby);

    if (nearest) {
	*nearest = nearby;
    }

    if (!nearby) {
	/*
	 * Cache the result.
	 */

	dInfoPtr->currChunkIndex = *indexPtr;
	TkTextIndexSetEpoch(&dInfoPtr->currChunkIndex, epoch); /* price it as actual */
	dInfoPtr->currChunkPtr = currChunkPtr;
	dInfoPtr->currDLinePtr = dlPtr;
    } else {
	dInfoPtr->currChunkPtr = NULL;
    }

    DLineIndexOfX(textPtr, currChunkPtr, x, indexPtr);
    return FindNextTagInfoChunk(currChunkPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * DLineIndexOfX --
 *
 *	Given an x coordinate in a display line, increase the byte position
 *	of the index according to the character closest to that location.
 *
 *	Together with DLineChunkOfX this is effectively the opposite of
 *	DLineXOfIndex.
 *
 *	Note: use DLineChunkOfX for the computation of the chunk.
 *
 * Results:
 *	The index at *indexPtr is modified to refer to the character on the
 *	display line that is closest to x.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
DLineIndexOfX(
    TkText *textPtr,		/* Widget record for text widget. */
    TkTextDispChunk *chunkPtr,	/* Chunk which contains the character. */
    int x,			/* Pixel x coordinate of point in widget's window. */
    TkTextIndex *indexPtr)	/* This byte offset of this index will be increased according
				 * to the character position. */
{
    /*
     * If the chunk has more than one byte in it, ask it which character is at
     * the desired location. In this case we can manipulate
     * 'indexPtr->byteIndex' directly, because we know we're staying inside a
     * single logical line.
     */

    if (chunkPtr && chunkPtr->numBytes > 1) {
	x -= textPtr->dInfoPtr->x - textPtr->dInfoPtr->curXPixelOffset;
	TkTextIndexAddToByteIndex(indexPtr, chunkPtr->layoutProcs->measureProc(chunkPtr, x));
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DLineChunkOfX --
 *
 *	Given an x coordinate in a display line, find the index of the
 *	character closest to that location.
 *
 *	This is effectively the opposite of DLineXOfIndex.
 *
 * Results:
 *	The index at *indexPtr is modified to refer to the character on the
 *	display line that is closest to x.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static TkTextDispChunk *
DLineChunkOfX(
    TkText *textPtr,		/* Widget record for text widget. */
    DLine *dlPtr,		/* Display information for this display line. */
    int x,			/* Pixel x coordinate of point in widget's window. */
    TkTextIndex *indexPtr,	/* This index gets filled in with the index of the character
				 * nearest to x. */
    int *nearby)		/* If non-NULL then gets set to true if (x,y) is not actually over the
				 * returned index, but never set to false. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    TkTextDispChunk *chunkPtr;
    TkTextDispChunkSection *sectionPtr;
    unsigned countBytes;

    /*
     * Scan through the line's chunks to find the one that contains the desired x-coordinate.
     * Before doing this, translate the x-coordinate from the coordinate system of the window
     * to the coordinate system of the line (to take account of x-scrolling).
     */

    chunkPtr = dlPtr->chunkPtr;
    *indexPtr = dlPtr->index;

    if (!chunkPtr) {
	/* this may happen if everything is elided */
	if (nearby) {
	    *nearby = 1;
	}
	return chunkPtr;
    }

    x -= dInfoPtr->x - dInfoPtr->curXPixelOffset;

    if (x < chunkPtr->x) {
	if (chunkPtr->stylePtr->sValuePtr->indentBg) {
	    /* if -indentbackground is enabled, then do not trigger when hovering the margin */
	    *nearby = 1;
	}
	return chunkPtr;
    }

    sectionPtr = chunkPtr->sectionPtr;
    countBytes = chunkPtr->byteOffset;

    while (sectionPtr->nextPtr && x >= sectionPtr->nextPtr->chunkPtr->x) {
	countBytes += sectionPtr->numBytes;
	sectionPtr = sectionPtr->nextPtr;
    }

    chunkPtr = sectionPtr->chunkPtr;

    while (chunkPtr->nextPtr && x >= chunkPtr->x + chunkPtr->width) {
	countBytes += chunkPtr->numBytes;
	chunkPtr = chunkPtr->nextPtr;
    }

    TkrTextIndexForwBytes(textPtr, indexPtr, countBytes, indexPtr);
    return chunkPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexOfX --
 *
 *	Given a logical x coordinate (i.e. distance in pixels from the
 *	beginning of the display line, not taking into account any information
 *	about the window, scrolling etc.) on the display line starting with
 *	the given index, adjust that index to refer to the object under the x
 *	coordinate.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
TkTextIndexOfX(
    TkText *textPtr,		/* Widget record for text widget. */
    int x,			/* The x coordinate for which we want the index. */
    TkTextIndex *indexPtr)	/* Index of display line start, which will be adjusted to the
				 * index under the given x coordinate. */
{
    TextDInfo *dInfoPtr;
    DLine *dlPtr;

    assert(textPtr);

    if (TkTextIndexGetLine(indexPtr) == TkBTreeGetLastLine(textPtr)) {
	return;
    }

    dInfoPtr = textPtr->dInfoPtr;
    dlPtr = FindCachedDLine(textPtr, indexPtr);

    if (!dlPtr
	    && !(dInfoPtr->flags & DINFO_OUT_OF_DATE)
	    && TkTextIndexCompare(indexPtr, &textPtr->topIndex) >= 0) {
	dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, indexPtr);
    }
    if (!dlPtr) {
	DisplayInfo info;

	ComputeDisplayLineInfo(textPtr, indexPtr, &info);
	if (!(dlPtr = info.lastDLinePtr)) {
	    TkTextIndex index = *indexPtr;

	    /* we need display line start */
	    TkrTextIndexBackBytes(textPtr, &index, info.byteOffset, &index);
	    dlPtr = LayoutDLine(&index, info.displayLineNo);
	} else if ((info.lastDLinePtr = info.lastDLinePtr->prevPtr)) {
	    dlPtr->prevPtr = info.lastDLinePtr->nextPtr = NULL;
	} else {
	    info.dLinePtr = NULL;
	}
	FreeDLines(textPtr, dlPtr, NULL, DLINE_CACHE);
	FreeDLines(textPtr, info.dLinePtr, NULL, DLINE_FREE_TEMP);
    }
    x += dInfoPtr->x - dInfoPtr->curXPixelOffset;
    DLineIndexOfX(textPtr, DLineChunkOfX(textPtr, dlPtr, x, indexPtr, NULL), x, indexPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * DLineXOfIndex --
 *
 *	Given a relative byte index on a given display line (i.e. the number
 *	of byte indices from the beginning of the given display line), find
 *	the x coordinate of that index within the abstract display line,
 *	without adjusting for the x-scroll state of the line.
 *
 *	This is effectively the opposite of DLineIndexOfX.
 *
 *	NB. The 'byteIndex' is relative to the display line, NOT the logical
 *	line.
 *
 * Results:
 *	The x coordinate.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
DLineXOfIndex(
    TkText *textPtr,		/* Widget record for text widget. */
    DLine *dlPtr,		/* Display information for this display line. */
    unsigned byteIndex)		/* The byte index for which we want the coordinate. */
{
    TkTextDispChunkSection *sectionPtr, *nextPtr;
    TkTextDispChunk *chunkPtr;
    int x;

    if (byteIndex == 0 || !(sectionPtr = dlPtr->chunkPtr->sectionPtr)) {
	return 0;
    }

    while (byteIndex >= sectionPtr->numBytes && (nextPtr = sectionPtr->nextPtr)) {
	byteIndex -= sectionPtr->numBytes;
	sectionPtr = nextPtr;
    }

    chunkPtr = sectionPtr->chunkPtr;
    assert(chunkPtr);

    /*
     * Scan through the line's chunks to find the one that contains the desired byte index.
     */

    x = 0;

    while (1) {
	if (byteIndex < chunkPtr->numBytes) {
	    int unused;

	    x = chunkPtr->x;
	    chunkPtr->layoutProcs->bboxProc(textPtr, chunkPtr, byteIndex,
		    dlPtr->y + dlPtr->spaceAbove,
		    dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow,
		    dlPtr->baseline - dlPtr->spaceAbove, &x, &unused, &unused,
		    &unused);
	    break;
	}
	if (!chunkPtr->nextPtr || byteIndex == chunkPtr->numBytes) {
	    x = chunkPtr->x + chunkPtr->width;
	    break;
	}
	byteIndex -= chunkPtr->numBytes;
	chunkPtr = chunkPtr->nextPtr;
    }

    return x;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextIndexBbox --
 *
 *	Given an index, find the bounding box of the screen area occupied by
 *	the entity (character, window, image) at that index.
 *
 * Results:
 *	'True' is returned if the index is on the screen. 'False' means the index
 *	is not on the screen. If the return value is 'true', then the bounding box
 *	of the part of the index that's visible on the screen is returned to
 *	*xPtr, *yPtr, *widthPtr, and *heightPtr.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextIndexBbox(
    TkText *textPtr,		/* Widget record for text widget. */
    const TkTextIndex *indexPtr,/* Index whose bounding box is desired. */
    int extents,		/* Return the extents of the bbox (the overflow, not visible on
				 * screen). */
    int *xPtr, int *yPtr,	/* Filled with index's upper-left coordinate. */
    int *widthPtr, int *heightPtr,
				/* Filled in with index's dimensions. */
    int *charWidthPtr,		/* If the 'index' is at the end of a display line and therefore
				 * takes up a very large width, this is used to return the smaller
				 * width actually desired by the index. */
    Tcl_UniChar *thisChar)	/* Character at given position, can be NULL. Zero will be returned
				 * if this is not a char chunk, or if outside of screen. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    int isLastCharInLine;
    DLine *dlPtr;

    /*
     * Make sure that all of the screen layout information is up to date.
     */

    if (dInfoPtr->flags & DINFO_OUT_OF_DATE) {
	UpdateDisplayInfo(textPtr);
    }

    /*
     * Find the display line containing the desired index.
     */

    dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, indexPtr);

    /*
     * Two cases shall be trapped here because the logic later really
     * needs dlPtr to be the display line containing indexPtr:
     *   1. if no display line contains the desired index (NULL dlPtr or no chunk)
     *   2. if indexPtr is before the first display line, in which case
     *      dlPtr currently points to the first display line
     */

    if (!dlPtr || !dlPtr->chunkPtr || TkTextIndexCompare(&dlPtr->index, indexPtr) > 0) {
	if (thisChar) { *thisChar = 0; }
	return 0;
    }

    if (!GetBbox(textPtr, dlPtr, indexPtr, xPtr, yPtr, widthPtr, heightPtr,
	    &isLastCharInLine, thisChar)) {
	return 0;
    }

    *xPtr -= dInfoPtr->curXPixelOffset;

    if (extents) {
	*widthPtr = MAX(0, *xPtr + *widthPtr - dInfoPtr->maxX);
	*heightPtr = MAX(0, *yPtr + *heightPtr - dInfoPtr->maxY);
	*xPtr = MAX(0, -*xPtr);
	*yPtr = MAX(0, -*yPtr);
    } else {
	*xPtr = *xPtr + dInfoPtr->x;

	if (isLastCharInLine) {
	    /*
	     * Last character in display line. Give it all the space up to the line.
	     */

	    if (charWidthPtr) {
		*charWidthPtr = dInfoPtr->maxX - *xPtr;
		if (*charWidthPtr > textPtr->charWidth) {
		    *charWidthPtr = textPtr->charWidth;
		}
	    }
	    if (*xPtr > dInfoPtr->maxX) {
		*xPtr = dInfoPtr->maxX;
	    }
	    *widthPtr = dInfoPtr->maxX - *xPtr;
	} else {
	    if (charWidthPtr) {
		*charWidthPtr = *widthPtr;
	    }
	}

	if (*widthPtr == 0) {
	    /*
	     * With zero width (e.g. elided text) we just need to make sure it is
	     * onscreen, where the '=' case here is ok.
	     */

	    if (*xPtr < dInfoPtr->x) {
		return 0;
	    }
	} else if (*xPtr + *widthPtr <= dInfoPtr->x) {
	    return 0;
	}

	if (*xPtr + *widthPtr > dInfoPtr->maxX) {
	    if ((*widthPtr = dInfoPtr->maxX - *xPtr) <= 0) {
		return 0;
	    }
	}

	if (*yPtr + *heightPtr > dInfoPtr->maxY) {
	    if ((*heightPtr = dInfoPtr->maxY - *yPtr) <= 0) {
		return 0;
	    }
	}
    }

    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextDLineInfo --
 *
 *	Given an index, return information about the display line containing
 *	that character.
 *
 * Results:
 *	'true' is returned if the character is on the screen. 'false' means
 *	the character isn't on the screen. If the return value is 'true', then
 *	information is returned in the variables pointed to by xPtr, yPtr,
 *	widthPtr, heightPtr, and basePtr.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

int
TkTextGetDLineInfo(
    TkText *textPtr,		/* Widget record for text widget. */
    const TkTextIndex *indexPtr,/* Index of character whose bounding box is desired. */
    int extents,		/* Return the extents of the bbox (the overflow, not visible on
				 * screen). */
    int *xPtr, int *yPtr,	/* Filled with line's upper-left coordinate. */
    int *widthPtr, int *heightPtr,
				/* Filled in with line's dimensions. */
    int *basePtr)		/* Filled in with the baseline position, measured as an offset down
				 * from *yPtr. */
{
    TextDInfo *dInfoPtr = textPtr->dInfoPtr;
    DLine *dlPtr;
    int dlx;

    /*
     * Make sure that all of the screen layout information is up to date.
     */

    if (dInfoPtr->flags & DINFO_OUT_OF_DATE) {
	UpdateDisplayInfo(textPtr);
    }

    /*
     * Find the display line containing the desired index.
     */

    dlPtr = FindDLine(textPtr, dInfoPtr->dLinePtr, indexPtr);

    /*
     * Two cases shall be trapped here because the logic later really
     * needs dlPtr to be the display line containing indexPtr:
     *   1. if no display line contains the desired index (NULL dlPtr)
     *   2. if indexPtr is before the first display line, in which case
     *      dlPtr currently points to the first display line
     */

    if (!dlPtr || TkTextIndexCompare(&dlPtr->index, indexPtr) > 0) {
	return 0;
    }

    dlx = dlPtr->chunkPtr ? dlPtr->chunkPtr->x : 0;
    *xPtr = dInfoPtr->x - dInfoPtr->curXPixelOffset + dlx;
    *widthPtr = dlPtr->width;
    *yPtr = dlPtr->y;
    *heightPtr = dlPtr->height;

    if (extents) {
	*widthPtr = MAX(0, *xPtr + (int) dlPtr->length - dInfoPtr->maxX);
	*heightPtr = MAX(0, *yPtr + *heightPtr - dInfoPtr->maxY);
	*xPtr = MAX(0, -*xPtr);
	*yPtr = MAX(0, -*yPtr);
    } else {
	if (dlPtr->y + dlPtr->height > dInfoPtr->maxY) {
	    *heightPtr = dInfoPtr->maxY - dlPtr->y;
	}
    }

    *basePtr = dlPtr->baseline;
    return 1;
}

/*
 * Get bounding-box information about an elided chunk.
 */

static void
ElideBboxProc(
    TCL_UNUSED(TkText *),
    TkTextDispChunk *chunkPtr,	/* Chunk containing desired char. */
    TCL_UNUSED(Tcl_Size),			/* Index of desired character within the chunk. */
    int y,			/* Topmost pixel in area allocated for this line. */
    TCL_UNUSED(int),		/* Height of line, in pixels. */
    TCL_UNUSED(int),		/* Location of line's baseline, in pixels measured down from y. */
    int *xPtr, int *yPtr,	/* Gets filled in with coords of character's upper-left pixel.
				 * X-coord is in same coordinate system as chunkPtr->x. */
    int *widthPtr,		/* Gets filled in with width of character, in pixels. */
    int *heightPtr)		/* Gets filled in with height of character, in pixels. */
{
    *xPtr = chunkPtr->x;
    *yPtr = y;
    *widthPtr = *heightPtr = 0;
}

/*
 * Measure an elided chunk.
 */

static Tcl_Size
ElideMeasureProc(
    TCL_UNUSED(TkTextDispChunk *),	/* Chunk containing desired coord. */
    TCL_UNUSED(int))			/* X-coordinate, in same coordinate system as chunkPtr->x. */
{
    return 0;
}

/*
 *--------------------------------------------------------------
 *
 * CharMeasureProc --
 *
 *	This function is called to determine which character in a character
 *	chunk lies over a given x-coordinate.
 *
 * Results:
 *	The return value is the index *within the chunk* of the character that
 *	covers the position given by "x".
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static Tcl_Size
CharMeasureProc(
    TkTextDispChunk *chunkPtr,	/* Chunk containing desired coord. */
    int x)			/* X-coordinate, in same coordinate system as chunkPtr->x. */
{
    if (chunkPtr->endOfLineSymbol) {
	return 0;
    }
    assert(chunkPtr->dlPtr->index.textPtr);
    return CharChunkMeasureChars(chunkPtr, NULL, 0, 0, chunkPtr->numBytes - 1, chunkPtr->x, x,
	    chunkPtr->dlPtr->index.textPtr->spaceMode, 0, NULL);
}

/*
 *--------------------------------------------------------------
 *
 * CharBboxProc --
 *
 *	This function is called to compute the bounding box of the area
 *	occupied by a single character.
 *
 * Results:
 *	There is no return value. *xPtr and *yPtr are filled in with the
 *	coordinates of the upper left corner of the character, and *widthPtr
 *	and *heightPtr are filled in with the dimensions of the character in
 *	pixels. Note: not all of the returned bbox is necessarily visible on
 *	the screen (the rightmost part might be off-screen to the right, and
 *	the bottommost part might be off-screen to the bottom).
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static void
CharBboxProc(
    TkText *textPtr,
    TkTextDispChunk *chunkPtr,	/* Chunk containing desired char. */
    Tcl_Size byteIndex,		/* Byte offset of desired character within the chunk */
    int y,			/* Topmost pixel in area allocated for this line. */
    TCL_UNUSED(int),		/* Height of line, in pixels. */
    int baseline,		/* Location of line's baseline, in pixels measured down from y. */
    int *xPtr, int *yPtr,	/* Gets filled in with coords of character's upper-left pixel.
				 * X-coord is in same coordinate system as chunkPtr->x. */
    int *widthPtr,		/* Gets filled in with width of character, in pixels. */
    int *heightPtr)		/* Gets filled in with height of character, in pixels. */
{
    CharInfo *ciPtr = (CharInfo *)chunkPtr->clientData;
    int offset = ciPtr->baseOffset + byteIndex;
    int maxX = chunkPtr->width + chunkPtr->x;
    int nextX;

    CharChunkMeasureChars(chunkPtr, NULL, 0, 0, byteIndex, chunkPtr->x, -1, textPtr->spaceMode, 0, xPtr);

    if (byteIndex >= ciPtr->numBytes) {
	/*
	 * This situation only happens if the last character in a line is a
	 * space character, in which case it absorbs all of the extra space in
	 * the line (see TkTextCharLayoutProc).
	 */

	*widthPtr = maxX - *xPtr;
    } else if (ciPtr->u.chars[offset] == '\t' && byteIndex == ciPtr->numBytes - 1) {
	/*
	 * The desired character is a tab character that terminates a chunk;
	 * give it all the space left in the chunk.
	 */

	*widthPtr = maxX - *xPtr;
    } else {
	CharChunkMeasureChars(chunkPtr, NULL, 0, byteIndex, byteIndex + 1, *xPtr, -1,
		textPtr->spaceMode, 0, &nextX);

	if (nextX >= maxX) {
	    *widthPtr = maxX - *xPtr;
	} else {
	    *widthPtr = nextX - *xPtr;

	    if (chunkPtr->additionalWidth && IsExpandableSpace(ciPtr->u.chars + offset)) {
		/*
		 * We've expanded some spaces for full line justification. Compute the
		 * width of this specific space character.
		 */

		const char *base = ciPtr->u.chars + ciPtr->baseOffset;
		const char *q = ciPtr->u.chars + offset;
		unsigned numSpaces = chunkPtr->numSpaces;
		unsigned remaining = chunkPtr->additionalWidth;

		do {
		    unsigned space;

		    assert(numSpaces > 0);
		    space = (remaining + numSpaces - 1)/numSpaces;
		    *widthPtr += space;
		    remaining -= space;
		    numSpaces -= 1;
		    if (base == q) {
			break;
		    }
		    q = Tcl_UtfPrev(q, ciPtr->u.chars);
		} while (IsExpandableSpace(q));
	    }
	}
    }

    *yPtr = y + baseline - chunkPtr->minAscent;
    *heightPtr = chunkPtr->minAscent + chunkPtr->minDescent;
}

/*
 *----------------------------------------------------------------------
 *
 * AdjustForTab --
 *
 *	This function is called to move a series of chunks right in order to
 *	align them with a tab stop.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The width of chunkPtr gets adjusted so that it absorbs the extra space
 *	due to the tab. The x locations in all the chunks after chunkPtr are
 *	adjusted rightward to align with the tab stop given by tabArrayPtr and
 *	index.
 *
 *----------------------------------------------------------------------
 */

static void
AdjustForTab(
    LayoutData *data)
{
    int x, desired = 0, delta, width;
    TkTextDispChunk *chunkPtr, *nextChunkPtr, *chPtr;
    TkTextTabArray *tabArrayPtr;
    TkText *textPtr;
    int tabX, tabIndex;

    assert(data->tabIndex >= 0);

    if (!(chunkPtr = data->tabChunkPtr)) {
	/* Part after decimal point, no action required. */
	return;
    }

    if (data->adjustFirstChunk) {
	nextChunkPtr = chunkPtr;
    } else if (!(nextChunkPtr = chunkPtr->nextPtr) && data->lastChunkPtr) {
	/* Nothing after the actual tab; just return. */
	return;
    }

    data->tabApplied = 1;
    tabX = data->tabX;
    tabIndex = data->tabIndex;
    textPtr = data->textPtr;
    tabArrayPtr = data->tabArrayPtr;
    x = nextChunkPtr ? nextChunkPtr->x : 0;

    /*
     * If no tab information has been given, assuming tab stops are at 8
     * average-sized characters. Still ensure we respect the tabular versus
     * wordprocessor tab style.
     */

    if (!tabArrayPtr || tabArrayPtr->numTabs == 0) {
	/*
	 * No tab information has been given, so use the default
	 * interpretation of tabs.
	 */

	unsigned tabWidth = textPtr->charWidth*8;

	tabWidth = MAX(1u, tabWidth);

	if (textPtr->tabStyle == TK_TEXT_TABSTYLE_TABULAR) {
	    desired = tabWidth*(tabIndex + 1);
	} else {
	    desired = NextTabStop(tabWidth, x, 0);
	}

	desired %= data->maxX;
    } else {
	switch (data->tabAlignment) {
	case LEFT:
	    desired = tabX;
	    break;

	case CENTER:
	    /*
	     * Compute the width of all the information in the tab group, then use
	     * it to pick a desired location.
	     */

	    width = 0;
	    for (chPtr = nextChunkPtr; chPtr; chPtr = chPtr->nextPtr) {
		width += chPtr->width;
	    }
	    if (data->maxX >= 0) {
		desired = MIN(tabX, data->maxX) - width/2;
	    } else {
		desired = tabX - width/2;
	    }
	    break;

	case RIGHT:
	    /*
	     * Compute the width of all the information in the tab group, then use
	     * it to pick a desired location.
	     */

	    width = 0;
	    for (chPtr = nextChunkPtr; chPtr; chPtr = chPtr->nextPtr) {
		width += chPtr->width;
	    }
	    if (data->maxX - data->tabOverhang >= 0) {
		desired = MIN(tabX, data->maxX - data->tabOverhang) - width;
	    } else {
		desired = tabX - width;
	    }
	    break;

	case NUMERIC:
	    /*
	     * Right justify before decimal point.
	     */

	    width = 0;
	    for (chPtr = nextChunkPtr; chPtr && !chPtr->integralPart; chPtr = chPtr->nextPtr) {
		width += chPtr->width;
	    }
	    if (data->maxX - data->tabOverhang >= 0) {
		desired = MIN(tabX, data->maxX - data->tabOverhang) - width;
	    } else {
		desired = data->maxX - data->tabOverhang - width;
	    }
	    data->tabApplied = 0;
	    break;
	}
    }

    desired += data->tabShift;

    /*
     * Shift all of the chunks to the right so that the left edge is at the
     * desired location, then expand the chunk containing the tab. Be sure
     * that the tab occupies at least the width of a space character.
     */

    delta = MAX(textPtr->spaceWidth, desired - x);

    if (nextChunkPtr) {
	for (chPtr = nextChunkPtr; chPtr; chPtr = chPtr->nextPtr) {
	    chPtr->x += delta;
	}
	chunkPtr->width += delta;
    } else {
	chunkPtr->x = MAX(0, delta - chunkPtr->width);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeShiftForRightTab --
 *
 *	This estimates the amount of characters we have to shift to next
 *	line for adjustment of right tabs. The computation is a bit tricky,
 *	because we have to measure backwards.
 *
 * Results:
 *	Store the number of characters for next line in 'data->shiftToNextLine'.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
MeasureBackwards(
    LayoutData *data,
    TkTextSegment *firstSegPtr,
    int offset,
    TkTextSegment *lastSegPtr,
    int lastOffset)
{
    TkTextSegment *segPtr;
    int maxX = data->tabX % data->maxX;

    data->shiftToNextLine = 0;
    data->shiftToNextLinePos.segPtr = NULL;

    for (segPtr = lastSegPtr; segPtr != firstSegPtr->prevPtr; segPtr = segPtr->prevPtr) {
	switch (segPtr->typePtr->group) {
	case SEG_GROUP_CHAR: {
	    const char *p = segPtr->body.chars + (segPtr == firstSegPtr ? offset : 0);
	    const char *e = segPtr->body.chars + (segPtr == lastSegPtr ? lastOffset : segPtr->size);
	    unsigned length = e - p;

	    if (e > p && e[-1] == '\n') {
		e -= 1;
		length -= 1;
	    }

	    if (length > 0) {
		TextStyle *stylePtr = GetStyle(data->textPtr, segPtr);
		char buffer[512];
		char *str = buffer;
		char *first;
		char *last;
		int nextX;
		int fit;

		if ((size_t) length > sizeof(buffer)) {
		    str = (char *)ckalloc(length);
		}
		memcpy(str, p, length);

		first = str;
		last = str + length;
		for (--last ; first < last; ++first, --last)
		{
		    char c = *first;
		    *first = *last;
		    *last = c;
		}

		fit = MeasureChars(stylePtr->sValuePtr->tkfont,
			str, length, 0, length, 0, maxX, 0, &nextX);
		FreeStyle(data->textPtr, stylePtr);

		if (fit < (int) length && maxX - nextX > 0)
		{
		    int x;
		    MeasureChars(stylePtr->sValuePtr->tkfont, str + fit, 1, 0, 1, 0, -1, 0, &x);
		    data->tabOverhang = MAX(0, x - (maxX - nextX));
		}
		if (fit) {
		    if (*e == '\n') {
			fit += 1;
			length += 1;
		    }
		    data->shiftToNextLine += fit;
		    data->shiftToNextLinePos.segPtr = segPtr;
		    data->shiftToNextLinePos.offset = (p - segPtr->body.chars) + length - fit;
		    maxX -= nextX;
		}
		if (str != buffer) {
		    ckfree(str);
		}
		if (maxX <= 0) {
		    return;
		}
	    }
	    break;
	}
	case SEG_GROUP_HYPHEN:
	    if (!data->textPtr->hyphenate) {
		TextStyle *stylePtr;
		int nextX, fit;

		stylePtr = GetStyle(data->textPtr, segPtr);
		fit = MeasureChars(stylePtr->sValuePtr->tkfont,
			HYPHEN_STRING, HYPHEN_LENGTH, 0, HYPHEN_LENGTH, 0, maxX, 0, &nextX);
		if (!fit) {
		    return;
		}
		data->shiftToNextLine += fit;
		data->shiftToNextLinePos.segPtr = segPtr;
		data->shiftToNextLinePos.offset = 0;
		maxX -= nextX;
	    }
	    break;
	case SEG_GROUP_IMAGE:
	case SEG_GROUP_WINDOW: {
	    TkTextIndex index;

	    TkTextIndexClear(&index, data->textPtr);
	    TkTextIndexSetSegment(&index, segPtr);

	    if (segPtr->typePtr->layoutProc(&index, segPtr, 0, maxX, 1, 0, data->wrapMode,
		    data->textPtr->spaceMode, NULL) == 0) {
		return;
	    }
	    data->shiftToNextLine += 1;
	    data->shiftToNextLinePos.segPtr = segPtr;
	    data->shiftToNextLinePos.offset = 0;
	    break;
	}
	case SEG_GROUP_BRANCH:
	    if (segPtr->typePtr == &tkTextLinkType) {
		segPtr = segPtr->body.link.prevPtr;
	    }
	    break;
	case SEG_GROUP_MARK:
	case SEG_GROUP_PROTECT:
	case SEG_GROUP_TAG:
	    break;
	}
    }
}

static TkTextSegment *
FindEndOfTab(
    LayoutData *data,
    TkTextSegment *segPtr,
    int offset,
    int *lastOffset)
{
    TkTextSegment *firstSegPtr = segPtr;
    TkTextSegment *lastSegPtr = segPtr;

    *lastOffset = offset;

    for ( ; segPtr; segPtr = segPtr->nextPtr) {
	switch (segPtr->typePtr->group) {
	case SEG_GROUP_CHAR: {
	    const char *p = segPtr->body.chars + (segPtr == firstSegPtr ? offset : 0);
	    const char *e = segPtr->body.chars + segPtr->size;

	    for ( ; p < e; ++p) {
		if (*p == '\t') {
		    *lastOffset = p - segPtr->body.chars;
		    return segPtr;
		}
	    }

	    lastSegPtr = segPtr;
	    *lastOffset = e - segPtr->body.chars;
	    break;
	}
	case SEG_GROUP_HYPHEN: {
	    if (data->textPtr->hyphenate) {
		return lastSegPtr;
	    }
	    lastSegPtr = segPtr;
	    *lastOffset = HYPHEN_LENGTH;
	    break;
	}
	case SEG_GROUP_BRANCH:
	    if (segPtr->typePtr == &tkTextBranchType) {
		segPtr = segPtr->body.branch.nextPtr;
	    }
	    break;
	case SEG_GROUP_IMAGE:
	case SEG_GROUP_WINDOW:
	    lastSegPtr = segPtr;
	    *lastOffset = 1;
	    break;
	case SEG_GROUP_MARK:
	case SEG_GROUP_PROTECT:
	case SEG_GROUP_TAG:
	    break;
	}
    }

    return lastSegPtr;
}

static void
ComputeShiftForRightTab(
    LayoutData *data,
    TkTextSegment *segPtr,
    int offset)
{
    int lastOffset;
    TkTextSegment *lastSegPtr = FindEndOfTab(data, segPtr, offset, &lastOffset);

    assert(data->tabX > data->maxX);
    MeasureBackwards(data, segPtr, offset, lastSegPtr, lastOffset);
    if (data->shiftToNextLine) {
	data->isRightTab = 1;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * IsStartOfTab --
 *
 *	Determine whether the given offset in segment is immediately after
 *	tab character.
 *
 * Results:
 *	Whether given offset in segment is immediately after tab character.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
IsStartOfTab(
    TkTextSegment *segPtr,
    int offset)
{
    if (offset > 0) {
	return segPtr->body.chars[offset - 1] == '\t';
    }
    for ( ; segPtr; segPtr = segPtr->prevPtr) {
	switch (segPtr->typePtr->group) {
	case SEG_GROUP_CHAR:
	    return segPtr->body.chars[segPtr->size - 1] == '\t';
	case SEG_GROUP_HYPHEN:
	case SEG_GROUP_IMAGE:
	case SEG_GROUP_WINDOW:
	    return 0;
	case SEG_GROUP_BRANCH:
	    if (segPtr->typePtr == &tkTextLinkType) {
		segPtr = segPtr->body.link.prevPtr;
	    }
	    break;
	case SEG_GROUP_MARK:
	case SEG_GROUP_PROTECT:
	case SEG_GROUP_TAG:
	    break;
	}
    }
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeShiftForNumericTab --
 *
 *	This estimates the amount of characters we have to shift to next
 *	line for adjustment of numeric tabs. The computation is a bit tricky,
 *	because we have to measure backwards.
 *
 * Results:
 *	Store the number of characters for next line in 'data->shiftToNextLine'.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */


static void
ComputeShiftForNumericTab(
    LayoutData *data,
    TkTextSegment *firstSegPtr,
    int offset)
{
    TkTextSegment *lastSegPtr = data->lastNumericalPos.segPtr;

    if (!lastSegPtr || !IsStartOfTab(firstSegPtr, offset)) {
	return;
    }

    if (data->tabX < data->maxX) {
	return; /* may happen with very small size */
    }

    MeasureBackwards(data, firstSegPtr, offset, lastSegPtr, data->lastNumericalPos.offset);
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeSizeOfTab --
 *
 *	This estimates the amount of white space that will be consumed by
 *	a tab.
 *
 * Results:
 *	The 'current tab' is the minimum number of pixels that will be occupied
 *	by the next tab of tabArrayPtr, assuming that the current position on the
 *	line is x and the end of the line is maxX. The 'next tab' is determined
 *	by a combination of the current position (x) which it must be equal to or
 *	beyond, and the tab count in indexPtr.
 *
 *	For numeric tabs, this is a conservative estimate. The 'current tab' is
 *	always >= 0.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
FindDecimalPointBackwards(
    TkTextSegment *segPtr,
    int offset)
{
    TkTextSegment *startSegPtr = segPtr;

    for ( ; segPtr; segPtr = segPtr->prevPtr) {
	if (segPtr->typePtr->group == SEG_GROUP_CHAR) {
	    const char *p = segPtr->body.chars + (segPtr == startSegPtr ? offset : segPtr->size);

	    for (--p; p >= segPtr->body.chars; --p) {
		if (IsDecimalPoint(*p)) {
		    return 1;
		}
	    }
	} else if (segPtr->typePtr->group == SEG_GROUP_BRANCH) {
	    if (segPtr->typePtr == &tkTextLinkType) {
		segPtr = segPtr->body.link.prevPtr;
	    }
	}
    }
    return 0;
}

static void
FindDecimalPoint(
    LayoutData *data,
    TkTextSegment *segPtr,
    int offset)
{
    for ( ; segPtr; segPtr = segPtr->nextPtr) {
	switch (segPtr->typePtr->group) {
	case SEG_GROUP_CHAR: {
	    const char *p = segPtr->body.chars + offset;
	    const char *e = segPtr->body.chars + segPtr->size;

	    for ( ; p < e; ++p) {
		if (IsDecimalPoint(*p)) {
		    data->lengthOfFractional = 0;
		    data->decimalPointPos.segPtr = segPtr;
		    data->decimalPointPos.offset = p - segPtr->body.chars;
		} else if (*p == '\t' || *p == '\n') {
		    return;
		}
		if (data->decimalPointPos.segPtr) {
		    data->lengthOfFractional += 1;
		}
		data->lastNumericalPos.segPtr = segPtr;
		data->lastNumericalPos.offset = p - segPtr->body.chars + 1;
	    }

	    offset = 0;
	    break;
	}
	case SEG_GROUP_HYPHEN:
	case SEG_GROUP_IMAGE:
	case SEG_GROUP_WINDOW:
	    if (data->decimalPointPos.segPtr) {
		data->lengthOfFractional += segPtr->size;
	    }
	    data->lastNumericalPos.segPtr = segPtr;
	    data->lastNumericalPos.offset = segPtr->size;
	    break;
	case SEG_GROUP_BRANCH:
	    if (segPtr->typePtr == &tkTextBranchType) {
		segPtr = segPtr->body.branch.nextPtr;
	    }
	    break;
	case SEG_GROUP_MARK:
	case SEG_GROUP_PROTECT:
	case SEG_GROUP_TAG:
	    break;
	}
    }
}

static void
ComputeSizeOfTab(
    LayoutData *data,
    TkTextSegment *segPtr,
    int offset)
{
    TkText *textPtr;
    TkTextTabArray *tabArrayPtr;
    unsigned tabWidth;
    int min = 0; /* shut up the compiler */

    textPtr = data->textPtr;
    tabArrayPtr = data->tabArrayPtr;
    data->tabApplied = 0;
    data->tabOverhang = 0;

    if (!tabArrayPtr || tabArrayPtr->numTabs == 0) {
	/*
	 * We're using a default tab spacing of 8 characters.
	 */

	tabWidth = MAX(1, textPtr->charWidth*8);
    } else {
	tabWidth = 0;
    }

    do {
	/*
	 * We were given the count before this tab, so increment it first.
	 */

	data->tabIndex += 1;

	if (!tabArrayPtr || tabArrayPtr->numTabs == 0) {
	    /*
	     * We're using a default tab spacing calculated above.
	     */

	    data->tabX = tabWidth*(data->tabIndex + 1);
	    data->tabAlignment = LEFT;
	} else if (data->tabIndex < tabArrayPtr->numTabs) {
	    data->tabX = tabArrayPtr->tabs[data->tabIndex].location;
	    data->tabAlignment = tabArrayPtr->tabs[data->tabIndex].alignment;
	} else {
	    /*
	     * Ran out of tab stops; compute a tab position by extrapolating.
	     */

	    data->tabX = (int) (tabArrayPtr->lastTab
		    + (data->tabIndex + 1 - tabArrayPtr->numTabs)*tabArrayPtr->tabIncrement
		    + 0.5);
	    data->tabAlignment = tabArrayPtr->tabs[tabArrayPtr->numTabs - 1].alignment;
	}

	/*
	 * If this tab stop is before the current x position, then we have two
	 * cases:
	 *
	 * With 'wordprocessor' style tabs, we must obviously continue until
	 * we reach the text tab stop.
	 *
	 * With 'tabular' style tabs, we always use the data->tabIndex'th tab stop.
	 */
    } while (data->tabX <= data->x && data->tabStyle == TK_TEXT_TABSTYLE_WORDPROCESSOR);

    if (data->displayLineNo > 0 && data->tabStyle != TK_TEXT_TABSTYLE_WORDPROCESSOR) {
	int tabX = data->tabX - ((int) data->displayLineNo)*data->maxX;

	if (data->tabAlignment == LEFT && data->x == 0) {
	    data->tabShift = tabX;
	}

	data->tabX = MAX(0, tabX + data->tabShift);
    }

    /*
     * Inform our caller of how many tab stops we've used up.
     */

    switch (data->tabAlignment) {
    case CENTER:
	if (data->displayLineNo > 0 && data->x == 0) {
	    data->tabSize = 0;
	    return;
	}
	/*
	 * Be very careful in the arithmetic below, because maxX may be the
	 * largest positive number: watch out for integer overflow.
	 */
	if (data->maxX - data->tabX < data->tabX - data->x) {
	    data->tabSize = data->maxX - data->x - 2*(data->maxX - data->tabX);
	    min = textPtr->spaceWidth;
	} else {
	    min = 0;
	}
	break;

    case RIGHT:
	data->isRightTab = 0; /* will only be set when wrapping line */
	data->tabSize = data->maxX - data->tabX - data->x;
	min = (data->x == 0) ? 0 : textPtr->spaceWidth;
	break;

    case NUMERIC:
	/*
	 * We have to pre-compute the position of the last decimal point, and
	 * the position of the first non-numerical character.
	 */
	data->isNumericTab = 0;
	data->decimalPointPos.segPtr = NULL;
	data->shiftToNextLinePos.segPtr = NULL;
	FindDecimalPoint(data, segPtr, offset);
	if (data->decimalPointPos.segPtr) {
	    data->lastNumericalPos = data->decimalPointPos;
	    data->isNumericTab = 1;
	} else if (!FindDecimalPointBackwards(segPtr, offset)) {
	    data->isNumericTab = 1;
	}
	min = 0;
	/* fallthru */

    case LEFT:
	data->tabSize = data->tabX - data->x;
	assert(textPtr->spaceWidth > 0); /* ensure positive size */
	min = (data->x == 0) ? 0 : textPtr->spaceWidth;
	break;
    }

    data->tabSize = MAX(min, data->tabSize);
}

/*
 *---------------------------------------------------------------------------
 *
 * NextTabStop --
 *
 *	Given the current position, determine where the next default tab stop
 *	would be located. This function is called when the current chunk in
 *	the text has no tabs defined and so the default tab spacing for the
 *	font should be used, provided we are using wordprocessor style tabs.
 *
 * Results:
 *	The location in pixels of the next tab stop.
 *
 * Side effects:
 *	None.
 *
 *---------------------------------------------------------------------------
 */

static int
NextTabStop(
    unsigned tabWidth,		/* Default tab width of the widget. */
    int x,			/* X-position in pixels where last character was drawn. The next
				 * tab stop occurs somewhere after this location. */
    int tabOrigin)		/* The origin for tab stops. May be non-zero if text has been
				 * scrolled. */
{
    int rem;

    assert(tabWidth > 0);

    x += tabWidth;
    if ((rem = (x - tabOrigin) % tabWidth) < 0) {
	rem += tabWidth;
    }
    x -= rem;
    return x;
}

/*
 *---------------------------------------------------------------------------
 *
 * MeasureChars --
 *
 *	Determine the number of characters from the string that will fit in
 *	the given horizontal span. The measurement is done under the
 *	assumption that Tk_DrawChars will be used to actually display the
 *	characters.
 *
 *	If tabs are encountered in the string, they will be ignored (they
 *	should only occur as last character of the string anyway).
 *
 *	If a newline is encountered in the string, the line will be broken at
 *	that point.
 *
 * Results:
 *	The return value is the number of bytes from the range of start to end
 *	in source that fit in the span given by startX and maxX. *nextXPtr is
 *	filled in with the x-coordinate at which the first character that
 *	didn't fit would be drawn, if it were to be drawn.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

#ifdef TK_DRAW_IN_CONTEXT

static int
TkpMeasureChars(
    Tk_Font tkfont,
    const char *source,
    Tcl_Size numBytes,
    int rangeStart,
    int rangeLength,
    int maxLength,
    int flags,
    int *lengthPtr)
{
    return TkpMeasureCharsInContext(tkfont, source, numBytes, rangeStart,
	    rangeLength, maxLength, flags, lengthPtr);
}

#else /* if !TK_DRAW_IN_CONTEXT */

static int
TkpMeasureChars(
    Tk_Font tkfont,
    const char *source,
    TCL_UNUSED(Tcl_Size),
    Tcl_Size rangeStart,
    Tcl_Size rangeLength,
    int maxLength,
    int flags,
    int *lengthPtr)
{
    return Tk_MeasureChars(tkfont, source + rangeStart, rangeLength, maxLength, flags, lengthPtr);
}

#endif /* TK_DRAW_IN_CONTEXT */

static int
MeasureChars(
    Tk_Font tkfont,		/* Font in which to draw characters. */
    const char *source,		/* Characters to be displayed. Need not be NUL-terminated. */
    Tcl_Size maxBytes,		/* Maximum # of bytes to consider from source. */
    Tcl_Size rangeStart, Tcl_Size rangeLength,
				/* Range of bytes to consider in source.*/
    int startX,			/* X-position at which first character will be drawn. */
    int maxX,			/* Don't consider any character that would cross this x-position. */
    int flags,			/* Flags to pass to Tk_MeasureChars. */
    int *nextXPtr)		/* Return x-position of terminating character here, can be NULL. */
{
    int curX, width, ch;
    const char *special, *end, *start;

    ch = 0;
    curX = startX;
    start = source + rangeStart;
    end = start + rangeLength;
    special = start;

    while (start < end) {
	if (start >= special) {
	    /*
	     * Find the next special character in the string.
	     */

	    for (special = start; special < end; ++special) {
		ch = *special;
		if (ch == '\t' || ch == '\n') {
		    break;
		}
	    }
	}

	/*
	 * Special points at the next special character (or the end of the
	 * string). Process characters between start and special.
	 */

	if (maxX >= 0 && curX >= maxX) {
	    break;
	}
	start += TkpMeasureChars(tkfont, source, maxBytes, start - source, special - start,
		maxX >= 0 ? maxX - curX : -1, flags, &width);
	curX += width;
	if (start < special) {
	    /*
	     * No more chars fit in line.
	     */

	    break;
	}
	if (special < end) {
	    if (ch != '\t') {
		break;
	    }
	    start += 1;
	}
    }

    if (nextXPtr) {
	*nextXPtr = curX;
    }
    return start - (source + rangeStart);
}

/*
 *----------------------------------------------------------------------
 *
 * TextGetScrollInfoObj --
 *
 *	This function is invoked to parse "xview" and "yview" scrolling
 *	commands for text widgets using the new scrolling command syntax
 *	("moveto" or "scroll" options). It extends the public
 *	Tk_GetScrollInfoObj function with the addition of "pixels" as a valid
 *	unit alongside "pages" and "units". It is a shame the core API isn't
 *	more flexible in this regard.
 *
 * Results:
 *	The return value is either SCROLL_MOVETO, SCROLL_PAGES,
 *	SCROLL_UNITS, SCROLL_PIXELS or SCROLL_ERROR. This
 *	indicates whether the command was successfully parsed and what form
 *	the command took. If SCROLL_MOVETO, *dblPtr is filled in with
 *	the desired position; if SCROLL_PAGES, SCROLL_PIXELS or
 *	SCROLL_UNITS, *intPtr is filled in with the number of
 *	pages/pixels/lines to move (may be negative); if SCROLL_ERROR,
 *	the interp's result contains an error message.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static ScrollMethod
TextGetScrollInfoObj(
    Tcl_Interp *interp,		/* Used for error reporting. */
    TkText *textPtr,		/* Information about the text widget. */
    int objc,			/* # arguments for command. */
    Tcl_Obj *const objv[],	/* Arguments for command. */
    double *dblPtr,		/* Filled in with argument "moveto" option, if any. */
    int *intPtr)		/* Filled in with number of pages or lines or pixels to scroll,
				 * if any. */
{
    static const char *const subcommands[] = {
	"moveto", "scroll", NULL
    };
    enum viewSubcmds {
	VIEW_MOVETO, VIEW_SCROLL
    };
    static const char *const units[] = {
	"pages", "pixels", "units", NULL
    };
    enum viewUnits {
	VIEW_SCROLL_PAGES, VIEW_SCROLL_PIXELS, VIEW_SCROLL_UNITS
    };
    int index;
    double d;

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

    switch ((enum viewSubcmds) index) {
    case VIEW_MOVETO:
	if (objc != 4) {
	    Tcl_WrongNumArgs(interp, 3, objv, "fraction");
	    return SCROLL_ERROR;
	}
	if (Tcl_GetDoubleFromObj(interp, objv[3], dblPtr) != TCL_OK) {
	    return SCROLL_ERROR;
	}
	return SCROLL_MOVETO;
    case VIEW_SCROLL:
	if (objc != 5) {
	    Tcl_WrongNumArgs(interp, 3, objv, "number pages|pixels|units");
	    return SCROLL_ERROR;
	}
	if (Tcl_GetIndexFromObjStruct(interp, objv[4], units, sizeof(char *), "argument", 0, &index)
		!= TCL_OK) {
	    return SCROLL_ERROR;
	}
	switch ((enum viewUnits) index) {
	case VIEW_SCROLL_PAGES:
	    if (Tcl_GetDoubleFromObj(interp, objv[3], &d) != TCL_OK) {
		return SCROLL_ERROR;
	    }
	    *intPtr = (d > 0) ? ceil(d) : floor(d);
	    if (dblPtr) {
		*dblPtr = d;
	    }
	    return SCROLL_PAGES;
	case VIEW_SCROLL_PIXELS:
	    if (Tk_GetPixelsFromObj(interp, textPtr->tkwin, objv[3], intPtr) != TCL_OK) {
		return SCROLL_ERROR;
	    }
	    return SCROLL_PIXELS;
	case VIEW_SCROLL_UNITS:
	    if (Tcl_GetDoubleFromObj(interp, objv[3], &d) != TCL_OK) {
		return SCROLL_ERROR;
	    }
	    *intPtr = (d > 0) ? ceil(d) : floor(d);
	    if (dblPtr) {
		*dblPtr = d;
	    }
	    return SCROLL_UNITS;
	}
    }
    assert(!"unexpected switch fallthrough");
    return SCROLL_ERROR; /* should be never reached */
}

/*
 *----------------------------------------------------------------------
 *
 * AllocCharInfo --
 *
 *	Allocate new char info struct. We are using a pool of char info
 *	structs.
 *
 * Results:
 *	The newly allocated struct, or a free char info struct from
 *	pool.
 *
 * Side effects:
 *	May allocate some memory.
 *
 *----------------------------------------------------------------------
 */

static CharInfo *
AllocCharInfo(
    TkText *textPtr)
{
    TextDInfo *dInfoPtr;
    CharInfo *ciPtr;

    assert(textPtr);

    dInfoPtr = textPtr->dInfoPtr;
    if ((ciPtr = dInfoPtr->charInfoPoolPtr)) {
	dInfoPtr->charInfoPoolPtr = dInfoPtr->charInfoPoolPtr->u.next;
    } else {
	ciPtr = (CharInfo *)ckalloc(sizeof(CharInfo));
	DEBUG_ALLOC(tkTextCountNewCharInfo++);
    }

    return ciPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeCharInfo --
 *
 *	Put back given char info to pool.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
FreeCharInfo(
    TkText *textPtr,
    CharInfo *ciPtr)
{
    TextDInfo *dInfoPtr;

    assert(textPtr);
    assert(ciPtr);

    TkBTreeFreeSegment(ciPtr->segPtr);
    dInfoPtr = textPtr->dInfoPtr;
    ciPtr->u.next = dInfoPtr->charInfoPoolPtr;
    dInfoPtr->charInfoPoolPtr = ciPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeBreakIndex --
 *
 *	Compute a break location. If we're in word wrap mode, a break
 *	can occurr after any space character, or at the end of the chunk
 *	if the the next segment (ignoring those with zero size) is not a
 *	character segment.
 *
 * Results:
 *	The computed break location.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
ComputeBreakIndex(
    TCL_UNUSED(TkText *),
    const TkTextDispChunk *chunkPtr,
    TkTextSegment *segPtr,
    int byteOffset,
    TkWrapMode wrapMode,
    TkTextSpaceMode spaceMode)
{
    switch (wrapMode) {
    case TEXT_WRAPMODE_NONE:
	break;
    case TEXT_WRAPMODE_WORD:
    case TEXT_WRAPMODE_CODEPOINT: {
	TkTextSegment *nextPtr;
	const char *p;
	int count;

	if (segPtr->typePtr == &tkTextHyphenType) {
	    return 1;
	}

	if ((int) chunkPtr->numBytes + byteOffset == segPtr->size) {
	    for (nextPtr = segPtr->nextPtr; nextPtr; nextPtr = nextPtr->nextPtr) {
		if (nextPtr->size > 0) {
		    if (!(nextPtr->typePtr->group & (SEG_GROUP_CHAR|SEG_GROUP_HYPHEN))) {
			return chunkPtr->numBytes;
		    }
		    break;
		} else if (nextPtr->typePtr == &tkTextBranchType) {
		    nextPtr = nextPtr->body.branch.nextPtr->nextPtr;
		}
	    }
	}

	count = chunkPtr->numBytes;
	if (chunkPtr->endsWithSyllable) {
	    assert(chunkPtr->numBytes > 0);
	    count -= 1;
	}
	p = segPtr->body.chars + byteOffset + count - 1;

	if (wrapMode == TEXT_WRAPMODE_WORD) {
	    /*
	     * Don't use isspace(); effects are unpredictable (because the result
	     * is locale dependent) and can lead to odd word-wrapping problems on
	     * some platforms. Also don't use Tcl_UniCharIsSpace here either, this
	     * can be used when displaying Markup in read-only mode (except the
	     * non-breaking space), but in text data there is a difference between
	     * ASCII spaces and all other spaces, and this difference must be
	     * visible for the user (line break makes the spaces indistinguishable).
	     * Keep in mind that the text widget will also be used for editing
	     * text. What we actually want is only the ASCII space characters, so
	     * use them explicitly...
	     *
	     * NOTE: don't break at HYPHEN-MINUS character (U+002D), because the
	     * meaning of this character is contextual. The user has to use the
	     * "codepoint" wrap mode if he want's line breaking at hard hyphen
	     * characters.
	     */

	    for ( ; count > 0; --count, --p) {
		switch (*p) {
		case ' ':
		    if (spaceMode == TEXT_SPACEMODE_EXACT) {
			return -1;
		    }
		    /* fallthru */
		case '\t': case '\n': case '\v': case '\f': case '\r':
		    return count;
		}
	    }
	} else {
	    const char *brks;
	    int i;

	    if (*p == '\n') {
		return count; /* catch special case end of line */
	    }

	    /*
	     * Note: it may happen that the chunk only contains the end of line/text
	     * symbol, in this case the break info is NULL.
	     */

	    if ((brks = chunkPtr->brks)) {
		i = count - 1;

		for ( ; i >= 0; --i, --p) {
		    assert(brks[i] <= LINEBREAK_INSIDEACHAR);
		    if (brks[i] == LINEBREAK_ALLOWBREAK) {
			return (*p == ' ' && spaceMode == TEXT_SPACEMODE_EXACT) ? -1 : i + 1;
		    }
		}
	    } else {
		assert(chunkPtr->endOfLineSymbol);
	    }
	}
	break;
    }
    default:
	return chunkPtr->numBytes;
    }

    return -1;
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextCheckDisplayLineConsistency --
 *
 *	This function is called for consistency checking of display line.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	If anything suspicious is found in the display lines, the function
 *	panics.
 *
 *----------------------------------------------------------------------
 */

void
TkTextCheckDisplayLineConsistency(
    const TkText *textPtr)
{
    DLine *dlPtr;

    for (dlPtr = textPtr->dInfoPtr->dLinePtr; dlPtr; dlPtr = dlPtr->nextPtr) {
	if (dlPtr->chunkPtr) {
	    const TkTextLine *linePtr = TkTextIndexGetLine(&dlPtr->index);

	    if (!linePtr->parentPtr || linePtr->parentPtr == (void *) 0x61616161) {
		Tcl_Panic("CheckDisplayLineConsisteny: expired index in display line");
	    }
	}
    }

    for (dlPtr = textPtr->dInfoPtr->savedDLinePtr; dlPtr; dlPtr = dlPtr->nextPtr) {
	if (dlPtr->chunkPtr) {
	    const TkTextLine *linePtr = TkTextIndexGetLine(&dlPtr->index);

	    if (!linePtr->parentPtr || linePtr->parentPtr == (void *) 0x61616161) {
		Tcl_Panic("CheckDisplayLineConsisteny: expired index in saved display line");
	    }
	}
    }

    dlPtr = textPtr->dInfoPtr->cachedDLinePtr;
    if (dlPtr && dlPtr->chunkPtr) {
	const TkTextLine *linePtr = TkTextIndexGetLine(&dlPtr->index);

	if (!linePtr->parentPtr || linePtr->parentPtr == (void *) 0x61616161) {
	    Tcl_Panic("CheckDisplayLineConsisteny: expired index in cached display line");
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * CheckLineMetricConsistency --
 *
 *	This function is called for consistency checking of display line
 *	metric information. Call this function only if all line metrics
 *	are up-to-date.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	If anything suspicious is found in the display line metric information,
 *	the function panics.
 *
 *----------------------------------------------------------------------
 */

static void
CheckLineMetricConsistency(
    const TkText *textPtr)
{
    const TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    unsigned epoch = textPtr->dInfoPtr->lineMetricUpdateEpoch;
    const TkTextLine *lastLinePtr;
    const TkTextLine *linePtr;
    unsigned lineNum = 0;
    unsigned reference;

    assert(textPtr->pixelReference >= 0);

    linePtr = TkBTreeGetStartLine(textPtr);
    lastLinePtr = TkBTreeGetLastLine(textPtr);

    if (textPtr->dInfoPtr->firstLineNo != TkBTreeLinesTo(sharedTextPtr->tree, NULL, linePtr, NULL)) {
	Tcl_Panic("CheckLineMetricConsistency: firstLineNo is not up-to-date");
    }
    if (textPtr->dInfoPtr->lastLineNo != TkBTreeLinesTo(sharedTextPtr->tree, NULL, lastLinePtr, NULL)) {
	Tcl_Panic("CheckLineMetricConsistency: lastLineNo is not up-to-date");
    }

    reference = textPtr->pixelReference;

    if (!lastLinePtr->nextPtr) {
	const TkTextPixelInfo *pixelInfo = lastLinePtr->pixelInfo + reference;

	if (pixelInfo->epoch & PARTIAL_COMPUTED_BIT) {
	    Tcl_Panic("CheckLineMetricConsistency: partial flag shouldn't be set in last line (%d)",
		    TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, lastLinePtr, NULL));
	}
	if (pixelInfo->dispLineInfo) {
	    Tcl_Panic("CheckLineMetricConsistency: last line (%d) should not have display line info",
		    TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, lastLinePtr, NULL));
	}
	if (pixelInfo->height > 0) {
	    Tcl_Panic("CheckLineMetricConsistency: last line (%d) should not have a height",
		    TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, lastLinePtr, NULL));
	}
    }

    while (linePtr != lastLinePtr) {
	const TkTextPixelInfo *pixelInfo = linePtr->pixelInfo + reference;
	const TkTextDispLineInfo *dispLineInfo = pixelInfo->dispLineInfo;
	const TkTextLine *logicalLinePtr = linePtr;
	unsigned logicalLineNum = lineNum;

	if ((pixelInfo->epoch & EPOCH_MASK) != epoch) {
	    Tcl_Panic("CheckLineMetricConsistency: line metric info (%d) is not up-to-date",
		    TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, linePtr, NULL));
	}
	if (pixelInfo->epoch & PARTIAL_COMPUTED_BIT) {
	    Tcl_Panic("CheckLineMetricConsistency: computation of this line (%d) is not yet complete",
		    TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, linePtr, NULL));
	}

	linePtr = linePtr->nextPtr;
	lineNum += 1;

	while (linePtr != lastLinePtr && !linePtr->logicalLine) {
	    const TkTextPixelInfo *pixelInfo1 = linePtr->pixelInfo + reference;

	    if ((pixelInfo1->epoch & EPOCH_MASK) != epoch) {
		Tcl_Panic("CheckLineMetricConsistency: line metric info (%d) is not up-to-date",
			TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, linePtr, NULL));
	    }
	    if (pixelInfo1->epoch & PARTIAL_COMPUTED_BIT) {
		Tcl_Panic("CheckLineMetricConsistency: partial flag shouldn't be set (line %d)",
			TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, linePtr, NULL));
	    }
	    if (pixelInfo1->dispLineInfo) {
		Tcl_Panic("CheckLineMetricConsistency: "
			"merged line (%d) should not have display line info",
			TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, linePtr, NULL));
	    }
	    if (pixelInfo1->height > 0) {
		Tcl_Panic("CheckLineMetricConsistency: merged line (%d) should not have a height",
			TkBTreeLinesTo(textPtr->sharedTextPtr->tree, NULL, linePtr, NULL));
	    }

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

	if (dispLineInfo) {
	    unsigned pixels = 0;
	    unsigned k;

	    if (dispLineInfo->numDispLines == 1) {
		Tcl_Panic("CheckLineMetricConsistency: this line should not have display line info");
	    }
	    for (k = 0; k < dispLineInfo->numDispLines; ++k) {
		const TkTextDispLineEntry *entry = dispLineInfo->entry + k;

		if (k == 0
			&& entry->byteOffset != 0
			/* this check does not work if -startindex is set */
			&& textPtr->startMarker == textPtr->sharedTextPtr->startMarker) {
		    Tcl_Panic("CheckLineMetricConsistency: first display line (line %d.%u) should "
			    "have byte offset zero", logicalLineNum, k);
		}
		if ((entry + 1)->byteOffset <= entry->byteOffset) {
		    Tcl_Panic("CheckLineMetricConsistency: display line (line %d.%u) has invalid byte "
			    "offset %d (previous is %d)", logicalLineNum, k, (entry + 1)->byteOffset,
			    entry->byteOffset);
		}
		if (entry->height == 0) {
		    TkTextIndex index;
		    const TkTextDispLine *dlPtr;

		    /*
		     * Zero height is invalid, except in very seldom cases, if the line
		     * only contains unrealized embedded images/windows. We test this
		     * explicitly, the corresponding display line contains this information.
		     */

		    TkTextIndexClear(&index, (TkText *) textPtr);
		    TkTextIndexSetToStartOfLine2(&index, (TkTextLine *) logicalLinePtr);
		    TkrTextIndexForwBytes(textPtr, &index, entry->byteOffset, &index);
		    dlPtr = FindDLine((TkText *) textPtr, textPtr->dInfoPtr->dLinePtr, &index);
		    assert(dlPtr);

		    if (!dlPtr->invisible) {
			Tcl_Panic("CheckLineMetricConsistency: display line (%d.%u) has zero height",
				logicalLineNum, k);
		    }
		}
		pixels += entry->height;
	    }
	    if (pixels != pixelInfo->height) {
		Tcl_Panic("CheckLineMetricConsistency: sum of display line pixels is wrong (line %d)",
			logicalLineNum);
	    }
	}
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextCheckLineMetricUpdate --
 *
 *	This function is called for consistency checking of display line
 *	metric update information.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	If anything suspicious is found in the display line metric update
 *	information, the function panics.
 *
 *----------------------------------------------------------------------
 */

void
TkTextCheckLineMetricUpdate(
    const TkText *textPtr)
{
    const TkRangeList *ranges;
    const TkRange *range;
    TkTextBTree tree;
    unsigned epoch;
    int n, total;

    assert(textPtr);

    if (!textPtr->sharedTextPtr->allowUpdateLineMetrics) {
	return;
    }
    if (!textPtr->endMarker->sectionPtr || !textPtr->startMarker->sectionPtr) {
	/*
	 * Called inside unlink of start/end marker, in this case we cannot check
	 * (and we don't need a check here).
	 */
	return;
    }

    ranges = textPtr->dInfoPtr->lineMetricUpdateRanges;
    tree = textPtr->sharedTextPtr->tree;
    total = TkrBTreeNumLines(tree, textPtr);

    if (!TkRangeListIsEmpty(ranges) && TkRangeListHigh(ranges) >= total) {
	Tcl_Panic("TkTextCheckLineMetricUpdate: line %d is out of range (max=%d)\n",
		TkRangeListHigh(ranges), total);
    }

    range = TkRangeListFirst(ranges);
    epoch = textPtr->dInfoPtr->lineMetricUpdateEpoch;

    for (n = 0; n < total - 1; ++n) {
	const TkTextPixelInfo *pixelInfo;

	if (range && range->low == n) {
	    n = range->high;
	    range = TkRangeListNext(ranges, range);
	    continue;
	}

	pixelInfo = TkBTreeLinePixelInfo(textPtr, TkBTreeFindLine(tree, textPtr, n));

	if (pixelInfo->epoch && (pixelInfo->epoch & EPOCH_MASK) != epoch) {
	    Tcl_Panic("TkTextCheckLineMetricUpdate: line %d is not up-to-date\n", n);
	}
	if (pixelInfo->epoch & PARTIAL_COMPUTED_BIT) {
	    Tcl_Panic("TkTextCheckLineMetricUpdate: line metric computation (line %d) is not "
		    "yet complete\n", n);
	}
    }
}

/*
 *---------------------------------------------------------------------------
 *
 * CharChunkMeasureChars --
 *
 *	Determine the number of characters from a char chunk that will fit in
 *	the given horizontal span.
 *
 *	This is the same as MeasureChars (which see), but in the context of a
 *	char chunk, i.e. on a higher level of abstraction. Use this function
 *	whereever possible instead of plain MeasureChars, so that the right
 *	context is used automatically.
 *
 * Results:
 *	The return value is the number of bytes from the range of start to end
 *	in source that fit in the span given by startX and maxX. *nextXPtr is
 *	filled in with the x-coordinate at which the first character that
 *	didn't fit would be drawn, if it were to be drawn.
 *
 * Side effects:
 *	None.
 *--------------------------------------------------------------
 */

static Tcl_Size
CharChunkMeasureChars(
    TkTextDispChunk *chunkPtr,	/* Chunk from which to measure. */
    const char *chars,		/* Chars to use, instead of the chunk's own. Used by the layoutproc
				 * during chunk setup. All other callers use NULL. Not NUL-terminated. */
    int charsLen,		/* Length of the "chars" parameter. */
    int start, int end,		/* The range of chars to measure inside the chunk (or inside the
				 * additional chars). */
    int startX,			/* Starting x coordinate where the measured span will begin. */
    int maxX,			/* Maximum pixel width of the span. May be -1 for unlimited. */
    TkTextSpaceMode spaceMode,	/* How to handle displaying spaces. Must be TEXT_SPACEMODE_NONE,
				 * TEXT_SPACEMODE_EXACT, or TEXT_SPACEMODE_TRIM. */
    int flags,			/* Flags to pass to MeasureChars. */
    int *nextXPtr)		/* The function puts the newly calculated right border x-position of
				 * the span here; can be NULL. */
{
    Tk_Font tkfont = chunkPtr->stylePtr->sValuePtr->tkfont;
    CharInfo *ciPtr = (CharInfo *)chunkPtr->clientData;
    int fit, rangeStart;

#ifdef TK_LAYOUT_WITH_BASE_CHUNKS

    const TkTextDispChunk *baseChunkPtr = chunkPtr->baseChunkPtr;

    assert(baseChunkPtr);

    if (!chars) {
	const Tcl_DString *baseChars = &baseChunkPtr->baseChars;

	chars = Tcl_DStringValue(baseChars);
	charsLen = Tcl_DStringLength(baseChars);
	start += ciPtr->baseOffset;
	if (end == -1) {
	    assert(ciPtr->numBytes >= (Tcl_Size)chunkPtr->wrappedAtSpace);
	    end = ciPtr->baseOffset + ciPtr->numBytes - chunkPtr->wrappedAtSpace;
	} else {
	    end += ciPtr->baseOffset;
	}
	if (chunkPtr->wrappedAtSpace) {
	    assert(charsLen >= 1);
	    charsLen -= 1;
	}
    }

    if ((Tcl_Size)start == ciPtr->baseOffset) {
	/*
	 * This is a very frequent case, and MeasureChars() is not needed here.
	 */

	startX -= chunkPtr->x - baseChunkPtr->x;
    } else {
	int widthUntilStart;
	MeasureChars(tkfont, chars, charsLen, 0, start, 0, -1, 0, &widthUntilStart);
	startX -= widthUntilStart;
    }

    rangeStart = 0;

#else

    rangeStart = start;

    if (!chars) {
	chars = ciPtr->u.chars;
	charsLen = ciPtr->numBytes;
    }

#endif

    if (end == -1) {
	end = charsLen;
    }

    if (spaceMode == TEXT_SPACEMODE_TRIM && end > rangeStart) {
	/*
	 * Don't measure trimmed spaces.
	 */
	if (chars[end] == '\n') {
	    end -= 1;
	    while (end > rangeStart && IsBlank(chars[end - 1])) {
		end -= 1;
	    }
	} else if (IsBlank(chars[end - 1])) {
	    end -= 1;
	    while (end > rangeStart && IsBlank(chars[end - 1])) {
		end -= 1;
	    }
	    end += 1;
	}
    }

    fit = MeasureChars(tkfont, chars, charsLen, rangeStart, end - rangeStart,
	    startX, maxX, flags, nextXPtr);

    return MAX(0, fit - start);
}

/*
 *--------------------------------------------------------------
 *
 * TkTextCharLayoutProc --
 *
 *	This function is the "layoutProc" for character segments.
 *
 * Results:
 *	If there is something to display for the chunk then a non-zero value
 *	is returned and the fields of chunkPtr will be filled in (see the
 *	declaration of TkTextDispChunk in tkText.h for details). If zero is
 *	returned it means that no characters from this chunk fit in the
 *	window. If -1 is returned it means that this segment just doesn't need
 *	to be displayed (never happens for text).
 *
 * Side effects:
 *	Memory is allocated to hold additional information about the chunk.
 *
 *--------------------------------------------------------------
 */

static int
EndsWithSyllable(
    TkTextSegment *segPtr)
{
    if (segPtr->typePtr->group == SEG_GROUP_CHAR) {
	for (segPtr = segPtr->nextPtr; segPtr; segPtr = segPtr->nextPtr) {
	    switch (segPtr->typePtr->group) {
	    case SEG_GROUP_MARK:
		break;
	    case SEG_GROUP_HYPHEN:
		return 1;
	    case SEG_GROUP_BRANCH:
		if (segPtr->typePtr == &tkTextBranchType) {
		    segPtr = segPtr->body.branch.nextPtr;
		    break;
		}
		/* fallthru */
	    default:
		return 0;
	    }
	}
    }
    return 0;
}

int
TkTextCharLayoutProc(
    const TkTextIndex *indexPtr,/* Index of first character to lay out (corresponds to segPtr and
				 * offset). */
    TkTextSegment *segPtr,	/* Segment being layed out. */
    Tcl_Size byteOffset,		/* Byte offset within segment of first character to consider. */
    int maxX,			/* Chunk must not occupy pixels at this position or higher. */
    Tcl_Size maxBytes,		/* Chunk must not include more than this many characters. */
    int noCharsYet,		/* 'true' means no characters have been assigned to this display
				 * line yet. */
    TkWrapMode wrapMode,	/* How to handle line wrapping: TEXT_WRAPMODE_CHAR, TEXT_WRAPMODE_NONE,
				 * TEXT_WRAPMODE_WORD, or TEXT_WRAPMODE_CODEPOINT. */
    TkTextSpaceMode spaceMode,	/* How to handle displaying spaces. Must be TEXT_SPACEMODE_NONE,
				 * TEXT_SPACEMODE_EXACT, or TEXT_SPACEMODE_TRIM. */
    TkTextDispChunk *chunkPtr)	/* Structure to fill in with information about this chunk. The x
				 * field has already been set by the caller. */
{
    Tk_Font tkfont;
    int nextX, bytesThatFit;
    Tk_FontMetrics fm;
    CharInfo *ciPtr;
    char const *p;

    assert(indexPtr->textPtr);
    assert(chunkPtr->clientData);

    /*
     * Figure out how many characters will fit in the space we've got. Include
     * the next character, even though it won't fit completely, if any of the
     * following is true:
     *
     *	 (a) the chunk contains no characters and the display line contains no
     *	     characters yet (i.e. the line isn't wide enough to hold even a
     *	     single character).
     *
     *	 (b) at least one pixel of the character is visible, we have not
     *	     already exceeded the character limit, and the next character is a
     *	     white space character.
     */

    tkfont = chunkPtr->stylePtr->sValuePtr->tkfont;
    ciPtr = (CharInfo *)chunkPtr->clientData;
    chunkPtr->layoutProcs = &layoutCharProcs;
    p = segPtr->body.chars + byteOffset;

    bytesThatFit = CharChunkMeasureChars(chunkPtr, ciPtr->u.chars, ciPtr->baseOffset + maxBytes,
	    ciPtr->baseOffset, -1, chunkPtr->x, maxX, spaceMode, TK_ISOLATE_END, &nextX);

    if (bytesThatFit < maxBytes) {
	if (bytesThatFit == 0 && noCharsYet) {
	    int chLen;

#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;
	    chLen = TkUtfToUniChar(p, &ch);
#else
	    /*
	     * Proper implementation for UTF-8 strings:
	     */

	    Tcl_UniChar ch;
	    chLen = Tcl_UtfToUniChar(p, &ch);
#endif

	    /*
	     * At least one character should be contained in current display line.
	     */

	    bytesThatFit = CharChunkMeasureChars(chunkPtr, ciPtr->u.chars, ciPtr->baseOffset + chLen,
		    ciPtr->baseOffset, -1, chunkPtr->x, -1, spaceMode, 0, &nextX);
	}
	if (spaceMode == TEXT_SPACEMODE_TRIM) {
	    while (IsBlank(p[bytesThatFit])) {
		bytesThatFit += 1;
	    }
	}
	if (p[bytesThatFit] == '\n') {
	    /*
	     * A newline character takes up no space, so if the previous
	     * character fits then so does the newline.
	     */

	    bytesThatFit += 1;
	} else if (spaceMode == TEXT_SPACEMODE_NONE
		&& nextX <= maxX
		&& ((1 << wrapMode) & ((1 << TEXT_WRAPMODE_WORD) | (1 << TEXT_WRAPMODE_CODEPOINT)))
		&& IsBlank(p[bytesThatFit])
		&& !(bytesThatFit == 0
		    && chunkPtr->prevCharChunkPtr
		    && chunkPtr->prevCharChunkPtr->wrappedAtSpace)) {
	    /*
	     * Space characters are funny, in that they are considered to fit at the end
	     * of the line. Just give the space character whatever space is left.
	     */

	    nextX = maxX;
	    bytesThatFit += 1;

	    /* Do not wrap next chunk in this line. */
	    chunkPtr->wrappedAtSpace = 1;
	}
	if (bytesThatFit == 0) {
	    return 0;
	}
    }

    Tk_GetFontMetrics(tkfont, &fm);

    /*
     * Fill in the chunk structure and allocate and initialize a CharInfo structure. If the
     * last character is a newline then don't bother to display it.
     */

    chunkPtr->endsWithSyllable =
	    p[bytesThatFit] == '\0' && indexPtr->textPtr->hyphenate && EndsWithSyllable(segPtr);
    chunkPtr->numBytes = bytesThatFit;
    chunkPtr->segByteOffset = byteOffset;
    chunkPtr->minAscent = fm.ascent + chunkPtr->stylePtr->sValuePtr->offset;
    chunkPtr->minDescent = fm.descent - chunkPtr->stylePtr->sValuePtr->offset;
    chunkPtr->minHeight = 0;
    chunkPtr->width = nextX - chunkPtr->x;
    chunkPtr->breakIndex =
	    ComputeBreakIndex(indexPtr->textPtr, chunkPtr, segPtr, byteOffset, wrapMode, spaceMode);

    ciPtr->numBytes = chunkPtr->numBytes;
    return 1;
}

/*
 *--------------------------------------------------------------
 *
 * CharDisplayProc --
 *
 *	This function is called to display a character chunk on the screen or
 *	in an off-screen pixmap.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Graphics are drawn.
 *
 *--------------------------------------------------------------
 */

static void
CharDisplayProc(
    TkText *textPtr,
    TkTextDispChunk *chunkPtr,	/* Chunk that is to be drawn. */
    int x,			/* X-position in dst at which to draw this chunk (may differ from
				 * the x-position in the chunk because of scrolling). */
    int y,			/* Y-position at which to draw this chunk in dst. */
    TCL_UNUSED(int),			/* Total height of line. */
    int baseline,		/* Offset of baseline from y. */
    Display *display,		/* Display to use for drawing. */
    Drawable dst,		/* Pixmap or window in which to draw chunk. */
    TCL_UNUSED(int))		/* Y-coordinate in text window that corresponds to y. */
{
    if (chunkPtr->width > 0 && x + chunkPtr->width > 0) {
	/* The chunk has displayable content, and is not off-screen. */
	DisplayChars(textPtr, chunkPtr, x, y, baseline, display, dst);
    }
}

/*
 *--------------------------------------------------------------
 *
 * CharUndisplayProc --
 *
 *	This function is called when a character chunk is no longer going to
 *	be displayed. It frees up resources that were allocated to display the
 *	chunk.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Memory and other resources get freed.
 *
 *--------------------------------------------------------------
 */

static void
CharUndisplayProc(
    TkText *textPtr,		/* Overall information about text widget. */
    TkTextDispChunk *chunkPtr)	/* Chunk that is about to be freed. */
{
    CharInfo *ciPtr = (CharInfo *)chunkPtr->clientData;

    if (!ciPtr) {
	return;
    }

#ifdef TK_LAYOUT_WITH_BASE_CHUNKS
    {
	TkTextDispChunk *baseChunkPtr = chunkPtr->baseChunkPtr;

	if (chunkPtr == baseChunkPtr) {
	    /*
	     * Base chunks are undisplayed first, when DLines are freed or
	     * partially freed, so this makes sure we don't access their data
	     * any more.
	     */

	    Tcl_DStringFree(&baseChunkPtr->baseChars);
	    DEBUG_ALLOC(tkTextCountDestroyBaseChars++);
	} else if (baseChunkPtr && ciPtr->numBytes > 0) {
	    /*
	     * When other char chunks are undisplayed, drop their characters
	     * from the base chunk. This usually happens, when they are last
	     * in a line and need to be re-layed out.
	     */

	    assert(ciPtr->baseOffset + ciPtr->numBytes == Tcl_DStringLength(&baseChunkPtr->baseChars));
	    Tcl_DStringSetLength(&baseChunkPtr->baseChars, ciPtr->baseOffset);
	    baseChunkPtr->baseWidth = 0;
	}

	if (chunkPtr->prevPtr) {
	    chunkPtr->x -= chunkPtr->prevPtr->xAdjustment;
	}

	chunkPtr->baseChunkPtr = NULL;
    }
#endif

    FreeCharInfo(textPtr, ciPtr);
    chunkPtr->clientData = NULL;
}

/*
 *--------------------------------------------------------------
 *
 * HyphenUndisplayProc --
 *
 *	This function is called when a hyphen chunk is no longer going to
 *	be displayed. It frees up resources that were allocated to display the
 *	chunk.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Memory and other resources get freed.
 *
 *--------------------------------------------------------------
 */

static void
HyphenUndisplayProc(
    TCL_UNUSED(TkText *),		/* Overall information about text widget. */
    TkTextDispChunk *chunkPtr)	/* Chunk that is about to be freed. */
{
    TkTextSegment *hyphenPtr = (TkTextSegment *)chunkPtr->clientData;

    if (hyphenPtr) {
	TkBTreeFreeSegment(hyphenPtr);
    }
    chunkPtr->clientData = NULL;
}

/*
 *--------------------------------------------------------------
 *
 * DisplayChars --
 *
 *	This function is called to display characters on the screen or
 *	in an off-screen pixmap.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Graphics are drawn.
 *
 *--------------------------------------------------------------
 */

static GC
GetForegroundGC(
    const TkText *textPtr,
    const TkTextDispChunk *chunkPtr)
{
    const TkTextSegment *segPtr = ((const CharInfo *) chunkPtr->clientData)->segPtr;

    assert(chunkPtr->stylePtr);
    assert(chunkPtr->stylePtr->refCount > 0);

    if (segPtr->typePtr == &tkTextHyphenType) {
	if (chunkPtr->stylePtr->hyphenGC != NULL) {
	    return chunkPtr->stylePtr->hyphenGC;
	}
    } else if (segPtr == textPtr->dInfoPtr->endOfLineSegPtr) {
	if (chunkPtr->stylePtr->eolGC != NULL) {
	    return chunkPtr->stylePtr->eolGC;
	}
    } else if (segPtr == textPtr->dInfoPtr->endOfTextSegPtr) {
	if (chunkPtr->stylePtr->eotGC != NULL) {
	    return chunkPtr->stylePtr->eotGC;
	}
    }
    return chunkPtr->stylePtr->fgGC;
}

#ifdef TK_DRAW_IN_CONTEXT
# if defined(_WIN32) || defined(__UNIX__)

/*****************************************************************************
 * We need this function for the emulation of context drawing, in this way the
 * context support can be pre-tested on platforms without sub-pixel accuracy.
 *****************************************************************************/

static void
DrawCharsInContext(
    Display *display,	/* Display on which to draw. */
    Drawable drawable,	/* Window or pixmap in which to draw. */
    GC gc,		/* Graphics context for drawing characters. */
    Tk_Font tkfont,	/* Font in which characters will be drawn; must be the same as font used
			 * in GC. */
    const char *source,	/* UTF-8 string to be displayed. Need not be nul terminated. All Tk
			 * meta-characters (tabs, control characters, and newlines) should be
			 * stripped out of the string that is passed to this function. If they are
			 * not stripped out, they will be displayed as regular printing characters. */
    Tcl_Size numBytes,	/* Number of bytes in string. */
    Tcl_Size rangeStart,	/* Index of first byte to draw. */
    Tcl_Size rangeLength,	/* Length of range to draw in bytes. */
    int x, int y,	/* Coordinates at which to place origin of the whole (not just the range)
			 * string when drawing. */
    int xOffset)	/* Offset to x-coordinate, required for emulation of context drawing. */
{
    Tk_DrawChars(display, drawable, gc, tkfont, source + rangeStart, rangeLength, xOffset, y);
}

# else /* if !(defined(_WIN32) || defined(__UNIX__)) */

static void
DrawCharsInContext(
    Display *display,	/* Display on which to draw. */
    Drawable drawable,	/* Window or pixmap in which to draw. */
    GC gc,		/* Graphics context for drawing characters. */
    Tk_Font tkfont,	/* Font in which characters will be drawn; must be the same as font used
			 * in GC. */
    const char *source,	/* UTF-8 string to be displayed. Need not be nul terminated. All Tk
			 * meta-characters (tabs, control characters, and newlines) should be
			 * stripped out of the string that is passed to this function. If they are
			 * not stripped out, they will be displayed as regular printing characters. */
    Tcl_Size numBytes,	/* Number of bytes in string. */
    Tcl_Size rangeStart,	/* Index of first byte to draw. */
    Tcl_Size rangeLength,	/* Length of range to draw in bytes. */
    int x, int y,	/* Coordinates at which to place origin of the whole (not just the range)
			 * string when drawing. */
    TCL_UNUSED(int))	/* Offset to x-coordinate, not needed here. */
{
    TkpDrawCharsInContext(display, drawable, gc, tkfont,
	    source, numBytes, rangeStart, rangeLength, x, y);
}

# endif /* defined(_WIN32) || defined(__UNIX__) */

static void
DrawChars(
    TkText *textPtr,
    TkTextDispChunk *chunkPtr,	/* Display the content of this chunk. */
    int x,			/* X-position in dst at which to draw. */
    int y,			/* Y-position at which to draw. */
    TCL_UNUSED(int),		/* Offset in x-direction. */
    int offsetBytes,		/* Offset in display string. */
    Display *display,		/* Display to use for drawing. */
    Drawable dst)		/* Pixmap or window in which to draw chunk. */
{
    const TkTextDispChunk *baseChunkPtr;
    Tcl_Size numBytes;

    assert(chunkPtr->baseChunkPtr);

    baseChunkPtr = chunkPtr->baseChunkPtr;
    numBytes = Tcl_DStringLength(&baseChunkPtr->baseChars);

    if (numBytes > offsetBytes) {
	const char *string;
	const CharInfo *ciPtr;
	const TextStyle *stylePtr;
	const StyleValues *sValuePtr;
	int xDisplacement, start, len;
	GC fgGC;

	string = Tcl_DStringValue(&baseChunkPtr->baseChars);
	ciPtr = (const CharInfo *)chunkPtr->clientData;
	start = ciPtr->baseOffset + offsetBytes;
	len = ciPtr->numBytes - offsetBytes;

	assert(ciPtr->numBytes >= (Tcl_Size)offsetBytes);

	if (len == 0 || (string[start + len - 1] == '\t' && --len == 0)) {
	    return;
	}

	stylePtr = chunkPtr->stylePtr;
	sValuePtr = stylePtr->sValuePtr;
	ciPtr = (const CharInfo *)chunkPtr->clientData;
	xDisplacement = x - chunkPtr->x;
	fgGC = GetForegroundGC(textPtr, chunkPtr);

	/*
	 * Draw the text, underline, and overstrike for this chunk.
	 */

	DrawCharsInContext(display, dst, fgGC, sValuePtr->tkfont, string, numBytes,
		start, len, baseChunkPtr->x + xDisplacement, y - sValuePtr->offset,
		chunkPtr->x + textPtr->dInfoPtr->x);

	if (sValuePtr->underline) {
	    TkUnderlineCharsInContext(display, dst, stylePtr->ulGC, sValuePtr->tkfont, string,
		    numBytes, baseChunkPtr->x + xDisplacement, y - sValuePtr->offset,
		    start, start + len);
	}
	if (sValuePtr->overstrike) {
	    Tk_FontMetrics fm;

	    Tk_GetFontMetrics(sValuePtr->tkfont, &fm);
	    TkUnderlineCharsInContext(display, dst, stylePtr->ovGC, sValuePtr->tkfont, string,
		    numBytes, baseChunkPtr->x + xDisplacement,
		    y - sValuePtr->offset - fm.descent - (fm.ascent*3)/10,
		    start, start + len);
	}
    }
}

#else /* if !TK_DRAW_IN_CONTEXT */

static void
DrawChars(
    TkText *textPtr,
    TkTextDispChunk *chunkPtr,	/* Display the content of this chunk. */
    TCL_UNUSED(int),			/* X-position in dst at which to draw. */
    int y,			/* Y-position at which to draw. */
    int offsetX,		/* Offset from x. */
    int offsetBytes,		/* Offset in display string. */
    Display *display,		/* Display to use for drawing. */
    Drawable dst)		/* Pixmap or window in which to draw chunk. */
{
    const CharInfo *ciPtr;
    Tcl_Size numBytes;

    ciPtr = (const CharInfo *)chunkPtr->clientData;
    numBytes = ciPtr->numBytes;

    assert((Tcl_Size)offsetBytes >= ciPtr->baseOffset);

    if (numBytes > offsetBytes) {
	const TextStyle *stylePtr = chunkPtr->stylePtr;

	if (stylePtr->fgGC != NULL) {
	    const StyleValues *sValuePtr;
	    const char *string;
	    GC fgGC;

	    string = ciPtr->u.chars + offsetBytes;
	    numBytes -= offsetBytes;

	    if (string[numBytes - 1] == '\t' && --numBytes == 0) {
		return;
	    }

	    sValuePtr = stylePtr->sValuePtr;
	    fgGC = GetForegroundGC(textPtr, chunkPtr);

	    /*
	     * Draw the text, underline, and overstrike for this chunk.
	     */

	    Tk_DrawChars(display, dst, fgGC, sValuePtr->tkfont, string, numBytes,
		    offsetX, y - sValuePtr->offset);
	    if (sValuePtr->underline) {
		Tk_UnderlineChars(display, dst, stylePtr->ulGC, sValuePtr->tkfont,
			string, offsetX, y - sValuePtr->offset, 0, numBytes);

	    }
	    if (sValuePtr->overstrike) {
		Tk_FontMetrics fm;

		Tk_GetFontMetrics(sValuePtr->tkfont, &fm);
		Tk_UnderlineChars(display, dst, stylePtr->ovGC, sValuePtr->tkfont, string, offsetX,
			y - sValuePtr->offset - fm.descent - (fm.ascent*3)/10, 0, numBytes);
	    }
	}
    }
}

#endif /* TK_DRAW_IN_CONTEXT */

static void
DisplayChars(
    TkText *textPtr,
    TkTextDispChunk *chunkPtr,	/* Display the content of this chunk. */
    int x,			/* X-position in dst at which to draw. */
    int y,			/* Y-position at which to draw. */
    int baseline,		/* Offset of baseline from y. */
    Display *display,		/* Display to use for drawing. */
    Drawable dst)		/* Pixmap or window in which to draw chunk. */
{
    const TextStyle *stylePtr = chunkPtr->stylePtr;
    int offsetBytes, offsetX;

    assert(!stylePtr->sValuePtr->elide);

    if (stylePtr->fgGC == NULL) {
	return;
    }

    /*
     * If the text sticks out way to the left of the window, skip over the
     * characters that aren't in the visible part of the window. This is
     * essential if x is very negative (such as less than 32K); otherwise
     * overflow problems will occur in servers that use 16-bit arithmetic,
     * like X.
     */

    offsetX = x;
    offsetBytes = (x >= 0) ? CharChunkMeasureChars(chunkPtr, NULL, 0, 0, -1, x, 0,
	    textPtr->spaceMode, 0, &offsetX) : 0;
    DrawChars(textPtr, chunkPtr, x, y + baseline, offsetX, offsetBytes, display, dst);
}

#ifndef NDEBUG
/*
 *--------------------------------------------------------------
 *
 * TkpTextPrintDispChunk --
 *
 *	This function is for debugging only, printing the content of
 *	the given tag display chunk.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

void
TkpTextPrintDispChunk(
    const TkText *textPtr,
    const TkTextDispChunk *chunkPtr)
{
    const DLine *dlPtr;
    int x, y, width, height;

    switch (chunkPtr->layoutProcs->type) {
    case TEXT_DISP_CHAR:
	fprintf(stdout, "CHAR=");
	if (chunkPtr->clientData) {
	    const CharInfo *ciPtr = (const CharInfo *) chunkPtr->clientData;
	    Tcl_Size i;

	    for (i = 0; i < ciPtr->numBytes; ++i) {
		char c = ciPtr->u.chars[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;
		}
	    }
	} else {
	    fprintf(stdout, "<not yet displayed>");
	}
	break;

    case TEXT_DISP_HYPHEN: fprintf(stdout, "HYPHEN"); break;
    case TEXT_DISP_IMAGE:  fprintf(stdout, "IMAGE"); break;
    case TEXT_DISP_WINDOW: fprintf(stdout, "WINDOW"); break;
    case TEXT_DISP_ELIDED: fprintf(stdout, "ELIDED"); break;
    case TEXT_DISP_CURSOR: fprintf(stdout, "CURSOR"); break;
    }

    dlPtr = chunkPtr->dlPtr;
    x = chunkPtr->x + textPtr->dInfoPtr->x;
    y = dlPtr->y + dlPtr->spaceAbove;
    width = chunkPtr->width;
    height = dlPtr->height - dlPtr->spaceAbove - dlPtr->spaceBelow;
    fprintf(stdout, " [%d,%d-%d,%d]\n", x, y, x + width, y + height);
}
#endif /* !NDEBUG */

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 105
 * End:
 * vi:set ts=8 sw=4:
 */