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

/*
 * To do:
 *
 * 1) Fix scroll unit round off errors.
 *
 * 2) Better error checking.
 *
 * 3) Use html format.
 *
 * 4) The dimension of cavities using -relwidth and -relheight
 *    should be 0 when computing initial estimates for the size
 *    of the virtual text.
 */

#include "bltInt.h"

#ifndef NO_HTEXT
#include <bltChain.h>
#include <bltHash.h>
#include "bltTile.h"
 
#include <sys/stat.h>
#include <X11/Xatom.h>

#define DEF_LINES_ALLOC 512	/* Default block of lines allocated */
#define CLAMP(val,low,hi)	\
	(((val) < (low)) ? (low) : ((val) > (hi)) ? (hi) : (val))

/*
 * Justify option values
 */
typedef enum {
    JUSTIFY_CENTER, JUSTIFY_TOP, JUSTIFY_BOTTOM
} Justify;

extern Tk_CustomOption bltFillOption;
extern Tk_CustomOption bltPadOption;
extern Tk_CustomOption bltDistanceOption;
extern Tk_CustomOption bltTileOption;

static int StringToWidth _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, Tk_Window tkwin, char *string, char *widgRec,
	int flags));
static int StringToHeight _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, Tk_Window tkwin, char *string, char *widgRec,
	int flags));
static char *WidthHeightToString _ANSI_ARGS_((ClientData clientData,
	Tk_Window tkwin, char *widgRec, int offset, Tcl_FreeProc **freeProc));

static Tk_CustomOption widthOption =
{
    StringToWidth, WidthHeightToString, (ClientData)0
};

static Tk_CustomOption heightOption =
{
    StringToHeight, WidthHeightToString, (ClientData)0
};

static int StringToJustify _ANSI_ARGS_((ClientData clientData,
	Tcl_Interp *interp, Tk_Window tkwin, char *string, char *widgRec,
	int offset));
static char *JustifyToString _ANSI_ARGS_((ClientData clientData,
	Tk_Window tkwin, char *widgRec, int offset, Tcl_FreeProc **freeProcPtr));

static Tk_CustomOption justifyOption =
{
    StringToJustify, JustifyToString, (ClientData)0
};


static void EmbeddedWidgetGeometryProc _ANSI_ARGS_((ClientData, Tk_Window));
static void EmbeddedWidgetCustodyProc _ANSI_ARGS_((ClientData, Tk_Window));

static Tk_GeomMgr htextMgrInfo =
{
    "htext",			/* Name of geometry manager used by winfo */
    EmbeddedWidgetGeometryProc,	/* Procedure to for new geometry requests */
    EmbeddedWidgetCustodyProc,	/* Procedure when window is taken away */
};


/*
 * Line --
 *
 *	Structure to contain the contents of a single line of text and
 *	the widgets on that line.
 *
 * 	Individual lines are not configurable, although changes to the
 * 	size of widgets do effect its values.
 */
typedef struct {
    int offset;			/* Offset of line from y-origin (0) in
				 * world coordinates */
    int baseline;		/* Baseline y-coordinate of the text */
    short int width, height;	/* Dimensions of the line */
    int textStart, textEnd;	/* Start and end indices of characters
				 * forming the line in the text array */
    Blt_Chain *chainPtr;	/* Chain of embedded widgets on the line of 
				 * text */
} Line;

typedef struct {
    int textStart;
    int textEnd;
} Segment;

typedef struct {
    int x, y;
} Position;

/*
 * Hypertext widget.
 */
typedef struct {
    Tk_Window tkwin;		/* Window that embodies the widget.
                                 * NULL means that the window has been
                                 * destroyed but the data structures
                                 * haven't yet been cleaned up.*/
    Display *display;		/* Display containing widget; needed,
                                 * among other things, to release
                                 * resources after tkwin has already
                                 * gone away. */
    Tcl_Interp *interp;		/* Interpreter associated with widget. */

    Tcl_Command cmdToken;	/* Token for htext's widget command. */
    int flags;

    /* User-configurable fields */

    XColor *normalFg, *normalBg;
    Tk_Font font;		/* Font for normal text. May affect the size
				 * of the viewport if the width/height is
				 * specified in columns/rows */
    GC drawGC;			/* Graphics context for normal text */
    Blt_Tile tile;
    int tileOffsetPage;		/* Set tile offset to top of page instead
				 * of toplevel window */
    GC fillGC;			/* GC for clearing the window in the
				 * designated background color. The
				 * background color is the foreground
				 * attribute in GC.  */

    int nRows, nColumns;	/* # of characters of the current font
				 * for a row or column of the viewport.
				 * Used to determine the width and height
				 * of the text window (i.e. viewport) */
    int reqWidth, reqHeight;	/* Requested dimensions of the viewport */
    int maxWidth, maxHeight;	/* Maximum dimensions allowed for the viewport,
				 * regardless of the size of the text */

    Tk_Cursor cursor;		/* X Cursor */

    char *fileName;		/* If non-NULL, indicates the name of a
				 * hypertext file to be read into the widget.
				 * If NULL, the *text* field is considered
				 * instead */
    char *text;			/* Hypertext to be loaded into the widget. This
				 * value is ignored if *fileName* is non-NULL */
    int specChar;		/* Special character designating a TCL
			         * command block in a hypertext file. */
    int leader;			/* # of pixels between lines */

    char *yScrollCmdPrefix;	/* Name of vertical scrollbar to invoke */
    int yScrollUnits;		/* # of pixels per vertical scroll */
    char *xScrollCmdPrefix;	/* Name of horizontal scroll bar to invoke */
    int xScrollUnits;		/* # of pixels per horizontal scroll */

    int reqLineNum;		/* Line requested by "goto" command */

    /*
     * The view port is the width and height of the window and the
     * origin of the viewport (upper left corner) in world coordinates.
     */
    int worldWidth, worldHeight;/* Size of view text in world coordinates */
    int xOffset, yOffset;	/* Position of viewport in world coordinates */

    int pendingX, pendingY;	/* New upper-left corner (origin) of
				 * the viewport (not yet posted) */

    int first, last;		/* Range of lines displayed */

    int lastWidth, lastHeight;
    /* Last known size of the window: saved to
				 * recognize when the viewport is resized. */

    Blt_HashTable widgetTable;	/* Table of embedded widgets. */

    /*
     * Selection display information:
     */
    Tk_3DBorder selBorder;	/* Border and background color */
    int selBorderWidth;		/* Border width */
    XColor *selFgColor;		/* Text foreground color */
    GC selectGC;		/* GC for drawing selected text */
    int selAnchor;		/* Fixed end of selection
			         * (i.e. "selection to" operation will
			         * use this as one end of the selection).*/
    int selFirst;		/* The index of first character in the
				 * text array selected */
    int selLast;		/* The index of the last character selected */
    int exportSelection;	/* Non-zero means to export the internal text
				 * selection to the X server. */
    char *takeFocus;

    /*
     * Scanning information:
     */
    XPoint scanMark;		/* Anchor position of scan */
    XPoint scanPt;		/* x,y position where the scan started. */

    char *charArr;		/* Pool of characters representing the text
				 * to be displayed */
    int nChars;			/* Length of the text pool */

    Line *lineArr;		/* Array of pointers to text lines */
    int nLines;			/* # of line entered into array. */
    int arraySize;		/* Size of array allocated. */

} HText;

/*
 * Bit flags for the hypertext widget:
 */
#define REDRAW_PENDING	 (1<<0)	/* A DoWhenIdle handler has already
				 * been queued to redraw the window */
#define IGNORE_EXPOSURES (1<<1)	/* Ignore exposure events in the text
				 * window.  Potentially many expose
				 * events can occur while rearranging
				 * embedded widgets during a single call to
				 * the DisplayText.  */

#define REQUEST_LAYOUT 	(1<<4)	/* Something has happened which
				 * requires the layout of text and
				 * embedded widget positions to be
				 * recalculated.  The following
				 * actions may cause this:
				 *
				 * 1) the contents of the hypertext
				 *    has changed by either the -file or
				 *    -text options.
				 *
				 * 2) a text attribute has changed
				 *    (line spacing, font, etc)
				 *
				 * 3) a embedded widget has been resized or
				 *    moved.
				 *
				 * 4) a widget configuration option has
				 *    changed.
				 */
#define TEXT_DIRTY 	(1<<5)	/* The layout was recalculated and the
				 * size of the world (text layout) has
				 * changed. */
#define GOTO_PENDING 	(1<<6)	/* Indicates the starting text line
				 * number has changed. To be reflected
				 * the next time the widget is redrawn. */
#define WIDGET_APPENDED	(1<<7)	/* Indicates a embedded widget has just
				 * been appended to the text.  This is
				 * used to determine when to add a
				 * space to the text array */

#define DEF_HTEXT_BG_COLOR		STD_COLOR_NORMAL_BG
#define DEF_HTEXT_BG_MONO		STD_MONO_NORMAL_BG
#define DEF_HTEXT_CURSOR		"arrow"
#define DEF_HTEXT_EXPORT_SELECTION	"1"

#define DEF_HTEXT_FG_COLOR		STD_COLOR_NORMAL_FG
#define DEF_HTEXT_FG_MONO		STD_MONO_NORMAL_FG
#define DEF_HTEXT_FILE_NAME		(char *)NULL
#define DEF_HTEXT_FONT			STD_FONT
#define DEF_HTEXT_HEIGHT		"0"
#define DEF_HTEXT_LINE_SPACING		"1"
#define DEF_HTEXT_MAX_HEIGHT		(char *)NULL
#define DEF_HTEXT_MAX_WIDTH 		(char *)NULL
#define DEF_HTEXT_SCROLL_UNITS		"10"
#define DEF_HTEXT_SPEC_CHAR		"0x25"
#define DEF_HTEXT_SELECT_BORDER_WIDTH 	STD_SELECT_BORDERWIDTH
#define DEF_HTEXT_SELECT_BG_COLOR 	STD_COLOR_SELECT_BG
#define DEF_HTEXT_SELECT_BG_MONO  	STD_MONO_SELECT_BG
#define DEF_HTEXT_SELECT_FG_COLOR 	STD_COLOR_SELECT_FG
#define DEF_HTEXT_SELECT_FG_MONO  	STD_MONO_SELECT_FG
#define DEF_HTEXT_TAKE_FOCUS		"1"
#define DEF_HTEXT_TEXT			(char *)NULL
#define DEF_HTEXT_TILE_OFFSET		"1"
#define DEF_HTEXT_WIDTH			"0"

static Tk_ConfigSpec configSpecs[] =
{
    {TK_CONFIG_COLOR, "-background", "background", "Background",
	DEF_HTEXT_BG_COLOR, Tk_Offset(HText, normalBg), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-background", "background", "Background",
	DEF_HTEXT_BG_MONO, Tk_Offset(HText, normalBg), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *)NULL, (char *)NULL, 0, 0},
    {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor",
	DEF_HTEXT_CURSOR, Tk_Offset(HText, cursor), TK_CONFIG_NULL_OK},
    {TK_CONFIG_BOOLEAN, "-exportselection", "exportSelection", "ExportSelection",
	DEF_HTEXT_EXPORT_SELECTION, Tk_Offset(HText, exportSelection), 0},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *)NULL, (char *)NULL, 0, 0},
    {TK_CONFIG_STRING, "-file", "file", "File",
	DEF_HTEXT_FILE_NAME, Tk_Offset(HText, fileName), TK_CONFIG_NULL_OK},
    {TK_CONFIG_FONT, "-font", "font", "Font",
	DEF_HTEXT_FONT, Tk_Offset(HText, font), 0},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
	DEF_HTEXT_FG_COLOR, Tk_Offset(HText, normalFg), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
	DEF_HTEXT_FG_MONO, Tk_Offset(HText, normalFg), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_CUSTOM, "-height", "height", "Height",
	DEF_HTEXT_HEIGHT, Tk_Offset(HText, reqHeight),
	TK_CONFIG_DONT_SET_DEFAULT, &heightOption},
    {TK_CONFIG_CUSTOM, "-linespacing", "lineSpacing", "LineSpacing",
	DEF_HTEXT_LINE_SPACING, Tk_Offset(HText, leader),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_CUSTOM, "-maxheight", "maxHeight", "MaxHeight",
	DEF_HTEXT_MAX_HEIGHT, Tk_Offset(HText, maxHeight),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_CUSTOM, "-maxwidth", "maxWidth", "MaxWidth",
	DEF_HTEXT_MAX_WIDTH, Tk_Offset(HText, maxWidth),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Background",
	DEF_HTEXT_SELECT_BG_MONO, Tk_Offset(HText, selBorder),
	TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Background",
	DEF_HTEXT_SELECT_BG_COLOR, Tk_Offset(HText, selBorder),
	TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_CUSTOM, "-selectborderwidth", "selectBorderWidth", "BorderWidth",
	DEF_HTEXT_SELECT_BORDER_WIDTH, Tk_Offset(HText, selBorderWidth),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Foreground",
	DEF_HTEXT_SELECT_FG_MONO, Tk_Offset(HText, selFgColor),
	TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Foreground",
	DEF_HTEXT_SELECT_FG_COLOR, Tk_Offset(HText, selFgColor),
	TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_INT, "-specialchar", "specialChar", "SpecialChar",
	DEF_HTEXT_SPEC_CHAR, Tk_Offset(HText, specChar), 0},
    {TK_CONFIG_STRING, "-takefocus", "takeFocus", "TakeFocus",
	DEF_HTEXT_TAKE_FOCUS, Tk_Offset(HText, takeFocus),
	TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-tile", "tile", "Tile",
	(char *)NULL, Tk_Offset(HText, tile), TK_CONFIG_NULL_OK,
	&bltTileOption},
    {TK_CONFIG_BOOLEAN, "-tileoffset", "tileOffset", "TileOffset",
	DEF_HTEXT_TILE_OFFSET, Tk_Offset(HText, tileOffsetPage), 0},
    {TK_CONFIG_STRING, "-text", "text", "Text",
	DEF_HTEXT_TEXT, Tk_Offset(HText, text), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-width", "width", "Width",
	DEF_HTEXT_WIDTH, Tk_Offset(HText, reqWidth),
	TK_CONFIG_DONT_SET_DEFAULT, &widthOption},
    {TK_CONFIG_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand",
	(char *)NULL, Tk_Offset(HText, xScrollCmdPrefix), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-xscrollunits", "xScrollUnits", "ScrollUnits",
	DEF_HTEXT_SCROLL_UNITS, Tk_Offset(HText, xScrollUnits),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_STRING, "-yscrollcommand", "yScrollCommand", "ScrollCommand",
	(char *)NULL, Tk_Offset(HText, yScrollCmdPrefix), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-yscrollunits", "yScrollUnits", "yScrollUnits",
	DEF_HTEXT_SCROLL_UNITS, Tk_Offset(HText, yScrollUnits),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_END, (char *)NULL, (char *)NULL, (char *)NULL,
	(char *)NULL, 0, 0}
};

typedef struct {
    HText *htPtr;		/* Pointer to parent's Htext structure */
    Tk_Window tkwin;		/* Widget window */
    int flags;

    int x, y;			/* Origin of embedded widget in text */

    int cavityWidth, cavityHeight; /* Dimensions of the cavity
				    * surrounding the embedded widget */
    /*
     *  Dimensions of the embedded widget.  Compared against actual
     *	embedded widget sizes when checking for resizing.
     */
    int winWidth, winHeight;

    int precedingTextEnd;	/* Index (in charArr) of the the last
				 * character immediatedly preceding
				 * the embedded widget */
    int precedingTextWidth;	/* Width of normal text preceding widget. */

    Tk_Anchor anchor;
    Justify justify;		/* Justification of region wrt to line */

    /*
     * Requested dimensions of the cavity (includes padding). If non-zero,
     * it overrides the calculated dimension of the cavity.
     */
    int reqCavityWidth, reqCavityHeight;

    /*
     * Relative dimensions of cavity wrt the size of the viewport. If
     * greater than 0.0.
     */
    double relCavityWidth, relCavityHeight;

    int reqWidth, reqHeight;	/* If non-zero, overrides the requested
				 * dimension of the embedded widget */

    double relWidth, relHeight;	/* Relative dimensions of embedded
				 * widget wrt the size of the viewport */

    Blt_Pad padX, padY;		/* Extra padding to frame around */

    int ipadX, ipadY;		/* internal padding for window */

    int fill;			/* Fill style flag */

} EmbeddedWidget;

/*
 * Flag bits embedded widgets:
 */
#define WIDGET_VISIBLE	(1<<2)	/* Widget is currently visible in the
				 * viewport. */
#define WIDGET_NOT_CHILD (1<<3) /* Widget is not a child of hypertext. */
/*
 * Defaults for embedded widgets:
 */
#define DEF_WIDGET_ANCHOR        "center"
#define DEF_WIDGET_FILL		"none"
#define DEF_WIDGET_HEIGHT	"0"
#define DEF_WIDGET_JUSTIFY	"center"
#define DEF_WIDGET_PAD_X		"0"
#define DEF_WIDGET_PAD_Y		"0"
#define DEF_WIDGET_REL_HEIGHT	"0.0"
#define DEF_WIDGET_REL_WIDTH  	"0.0"
#define DEF_WIDGET_WIDTH  	"0"

static Tk_ConfigSpec widgetConfigSpecs[] =
{
    {TK_CONFIG_ANCHOR, "-anchor", (char *)NULL, (char *)NULL,
	DEF_WIDGET_ANCHOR, Tk_Offset(EmbeddedWidget, anchor),
	TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-fill", (char *)NULL, (char *)NULL,
	DEF_WIDGET_FILL, Tk_Offset(EmbeddedWidget, fill),
	TK_CONFIG_DONT_SET_DEFAULT, &bltFillOption},
    {TK_CONFIG_CUSTOM, "-cavityheight", (char *)NULL, (char *)NULL,
	DEF_WIDGET_HEIGHT, Tk_Offset(EmbeddedWidget, reqCavityHeight),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_CUSTOM, "-cavitywidth", (char *)NULL, (char *)NULL,
	DEF_WIDGET_WIDTH, Tk_Offset(EmbeddedWidget, reqCavityWidth),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_CUSTOM, "-height", (char *)NULL, (char *)NULL,
	DEF_WIDGET_HEIGHT, Tk_Offset(EmbeddedWidget, reqHeight),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_CUSTOM, "-justify", (char *)NULL, (char *)NULL,
	DEF_WIDGET_JUSTIFY, Tk_Offset(EmbeddedWidget, justify),
	TK_CONFIG_DONT_SET_DEFAULT, &justifyOption},
    {TK_CONFIG_CUSTOM, "-padx", (char *)NULL, (char *)NULL,
	DEF_WIDGET_PAD_X, Tk_Offset(EmbeddedWidget, padX),
	TK_CONFIG_DONT_SET_DEFAULT, &bltPadOption},
    {TK_CONFIG_CUSTOM, "-pady", (char *)NULL, (char *)NULL,
	DEF_WIDGET_PAD_Y, Tk_Offset(EmbeddedWidget, padY),
	TK_CONFIG_DONT_SET_DEFAULT, &bltPadOption},
    {TK_CONFIG_DOUBLE, "-relcavityheight", (char *)NULL, (char *)NULL,
	DEF_WIDGET_REL_HEIGHT, Tk_Offset(EmbeddedWidget, relCavityHeight),
	TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-relcavitywidth", (char *)NULL, (char *)NULL,
	DEF_WIDGET_REL_WIDTH, Tk_Offset(EmbeddedWidget, relCavityWidth),
	TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-relheight", (char *)NULL, (char *)NULL,
	DEF_WIDGET_REL_HEIGHT, Tk_Offset(EmbeddedWidget, relHeight),
	TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-relwidth", (char *)NULL, (char *)NULL,
	DEF_WIDGET_REL_WIDTH, Tk_Offset(EmbeddedWidget, relWidth),
	TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-width", (char *)NULL, (char *)NULL,
	DEF_WIDGET_WIDTH, Tk_Offset(EmbeddedWidget, reqWidth),
	TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_END, (char *)NULL, (char *)NULL, (char *)NULL,
	(char *)NULL, 0, 0}
};


/* Forward Declarations */
static void DestroyText _ANSI_ARGS_((DestroyData dataPtr));
static void EmbeddedWidgetEventProc _ANSI_ARGS_((ClientData clientdata, 
	XEvent *eventPtr));
static void DisplayText _ANSI_ARGS_((ClientData clientData));
static void TextDeleteCmdProc _ANSI_ARGS_((ClientData clientdata));

#ifdef __STDC__
static Tcl_VarTraceProc TextVarProc;
static Blt_TileChangedProc TileChangedProc;
static Tk_LostSelProc TextLostSelection;
static Tk_SelectionProc TextSelectionProc;
static Tk_EventProc TextEventProc;
static Tcl_CmdProc TextWidgetCmd;
static Tcl_CmdProc TextCmd;
#endif /* __STDC__ */
/* end of Forward Declarations */


 /* Custom options */
/*
 *----------------------------------------------------------------------
 *
 * StringToJustify --
 *
 * 	Converts the justification string into its numeric
 * 	representation. This configuration option affects how the
 *	embedded widget is positioned with respect to the line on which
 *	it sits.
 *
 *	Valid style strings are:
 *
 *	"top"      Uppermost point of region is top of the line's
 *		   text
 * 	"center"   Center point of region is line's baseline.
 *	"bottom"   Lowermost point of region is bottom of the
 *		   line's text
 *
 * Returns:
 *	A standard Tcl result.  If the value was not valid
 *
 *---------------------------------------------------------------------- */
/*ARGSUSED*/
static int
StringToJustify(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Not used. */
    Tcl_Interp *interp;		/* Interpreter to send results back to */
    Tk_Window tkwin;		/* Not used. */
    char *string;		/* Justification string */
    char *widgRec;		/* Structure record */
    int offset;			/* Offset of justify in record */
{
    Justify *justPtr = (Justify *)(widgRec + offset);
    unsigned int length;
    char c;

    c = string[0];
    length = strlen(string);
    if ((c == 'c') && (strncmp(string, "center", length) == 0)) {
	*justPtr = JUSTIFY_CENTER;
    } else if ((c == 't') && (strncmp(string, "top", length) == 0)) {
	*justPtr = JUSTIFY_TOP;
    } else if ((c == 'b') && (strncmp(string, "bottom", length) == 0)) {
	*justPtr = JUSTIFY_BOTTOM;
    } else {
	Tcl_AppendResult(interp, "bad justification argument \"", string,
	    "\": should be \"center\", \"top\", or \"bottom\"", (char *)NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NameOfJustify --
 *
 *	Returns the justification style string based upon the value.
 *
 * Results:
 *	The static justification style string is returned.
 *
 *----------------------------------------------------------------------
 */
static char *
NameOfJustify(justify)
    Justify justify;
{
    switch (justify) {
    case JUSTIFY_CENTER:
	return "center";
    case JUSTIFY_TOP:
	return "top";
    case JUSTIFY_BOTTOM:
	return "bottom";
    default:
	return "unknown justification value";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * JustifyToString --
 *
 *	Returns the justification style string based upon the value.
 *
 * Results:
 *	The justification style string is returned.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static char *
JustifyToString(clientData, tkwin, widgRec, offset, freeProcPtr)
    ClientData clientData;	/* Not used. */
    Tk_Window tkwin;		/* Not used. */
    char *widgRec;		/* Structure record */
    int offset;			/* Offset of justify record */
    Tcl_FreeProc **freeProcPtr;	/* Not used. */
{
    Justify justify = *(Justify *)(widgRec + offset);

    return NameOfJustify(justify);
}

/*
 *----------------------------------------------------------------------
 *
 * GetScreenDistance --
 *
 *	Converts the given string into the screen distance or number
 *	of characters.  The valid formats are
 *
 *	    N	- pixels	Nm - millimeters
 *	    Ni  - inches        Np - pica
 *          Nc  - centimeters   N# - number of characters
 *
 *	where N is a non-negative decimal number.
 *
 * Results:
 *	A standard Tcl result.  The screen distance and the number of
 *	characters are returned.  If the string can't be converted,
 *	TCL_ERROR is returned and interp->result will contain an error
 *	message.
 *
 *----------------------------------------------------------------------
 */
static int
GetScreenDistance(interp, tkwin, string, sizePtr, countPtr)
    Tcl_Interp *interp;
    Tk_Window tkwin;
    char *string;
    int *sizePtr;
    int *countPtr;
{
    int nPixels, nChars;
    char *endPtr;		/* Pointer to last character scanned */
    double value;
    int rounded;

    value = strtod(string, &endPtr);
    if (endPtr == string) {
	Tcl_AppendResult(interp, "bad screen distance \"", string, "\"",
	    (char *)NULL);
	return TCL_ERROR;
    }
    if (value < 0.0) {
	Tcl_AppendResult(interp, "screen distance \"", string,
	    "\" must be non-negative value", (char *)NULL);
	return TCL_ERROR;
    }
    while (isspace(UCHAR(*endPtr))) {
	if (*endPtr == '\0') {
	    break;
	}
	endPtr++;
    }
    nPixels = nChars = 0;
    rounded = ROUND(value);
    switch (*endPtr) {
    case '\0':			/* Distance in pixels */
	nPixels = rounded;
	break;
    case '#':			/* Number of characters */
	nChars = rounded;
	break;
    default:			/* cm, mm, pica, inches */
	if (Tk_GetPixels(interp, tkwin, string, &rounded) != TCL_OK) {
	    return TCL_ERROR;
	}
	nPixels = rounded;
	break;
    }
    *sizePtr = nPixels;
    *countPtr = nChars;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToHeight --
 *
 *	Like TK_CONFIG_PIXELS, but adds an extra check for negative
 *	values.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToHeight(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Not used. */
    Tcl_Interp *interp;		/* Interpreter to send results back to */
    Tk_Window tkwin;		/* Window */
    char *string;		/* Pixel value string */
    char *widgRec;		/* Widget record */
    int offset;			/* Not used. */
{
    HText *htPtr = (HText *)widgRec;
    int height, nRows;

    if (GetScreenDistance(interp, tkwin, string, &height, &nRows) != TCL_OK) {
	return TCL_ERROR;
    }
    htPtr->nRows = nRows;
    htPtr->reqHeight = height;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToWidth --
 *
 *	Like TK_CONFIG_PIXELS, but adds an extra check for negative
 *	values.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToWidth(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Not used. */
    Tcl_Interp *interp;		/* Interpreter to send results back to */
    Tk_Window tkwin;		/* Window */
    char *string;		/* Pixel value string */
    char *widgRec;		/* Widget record */
    int offset;			/* Not used. */
{
    HText *htPtr = (HText *)widgRec;
    int width, nColumns;

    if (GetScreenDistance(interp, tkwin, string, &width,
	    &nColumns) != TCL_OK) {
	return TCL_ERROR;
    }
    htPtr->nColumns = nColumns;
    htPtr->reqWidth = width;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * WidthHeightToString --
 *
 *	Returns the string representing the positive pixel size.
 *
 * Results:
 *	The pixel size string is returned.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static char *
WidthHeightToString(clientData, tkwin, widgRec, offset, freeProcPtr)
    ClientData clientData;	/* Not used. */
    Tk_Window tkwin;		/* Not used. */
    char *widgRec;		/* Row/column structure record */
    int offset;			/* Offset of fill in Partition record */
    Tcl_FreeProc **freeProcPtr;	/* Not used. */
{
    int pixels = *(int *)(widgRec + offset);
    char *result;
    char string[200];

    sprintf(string, "%d", pixels);
    result = Blt_Strdup(string);
    if (result == NULL) {
	return "out of memory";
    }
    *freeProcPtr = (Tcl_FreeProc *)Blt_Free;
    return result;
}

/* General routines */
/*
 *----------------------------------------------------------------------
 *
 * EventuallyRedraw --
 *
 *	Queues a request to redraw the text window at the next idle
 *	point.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Information gets redisplayed.  Right now we don't do selective
 *	redisplays:  the whole window will be redrawn.  This doesn't
 *	seem to hurt performance noticeably, but if it does then this
 *	could be changed.
 *
 *----------------------------------------------------------------------
 */
static void
EventuallyRedraw(htPtr)
    HText *htPtr;		/* Information about widget. */
{
    if ((htPtr->tkwin != NULL) && !(htPtr->flags & REDRAW_PENDING)) {
	htPtr->flags |= REDRAW_PENDING;
	Tcl_DoWhenIdle(DisplayText, htPtr);
    }
}

/*
 * --------------------------------------------------------------------
 *
 * ResizeArray --
 *
 *	Reallocates memory to the new size given.  New memory
 *	is also cleared (zeros).
 *
 * Results:
 *	Returns a pointer to the new object or NULL if an error occurred.
 *
 * Side Effects:
 *	Memory is re/allocated.
 *
 * --------------------------------------------------------------------
 */
static int
ResizeArray(arrayPtr, elemSize, newSize, prevSize)
    char **arrayPtr;
    int elemSize;
    int newSize;
    int prevSize;
{
    char *newPtr;

    if (newSize == prevSize) {
	return TCL_OK;
    }
    if (newSize == 0) {		/* Free entire array */
	Blt_Free(*arrayPtr);
	*arrayPtr = NULL;
	return TCL_OK;
    }
    newPtr = Blt_Calloc(elemSize, newSize);
    if (newPtr == NULL) {
	return TCL_ERROR;
    }
    if ((prevSize > 0) && (*arrayPtr != NULL)) {
	int size;

	size = MIN(prevSize, newSize) * elemSize;
	if (size > 0) {
	    memcpy(newPtr, *arrayPtr, size);
	}
	Blt_Free(*arrayPtr);
    }
    *arrayPtr = newPtr;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * LineSearch --
 *
 * 	Performs a binary search for the line of text located at some
 * 	world y-coordinate (not screen y-coordinate). The search is
 * 	inclusive of those lines from low to high.
 *
 * Results:
 *	Returns the array index of the line found at the given
 *	y-coordinate.  If the y-coordinate is outside of the given range
 *	of lines, -1 is returned.
 *
 * ----------------------------------------------------------------------
 */
static int
LineSearch(htPtr, yCoord, low, high)
    HText *htPtr;		/* HText widget */
    int yCoord;			/* Search y-coordinate  */
    int low, high;		/* Range of lines to search */
{
    int median;
    Line *linePtr;

    while (low <= high) {
	median = (low + high) >> 1;
	linePtr = htPtr->lineArr + median;
	if (yCoord < linePtr->offset) {
	    high = median - 1;
	} else if (yCoord >= (linePtr->offset + linePtr->height)) {
	    low = median + 1;
	} else {
	    return median;
	}
    }
    return -1;
}

/*
 * ----------------------------------------------------------------------
 *
 * IndexSearch --
 *
 *	Try to find what line contains a given text index. Performs
 *	a binary search for the text line which contains the given index.
 *	The search is inclusive of those lines from low and high.
 *
 * Results:
 *	Returns the line number containing the given index. If the index
 *	is outside the range of lines, -1 is returned.
 *
 * ----------------------------------------------------------------------
 */
static int
IndexSearch(htPtr, key, low, high)
    HText *htPtr;		/* HText widget */
    int key;			/* Search index */
    int low, high;		/* Range of lines to search */
{
    int median;
    Line *linePtr;

    while (low <= high) {
	median = (low + high) >> 1;
	linePtr = htPtr->lineArr + median;
	if (key < linePtr->textStart) {
	    high = median - 1;
	} else if (key > linePtr->textEnd) {
	    low = median + 1;
	} else {
	    return median;
	}
    }
    return -1;
}

/*
 * ----------------------------------------------------------------------
 *
 * GetXYPosIndex --
 *
 * 	Converts a string in the form "@x,y", where x and y are
 *	window coordinates, to a text index.
 *
 *	Window coordinates are first translated into world coordinates.
 *	Any coordinate outside of the bounds of the virtual text is
 *	silently set the nearest boundary.
 *
 * Results:
 *	A standard Tcl result.  If "string" is a valid index, then
 *	*indexPtr is filled with the numeric index corresponding.
 *	Otherwise an error message is left in interp->result.
 *
 * ----------------------------------------------------------------------
 */
static int
GetXYPosIndex(htPtr, string, indexPtr)
    HText *htPtr;
    char *string;
    int *indexPtr;
{
    int x, y, curX, dummy;
    int textLength, textStart;
    int cindex, lindex;
    Line *linePtr;

    if (Blt_GetXY(htPtr->interp, htPtr->tkwin, string, &x, &y) != TCL_OK) {
	return TCL_ERROR;
    }
    /* Locate the line corresponding to the window y-coordinate position */

    y += htPtr->yOffset;
    if (y < 0) {
	lindex = htPtr->first;
    } else if (y >= htPtr->worldHeight) {
	lindex = htPtr->last;
    } else {
	lindex = LineSearch(htPtr, y, 0, htPtr->nLines - 1);
    }
    if (lindex < 0) {
	Tcl_AppendResult(htPtr->interp, "can't find line at \"", string, "\"",
	    (char *)NULL);
	return TCL_ERROR;
    }
    x += htPtr->xOffset;
    if (x < 0) {
	x = 0;
    } else if (x > htPtr->worldWidth) {
	x = htPtr->worldWidth;
    }
    linePtr = htPtr->lineArr + lindex;
    curX = 0;
    textStart = linePtr->textStart;
    textLength = linePtr->textEnd - linePtr->textStart;
    if (Blt_ChainGetLength(linePtr->chainPtr) > 0) {
	Blt_ChainLink *linkPtr;
	int deltaX;
	EmbeddedWidget *winPtr;

	for (linkPtr = Blt_ChainFirstLink(linePtr->chainPtr); linkPtr != NULL;
	    linkPtr = Blt_ChainNextLink(linkPtr)) {
	    winPtr = Blt_ChainGetValue(linkPtr);
	    deltaX = winPtr->precedingTextWidth + winPtr->cavityWidth;
	    if ((curX + deltaX) > x) {
		textLength = (winPtr->precedingTextEnd - textStart);
		break;
	    }
	    curX += deltaX;
	    /*
	     * Skip over the trailing space. It designates the position of
	     * a embedded widget in the text
	     */
	    textStart = winPtr->precedingTextEnd + 1;
	}
    }
    cindex = Tk_MeasureChars(htPtr->font, htPtr->charArr + textStart,
	textLength, 10000, DEF_TEXT_FLAGS, &dummy);
    *indexPtr = textStart + cindex;
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * ParseIndex --
 *
 *	Parse a string representing a text index into numeric
 *	value.  A text index can be in one of the following forms.
 *
 *	  "anchor"	- anchor position of the selection.
 *	  "sel.first"   - index of the first character in the selection.
 *	  "sel.last"	- index of the last character in the selection.
 *	  "page.top"  	- index of the first character on the page.
 *	  "page.bottom"	- index of the last character on the page.
 *	  "@x,y"	- x and y are window coordinates.
 * 	  "number	- raw index of text
 *	  "line.char"	- line number and character position
 *
 * Results:
 *	A standard Tcl result.  If "string" is a valid index, then
 *	*indexPtr is filled with the corresponding numeric index.
 *	Otherwise an error message is left in interp->result.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */
static int
ParseIndex(htPtr, string, indexPtr)
    HText *htPtr;		/* Text for which the index is being
				 * specified. */
    char *string;		/* Numerical index into htPtr's element
				 * list, or "end" to refer to last element. */
    int *indexPtr;		/* Where to store converted relief. */
{
    unsigned int length;
    char c;
    Tcl_Interp *interp = htPtr->interp;

    length = strlen(string);
    c = string[0];

    if ((c == 'a') && (strncmp(string, "anchor", length) == 0)) {
	*indexPtr = htPtr->selAnchor;
    } else if ((c == 's') && (length > 4)) {
	if (strncmp(string, "sel.first", length) == 0) {
	    *indexPtr = htPtr->selFirst;
	} else if (strncmp(string, "sel.last", length) == 0) {
	    *indexPtr = htPtr->selLast;
	} else {
	    goto badIndex;	/* Not a valid index */
	}
	if (*indexPtr < 0) {
	    Tcl_AppendResult(interp, "bad index \"", string,
		"\": nothing selected in \"",
		Tk_PathName(htPtr->tkwin), "\"", (char *)NULL);
	    return TCL_ERROR;
	}
    } else if ((c == 'p') && (length > 5) &&
	(strncmp(string, "page.top", length) == 0)) {
	int first;

	first = htPtr->first;
	if (first < 0) {
	    first = 0;
	}
	*indexPtr = htPtr->lineArr[first].textStart;
    } else if ((c == 'p') && (length > 5) &&
	(strncmp(string, "page.bottom", length) == 0)) {
	*indexPtr = htPtr->lineArr[htPtr->last].textEnd;
    } else if (c == '@') {	/* Screen position */
	if (GetXYPosIndex(htPtr, string, indexPtr) != TCL_OK) {
	    return TCL_ERROR;
	}
    } else {
	char *period;

	period = strchr(string, '.');
	if (period == NULL) {	/* Raw index */
	    int tindex;

	    if ((string[0] == 'e') && (strcmp(string, "end") == 0)) {
		tindex = htPtr->nChars - 1;
	    } else if (Tcl_GetInt(interp, string, &tindex) != TCL_OK) {
		goto badIndex;
	    }
	    if (tindex < 0) {
		tindex = 0;
	    } else if (tindex > (htPtr->nChars - 1)) {
		tindex = htPtr->nChars - 1;
	    }
	    *indexPtr = tindex;
	} else {
	    int lindex, cindex, offset;
	    Line *linePtr;
	    int result;

	    *period = '\0';
	    result = TCL_OK;
	    if ((string[0] == 'e') && (strcmp(string, "end") == 0)) {
		lindex = htPtr->nLines - 1;
	    } else {
		result = Tcl_GetInt(interp, string, &lindex);
	    }
	    *period = '.';	/* Repair index string before returning */
	    if (result != TCL_OK) {
		goto badIndex;	/* Bad line number */
	    }
	    if (lindex < 0) {
		lindex = 0;	/* Silently repair bad line numbers */
	    }
	    if (htPtr->nChars == 0) {
		*indexPtr = 0;
		return TCL_OK;
	    }
	    if (lindex >= htPtr->nLines) {
		lindex = htPtr->nLines - 1;
	    }
	    linePtr = htPtr->lineArr + lindex;
	    cindex = 0;
	    if ((*(period + 1) != '\0')) {
		string = period + 1;
		if ((string[0] == 'e') && (strcmp(string, "end") == 0)) {
		    cindex = linePtr->textEnd - linePtr->textStart;
		} else if (Tcl_GetInt(interp, string, &cindex) != TCL_OK) {
		    goto badIndex;
		}
	    }
	    if (cindex < 0) {
		cindex = 0;	/* Silently fix bogus indices */
	    }
	    offset = 0;
	    if (htPtr->nChars > 0) {
		offset = linePtr->textStart + cindex;
		if (offset > linePtr->textEnd) {
		    offset = linePtr->textEnd;
		}
	    }
	    *indexPtr = offset;
	}
    }
    if (htPtr->nChars == 0) {
	*indexPtr = 0;
    }
    return TCL_OK;

  badIndex:

    /*
     * Some of the paths here leave messages in interp->result, so we
     * have to clear it out before storing our own message.
     */
    Tcl_ResetResult(interp);
    Tcl_AppendResult(interp, "bad index \"", string, "\": \
should be one of the following: anchor, sel.first, sel.last, page.bottom, \
page.top, @x,y, index, line.char", (char *)NULL);
    return TCL_ERROR;
}

/*
 *--------------------------------------------------------------
 *
 * GetIndex --
 *
 *	Get the index from a string representing a text index.
 *
 *
 * Results:
 *	A standard Tcl result.  If "string" is a valid index, then
 *	*indexPtr is filled with the numeric index corresponding.
 *	Otherwise an error message is left in interp->result.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */
static int
GetIndex(htPtr, string, indexPtr)
    HText *htPtr;		/* Text for which the index is being
				 * specified. */
    char *string;		/* Numerical index into htPtr's element
				 * list, or "end" to refer to last element. */
    int *indexPtr;		/* Where to store converted relief. */
{
    int tindex;

    if (ParseIndex(htPtr, string, &tindex) != TCL_OK) {
	return TCL_ERROR;
    }
    *indexPtr = tindex;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * GetTextPosition --
 *
 * 	Performs a binary search for the index located on line in
 *	the text. The search is limited to those lines between
 *	low and high inclusive.
 *
 * Results:
 *	Returns the line number at the given Y coordinate. If position
 *	does not correspond to any of the lines in the given the set,
 *	-1 is returned.
 *
 * ----------------------------------------------------------------------
 */
static int
GetTextPosition(htPtr, tindex, lindexPtr, cindexPtr)
    HText *htPtr;
    int tindex;
    int *lindexPtr;
    int *cindexPtr;
{
    int lindex, cindex;

    lindex = cindex = 0;
    if (htPtr->nChars > 0) {
	Line *linePtr;

	lindex = IndexSearch(htPtr, tindex, 0, htPtr->nLines - 1);
	if (lindex < 0) {
	    char string[200];

	    sprintf(string, "can't determine line number from index \"%d\"",
		tindex);
	    Tcl_AppendResult(htPtr->interp, string, (char *)NULL);
	    return TCL_ERROR;
	}
	linePtr = htPtr->lineArr + lindex;
	if (tindex > linePtr->textEnd) {
	    tindex = linePtr->textEnd;
	}
	cindex = tindex - linePtr->textStart;
    }
    *lindexPtr = lindex;
    *cindexPtr = cindex;
    return TCL_OK;
}

/* EmbeddedWidget Procedures */
/*
 *----------------------------------------------------------------------
 *
 * GetEmbeddedWidgetWidth --
 *
 *	Returns the width requested by the embedded widget. The requested
 *	space also includes any internal padding which has been designated
 *	for this window.
 *
 * Results:
 *	Returns the requested width of the embedded widget.
 *
 *----------------------------------------------------------------------
 */
static int
GetEmbeddedWidgetWidth(winPtr)
    EmbeddedWidget *winPtr;
{
    int width;

    if (winPtr->reqWidth > 0) {
	width = winPtr->reqWidth;
    } else if (winPtr->relWidth > 0.0) {
	width = (int)
	    ((double)Tk_Width(winPtr->htPtr->tkwin) * winPtr->relWidth + 0.5);
    } else {
	width = Tk_ReqWidth(winPtr->tkwin);
    }
    width += (2 * winPtr->ipadX);
    return width;
}

/*
 *----------------------------------------------------------------------
 *
 * GetEmbeddedWidgetHeight --
 *
 *	Returns the height requested by the embedded widget. The requested
 *	space also includes any internal padding which has been designated
 *	for this window.
 *
 * Results:
 *	Returns the requested height of the embedded widget.
 *
 *----------------------------------------------------------------------
 */
static int
GetEmbeddedWidgetHeight(winPtr)
    EmbeddedWidget *winPtr;
{
    int height;

    if (winPtr->reqHeight > 0) {
	height = winPtr->reqHeight;
    } else if (winPtr->relHeight > 0.0) {
	height = (int)((double)Tk_Height(winPtr->htPtr->tkwin) *
	    winPtr->relHeight + 0.5);
    } else {
	height = Tk_ReqHeight(winPtr->tkwin);
    }
    height += (2 * winPtr->ipadY);
    return height;
}

/*
 * --------------------------------------------------------------
 *
 * EmbeddedWidgetEventProc --
 *
 * 	This procedure is invoked by the Tk dispatcher for various
 * 	events on hypertext widgets.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get
 *	cleaned up.  When it gets exposed, it is redisplayed.
 *
 * --------------------------------------------------------------
 */
static void
EmbeddedWidgetEventProc(clientData, eventPtr)
    ClientData clientData;	/* Information about the embedded widget. */
    XEvent *eventPtr;		/* Information about event. */
{
    EmbeddedWidget *winPtr = clientData;
    HText *htPtr;

    if ((winPtr == NULL) || (winPtr->tkwin == NULL)) {
	return;
    }
    htPtr = winPtr->htPtr;

    if (eventPtr->type == DestroyNotify) {
	Blt_HashEntry *hPtr;
	/*
	 * Mark the widget as deleted by dereferencing the Tk window
	 * pointer.  Zero out the height and width to collapse the area
	 * used by the widget.  Redraw the window only if the widget is
	 * currently visible.
	 */
	winPtr->htPtr->flags |= REQUEST_LAYOUT;
	if (Tk_IsMapped(winPtr->tkwin) && (winPtr->flags & WIDGET_VISIBLE)) {
	    EventuallyRedraw(htPtr);
	}
	Tk_DeleteEventHandler(winPtr->tkwin, StructureNotifyMask,
	    EmbeddedWidgetEventProc, winPtr);
	hPtr = Blt_FindHashEntry(&(htPtr->widgetTable), (char *)winPtr->tkwin);
	Blt_DeleteHashEntry(&(htPtr->widgetTable), hPtr);
	winPtr->cavityWidth = winPtr->cavityHeight = 0;
	winPtr->tkwin = NULL;

    } else if (eventPtr->type == ConfigureNotify) {
	/*
	 * EmbeddedWidgets can't request new positions. Worry only about resizing.
	 */
	if (winPtr->winWidth != Tk_Width(winPtr->tkwin) ||
	    winPtr->winHeight != Tk_Height(winPtr->tkwin)) {
	    EventuallyRedraw(htPtr);
	    htPtr->flags |= REQUEST_LAYOUT;
	}
    }
}

/*
 *--------------------------------------------------------------
 *
 * EmbeddedWidgetCustodyProc --
 *
 *	This procedure is invoked when a embedded widget has been
 *	stolen by another geometry manager.  The information and
 *	memory associated with the embedded widget is released.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Arranges for the widget formerly associated with the widget
 *	to have its layout re-computed and arranged at the
 *	next idle point.
 *
 *--------------------------------------------------------------
 */
 /* ARGSUSED */
static void
EmbeddedWidgetCustodyProc(clientData, tkwin)
    ClientData clientData;	/* Information about the former embedded widget. */
    Tk_Window tkwin;		/* Not used. */
{
    Blt_HashEntry *hPtr;
    EmbeddedWidget *winPtr = clientData;
    /*
     * Mark the widget as deleted by dereferencing the Tk window
     * pointer.  Zero out the height and width to collapse the area
     * used by the widget.  Redraw the window only if the widget is
     * currently visible.
     */
    winPtr->htPtr->flags |= REQUEST_LAYOUT;
    if (Tk_IsMapped(winPtr->tkwin) && (winPtr->flags & WIDGET_VISIBLE)) {
	EventuallyRedraw(winPtr->htPtr);
    }
    Tk_DeleteEventHandler(winPtr->tkwin, StructureNotifyMask,
	EmbeddedWidgetEventProc, winPtr);
    hPtr = Blt_FindHashEntry(&(winPtr->htPtr->widgetTable), 
			     (char *)winPtr->tkwin);
    Blt_DeleteHashEntry(&(winPtr->htPtr->widgetTable), hPtr);
    winPtr->cavityWidth = winPtr->cavityHeight = 0;
    winPtr->tkwin = NULL;
}

/*
 *--------------------------------------------------------------
 *
 * EmbeddedWidgetGeometryProc --
 *
 *	This procedure is invoked by Tk_GeometryRequest for
 *	embedded widgets managed by the hypertext widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Arranges for tkwin, and all its managed siblings, to
 *	be repacked and drawn at the next idle point.
 *
 *--------------------------------------------------------------
 */
 /* ARGSUSED */
static void
EmbeddedWidgetGeometryProc(clientData, tkwin)
    ClientData clientData;	/* Information about window that got new
			         * preferred geometry.  */
    Tk_Window tkwin;		/* Other Tk-related information about the
			         * window. */
{
    EmbeddedWidget *winPtr = clientData;

    winPtr->htPtr->flags |= REQUEST_LAYOUT;
    EventuallyRedraw(winPtr->htPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * FindEmbeddedWidget --
 *
 *	Searches for a widget matching the path name given
 *	If found, the pointer to the widget structure is returned,
 *	otherwise NULL.
 *
 * Results:
 *	The pointer to the widget structure. If not found, NULL.
 *
 * ----------------------------------------------------------------------
 */
static EmbeddedWidget *
FindEmbeddedWidget(htPtr, tkwin)
    HText *htPtr;		/* Hypertext widget structure */
    Tk_Window tkwin;		/* Path name of embedded widget  */
{
    Blt_HashEntry *hPtr;

    hPtr = Blt_FindHashEntry(&(htPtr->widgetTable), (char *)tkwin);
    if (hPtr != NULL) {
	return (EmbeddedWidget *) Blt_GetHashValue(hPtr);
    }
    return NULL;
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateEmbeddedWidget --
 *
 * 	This procedure creates and initializes a new embedded widget
 *	in the hyper text widget.
 *
 * Results:
 *	The return value is a pointer to a structure describing the
 *	new embedded widget.  If an error occurred, then the return 
 *	value is NULL and an error message is left in interp->result.
 *
 * Side effects:
 *	Memory is allocated. EmbeddedWidget window is mapped. 
 *	Callbacks are set up for embedded widget resizes and geometry 
 *	requests.
 *
 * ----------------------------------------------------------------------
 */
static EmbeddedWidget *
CreateEmbeddedWidget(htPtr, name)
    HText *htPtr;		/* Hypertext widget */
    char *name;			/* Name of embedded widget */
{
    EmbeddedWidget *winPtr;
    Tk_Window tkwin;
    Blt_HashEntry *hPtr;
    int isNew;

    tkwin = Tk_NameToWindow(htPtr->interp, name, htPtr->tkwin);
    if (tkwin == NULL) {
	return NULL;
    }
    if (Tk_Parent(tkwin) != htPtr->tkwin) {
	Tcl_AppendResult(htPtr->interp, "parent window of \"", name,
	    "\" must be \"", Tk_PathName(htPtr->tkwin), "\"", (char *)NULL);
	return NULL;
    }
    hPtr = Blt_CreateHashEntry(&(htPtr->widgetTable), (char *)tkwin, &isNew);
    /* Check is the widget is already embedded into this widget */
    if (!isNew) {
	Tcl_AppendResult(htPtr->interp, "\"", name,
	    "\" is already appended to ", Tk_PathName(htPtr->tkwin),
	    (char *)NULL);
	return NULL;
    }
    winPtr = Blt_Calloc(1, sizeof(EmbeddedWidget));
    assert(winPtr);
    winPtr->flags = 0;
    winPtr->tkwin = tkwin;
    winPtr->htPtr = htPtr;
    winPtr->x = winPtr->y = 0;
    winPtr->fill = FILL_NONE;
    winPtr->justify = JUSTIFY_CENTER;
    winPtr->anchor = TK_ANCHOR_CENTER;
    Blt_SetHashValue(hPtr, winPtr);

    Tk_ManageGeometry(tkwin, &htextMgrInfo, winPtr);
    Tk_CreateEventHandler(tkwin, StructureNotifyMask, EmbeddedWidgetEventProc,
	  winPtr);
    return winPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * DestroyEmbeddedWidget --
 *
 * 	This procedure is invoked by DestroyLine to clean up the
 * 	internal structure of a widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Everything associated with the widget is freed up.
 *
 * ----------------------------------------------------------------------
 */
static void
DestroyEmbeddedWidget(winPtr)
    EmbeddedWidget *winPtr;
{
    /* Destroy the embedded widget if it still exists */
    if (winPtr->tkwin != NULL) {
	Blt_HashEntry *hPtr;

	Tk_DeleteEventHandler(winPtr->tkwin, StructureNotifyMask,
	    EmbeddedWidgetEventProc, winPtr);
	hPtr = Blt_FindHashEntry(&(winPtr->htPtr->widgetTable),
	    (char *)winPtr->tkwin);
	Blt_DeleteHashEntry(&(winPtr->htPtr->widgetTable), hPtr);
	Tk_DestroyWindow(winPtr->tkwin);
    }
    Blt_Free(winPtr);
}

/* Line Procedures */
/*
 * ----------------------------------------------------------------------
 *
 * CreateLine --
 *
 * 	This procedure creates and initializes a new line of text.
 *
 * Results:
 *	The return value is a pointer to a structure describing the new
 * 	line of text.  If an error occurred, then the return value is NULL
 *	and an error message is left in interp->result.
 *
 * Side effects:
 *	Memory is allocated.
 *
 * ----------------------------------------------------------------------
 */
static Line *
CreateLine(htPtr)
    HText *htPtr;
{
    Line *linePtr;

    if (htPtr->nLines >= htPtr->arraySize) {
	if (htPtr->arraySize == 0) {
	    htPtr->arraySize = DEF_LINES_ALLOC;
	} else {
	    htPtr->arraySize += htPtr->arraySize;
	}
	if (ResizeArray((char **)&(htPtr->lineArr), sizeof(Line),
		htPtr->arraySize, htPtr->nLines) != TCL_OK) {
	    return NULL;
	}
    }
    /* Initialize values in the new entry */

    linePtr = htPtr->lineArr + htPtr->nLines;
    linePtr->offset = 0;
    linePtr->height = linePtr->width = 0;
    linePtr->textStart = 0;
    linePtr->textEnd = -1;
    linePtr->baseline = 0;
    linePtr->chainPtr = Blt_ChainCreate();

    htPtr->nLines++;
    return linePtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * DestroyLine --
 *
 * 	This procedure is invoked to clean up the internal structure
 *	of a line.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Everything associated with the line (text and widgets) is
 *	freed up.
 *
 * ----------------------------------------------------------------------
 */
static void
DestroyLine(linePtr)
    Line *linePtr;
{
    Blt_ChainLink *linkPtr;
    EmbeddedWidget *winPtr;

    /* Free the list of embedded widget structures */
    for (linkPtr = Blt_ChainFirstLink(linePtr->chainPtr); linkPtr != NULL;
	linkPtr = Blt_ChainNextLink(linkPtr)) {
	winPtr = Blt_ChainGetValue(linkPtr);
	DestroyEmbeddedWidget(winPtr);
    }
    Blt_ChainDestroy(linePtr->chainPtr);
}

static void
FreeText(htPtr)
    HText *htPtr;
{
    int i;

    for (i = 0; i < htPtr->nLines; i++) {
	DestroyLine(htPtr->lineArr + i);
    }
    htPtr->nLines = 0;
    htPtr->nChars = 0;
    if (htPtr->charArr != NULL) {
	Blt_Free(htPtr->charArr);
	htPtr->charArr = NULL;
    }
}

/* Text Procedures */
/*
 * ----------------------------------------------------------------------
 *
 * DestroyText --
 *
 * 	This procedure is invoked by Tcl_EventuallyFree or Tcl_Release
 *	to clean up the internal structure of a HText at a safe time
 *	(when no-one is using it anymore).
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Everything associated with the widget is freed up.
 *
 * ----------------------------------------------------------------------
 */
static void
DestroyText(dataPtr)
    DestroyData dataPtr;	/* Info about hypertext widget. */
{
    HText *htPtr = (HText *)dataPtr;

    Tk_FreeOptions(configSpecs, (char *)htPtr, htPtr->display, 0);
    if (htPtr->drawGC != NULL) {
	Tk_FreeGC(htPtr->display, htPtr->drawGC);
    }
    if (htPtr->fillGC != NULL) {
	Tk_FreeGC(htPtr->display, htPtr->fillGC);
    }
    if (htPtr->tile != NULL) {
	Blt_FreeTile(htPtr->tile);
    }
    if (htPtr->selectGC != NULL) {
	Tk_FreeGC(htPtr->display, htPtr->selectGC);
    }
    FreeText(htPtr);
    if (htPtr->lineArr != NULL) {
	Blt_Free(htPtr->lineArr);
    }
    Blt_DeleteHashTable(&(htPtr->widgetTable));
    Blt_Free(htPtr);
}

/*
 * --------------------------------------------------------------
 *
 * TextEventProc --
 *
 * 	This procedure is invoked by the Tk dispatcher for various
 * 	events on hypertext widgets.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get
 *	cleaned up.  When it gets exposed, it is redisplayed.
 *
 * --------------------------------------------------------------
 */
static void
TextEventProc(clientData, eventPtr)
    ClientData clientData;	/* Information about window. */
    XEvent *eventPtr;		/* Information about event. */
{
    HText *htPtr = clientData;

    if (eventPtr->type == ConfigureNotify) {
	if ((htPtr->lastWidth != Tk_Width(htPtr->tkwin)) ||
	    (htPtr->lastHeight != Tk_Height(htPtr->tkwin))) {
	    htPtr->flags |= (REQUEST_LAYOUT | TEXT_DIRTY);
	    EventuallyRedraw(htPtr);
	}
    } else if (eventPtr->type == Expose) {

	/*
	 * If the Expose event was synthetic (i.e. we manufactured it
	 * ourselves during a redraw operation), toggle the bit flag
	 * which controls redraws.
	 */

	if (eventPtr->xexpose.send_event) {
	    htPtr->flags ^= IGNORE_EXPOSURES;
	    return;
	}
	if ((eventPtr->xexpose.count == 0) &&
	    !(htPtr->flags & IGNORE_EXPOSURES)) {
	    htPtr->flags |= TEXT_DIRTY;
	    EventuallyRedraw(htPtr);
	}
    } else if (eventPtr->type == DestroyNotify) {
	if (htPtr->tkwin != NULL) {
	    htPtr->tkwin = NULL;
	    Tcl_DeleteCommandFromToken(htPtr->interp, htPtr->cmdToken);
	}
	if (htPtr->flags & REDRAW_PENDING) {
	    Tcl_CancelIdleCall(DisplayText, htPtr);
	}
	Tcl_EventuallyFree(htPtr, DestroyText);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextDeleteCmdProc --
 *
 *	This procedure is invoked when a widget command is deleted.  If
 *	the widget isn't already in the process of being destroyed,
 *	this command destroys it.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The widget is destroyed.
 *
 *----------------------------------------------------------------------
 */

static void
TextDeleteCmdProc(clientData)
    ClientData clientData;	/* Pointer to widget record for widget. */
{
    HText *htPtr = clientData;

    /*
     * This procedure could be invoked either because the window was
     * destroyed and the command was then deleted (in which case tkwin
     * is NULL) or because the command was deleted, and then this procedure
     * destroys the widget.
     */

    if (htPtr->tkwin != NULL) {
	Tk_Window tkwin;

	tkwin = htPtr->tkwin;
	htPtr->tkwin = NULL;
	Tk_DestroyWindow(tkwin);
#ifdef ITCL_NAMESPACES
	Itk_SetWidgetCommand(tkwin, (Tcl_Command) NULL);
#endif /* ITCL_NAMESPACES */
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TileChangedProc
 *
 *	Stub for image change notifications.  Since we immediately draw
 *	the image into a pixmap, we don't care about image changes.
 *
 *	It would be better if Tk checked for NULL proc pointers.
 *
 * Results:
 *	None.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static void
TileChangedProc(clientData, tile)
    ClientData clientData;
    Blt_Tile tile;		/* Not used. */
{
    HText *htPtr = clientData;

    if (htPtr->tkwin != NULL) {
	EventuallyRedraw(htPtr);
    }
}

/* Configuration Procedures */
static void
ResetTextInfo(htPtr)
    HText *htPtr;
{
    htPtr->first = 0;
    htPtr->last = htPtr->nLines - 1;
    htPtr->selFirst = htPtr->selLast = -1;
    htPtr->selAnchor = 0;
    htPtr->pendingX = htPtr->pendingY = 0;
    htPtr->worldWidth = htPtr->worldHeight = 0;
    htPtr->xOffset = htPtr->yOffset = 0;
}

static Line *
GetLastLine(htPtr)
    HText *htPtr;
{
    if (htPtr->nLines == 0) {
	return CreateLine(htPtr);
    }
    return (htPtr->lineArr + (htPtr->nLines - 1));
}

/*
 * ----------------------------------------------------------------------
 *
 * ReadNamedFile --
 *
 * 	Read the named file into a newly allocated buffer.
 *
 * Results:
 *	Returns the size of the allocated buffer if the file was
 *	read correctly.  Otherwise -1 is returned and "interp->result"
 *	will contain an error message.
 *
 * Side Effects:
 *	If successful, the contents of "bufferPtr" will point
 *	to the allocated buffer.
 *
 * ----------------------------------------------------------------------
 */
static int
ReadNamedFile(interp, fileName, bufferPtr)
    Tcl_Interp *interp;
    char *fileName;
    char **bufferPtr;
{
    FILE *f;
    int nRead, fileSize;
    int count, bytesLeft;
    char *buffer;
    int result = -1;
#ifdef _MSC_VER
#define fstat	 _fstat
#define stat	 _stat
#define fileno	 _fileno
#endif
    struct stat fileInfo;

    f = fopen(fileName, "r");
    if (f == NULL) {
	Tcl_AppendResult(interp, "can't open \"", fileName,
	    "\" for reading: ", Tcl_PosixError(interp), (char *)NULL);
	return -1;
    }
    if (fstat(fileno(f), &fileInfo) < 0) {
	Tcl_AppendResult(interp, "can't stat \"", fileName, "\": ",
	    Tcl_PosixError(interp), (char *)NULL);
	fclose(f);
	return -1;
    }
    fileSize = fileInfo.st_size + 1;
    buffer = Blt_Malloc(sizeof(char) * fileSize);
    if (buffer == NULL) {
	fclose(f);
	return -1;		/* Can't allocate memory for file buffer */
    }
    nRead = count = 0;
    for (bytesLeft = fileInfo.st_size; bytesLeft > 0; bytesLeft -= nRead) {
	nRead = fread(buffer + count, sizeof(char), bytesLeft, f);
	if (nRead < 0) {
	    Tcl_AppendResult(interp, "error reading \"", fileName, "\": ",
		Tcl_PosixError(interp), (char *)NULL);
	    fclose(f);
	    Blt_Free(buffer);
	    return -1;
	} else if (nRead == 0) {
	    break;
	}
	count += nRead;
    }
    fclose(f);
    buffer[count] = '\0';
    result = count;
    *bufferPtr = buffer;
    return result;
}

/*
 * ----------------------------------------------------------------------
 *
 * CollectCommand --
 *
 * 	Collect the characters representing a Tcl command into a
 *	given buffer.
 *
 * Results:
 *	Returns the number of bytes examined.  If an error occurred,
 *	-1 is returned and "interp->result" will contain an error
 *	message.
 *
 * Side Effects:
 *	If successful, the "cmdArr" will be filled with the string
 *	representing the Tcl command.
 *
 * ----------------------------------------------------------------------
 */

static int
CollectCommand(htPtr, inputArr, maxBytes, cmdArr)
    HText *htPtr;		/* Widget record */
    char inputArr[];		/* Array of bytes representing the htext input */
    int maxBytes;		/* Maximum number of bytes left in input */
    char cmdArr[];		/* Output buffer to be filled with the Tcl
				 * command */
{
    int c;
    int i;
    int state, count;

    /* Simply collect the all the characters until %% into a buffer */

    state = count = 0;
    for (i = 0; i < maxBytes; i++) {
	c = inputArr[i];
	if (c == htPtr->specChar) {
	    state++;
	} else if ((state == 0) && (c == '\\')) {
	    state = 3;
	} else {
	    state = 0;
	}
	switch (state) {
	case 2:		/* End of command block found */
	    cmdArr[count - 1] = '\0';
	    return i;

	case 4:		/* Escaped block designator */
	    cmdArr[count] = c;
	    state = 0;
	    break;

	default:		/* Add to command buffer */
	    cmdArr[count++] = c;
	    break;
	}
    }
    Tcl_AppendResult(htPtr->interp, "premature end of TCL command block",
	(char *)NULL);
    return -1;
}

/*
 * ----------------------------------------------------------------------
 *
 * ParseInput --
 *
 * 	Parse the input to the HText structure into an array of lines.
 *	Each entry contains the beginning index and end index of the
 *	characters in the text array which comprise the line.
 *
 *	|*|*|*|\n|T|h|i|s| |a| |l|i|n|e| |o|f| |t|e|x|t|.|\n|*|*|*|
 *                ^					  ^
 *	          textStart				  textEnd
 *
 *	Note that the end index contains the '\n'.
 *
 * Results:
 *	Returns TCL_OK or error depending if the file was read correctly.
 *
 * ----------------------------------------------------------------------
 */
static int
ParseInput(interp, htPtr, input, nBytes)
    Tcl_Interp *interp;
    HText *htPtr;
    char input[];
    int nBytes;
{
    int c;
    int i;
    char *textArr;
    char *cmdArr;
    int count, nLines;
    int length;
    int state;
    Line *linePtr;

    linePtr = CreateLine(htPtr);
    if (linePtr == NULL) {
	return TCL_ERROR;	/* Error allocating the line structure */
    }
    /*  Right now, we replace the text array instead of appending to it */

    linePtr->textStart = 0;

    /* In the worst case, assume the entire input could be Tcl commands */
    cmdArr = Blt_Malloc(sizeof(char) * (nBytes + 1));

    textArr = Blt_Malloc(sizeof(char) * (nBytes + 1));
    if (htPtr->charArr != NULL) {
	Blt_Free(htPtr->charArr);
    }
    htPtr->charArr = textArr;
    htPtr->nChars = 0;

    nLines = count = state = 0;
    htPtr->flags &= ~WIDGET_APPENDED;

    for (i = 0; i < nBytes; i++) {
	c = input[i];
	if (c == htPtr->specChar) {
	    state++;
	} else if (c == '\n') {
	    state = -1;
	} else if ((state == 0) && (c == '\\')) {
	    state = 3;
	} else {
	    state = 0;
	}
	switch (state) {
	case 2:		/* Block of Tcl commands found */
	    count--, i++;
	    length = CollectCommand(htPtr, input + i, nBytes - i, cmdArr);
	    if (length < 0) {
		goto error;
	    }
	    i += length;
	    linePtr->textEnd = count;
	    htPtr->nChars = count + 1;
	    if (Tcl_Eval(interp, cmdArr) != TCL_OK) {
		goto error;
	    }
	    if (htPtr->flags & WIDGET_APPENDED) {
		/* Indicates the location a embedded widget in the text array */
		textArr[count++] = ' ';
		htPtr->flags &= ~WIDGET_APPENDED;
	    }
	    state = 0;
	    break;

	case 4:		/* Escaped block designator */
	    textArr[count - 1] = c;
	    state = 0;
	    break;

	case -1:		/* End of line or input */
	    linePtr->textEnd = count;
	    textArr[count++] = '\n';
	    nLines++;
	    linePtr = CreateLine(htPtr);
	    if (linePtr == NULL) {
		goto error;
	    }
	    linePtr->textStart = count;
	    state = 0;
	    break;

	default:		/* Default action, add to text buffer */
	    textArr[count++] = c;
	    break;
	}
    }
    if (count > linePtr->textStart) {
	linePtr->textEnd = count;
	textArr[count++] = '\n';/* Every line must end with a '\n' */
	nLines++;
    }
    Blt_Free(cmdArr);
    /* Reset number of lines allocated */
    if (ResizeArray((char **)&(htPtr->lineArr), sizeof(Line), nLines,
	    htPtr->arraySize) != TCL_OK) {
	Tcl_AppendResult(interp, "can't reallocate array of lines", (char *)NULL);
	return TCL_ERROR;
    }
    htPtr->nLines = htPtr->arraySize = nLines;
    /*  and the size of the character array */
    if (ResizeArray(&(htPtr->charArr), sizeof(char), count,
	    nBytes) != TCL_OK) {
	Tcl_AppendResult(interp, "can't reallocate text character buffer",
	    (char *)NULL);
	return TCL_ERROR;
    }
    htPtr->nChars = count;
    return TCL_OK;
  error:
    Blt_Free(cmdArr);
    return TCL_ERROR;
}

static int
IncludeText(interp, htPtr, fileName)
    Tcl_Interp *interp;
    HText *htPtr;
    char *fileName;
{
    char *buffer;
    int result;
    int nBytes;

    if ((htPtr->text == NULL) && (fileName == NULL)) {
	return TCL_OK;		/* Empty text string */
    }
    if (fileName != NULL) {
	nBytes = ReadNamedFile(interp, fileName, &buffer);
	if (nBytes < 0) {
	    return TCL_ERROR;
	}
    } else {
	buffer = htPtr->text;
	nBytes = strlen(htPtr->text);
    }
    result = ParseInput(interp, htPtr, buffer, nBytes);
    if (fileName != NULL) {
	Blt_Free(buffer);
    }
    return result;
}

/* ARGSUSED */
static char *
TextVarProc(clientData, interp, name1, name2, flags)
    ClientData clientData;	/* Information about widget. */
    Tcl_Interp *interp;		/* Interpreter containing variable. */
    char *name1;		/* Name of variable. */
    char *name2;		/* Second part of variable name. */
    int flags;			/* Information about what happened. */
{
    HText *htPtr = clientData;
    HText *lasthtPtr;

    /* Check to see of this is the most recent trace */
    lasthtPtr = (HText *)Tcl_VarTraceInfo2(interp, name1, name2, flags,
	TextVarProc, NULL);
    if (lasthtPtr != htPtr) {
	return NULL;		/* Ignore all but most current trace */
    }
    if (flags & TCL_TRACE_READS) {
	char c;

	c = name2[0];
	if ((c == 'w') && (strcmp(name2, "widget") == 0)) {
	    Tcl_SetVar2(interp, name1, name2, Tk_PathName(htPtr->tkwin),
		flags);
	} else if ((c == 'l') && (strcmp(name2, "line") == 0)) {
	    char buf[80];
	    int lineNum;

	    lineNum = htPtr->nLines - 1;
	    if (lineNum < 0) {
		lineNum = 0;
	    }
	    sprintf(buf, "%d", lineNum);
	    Tcl_SetVar2(interp, name1, name2, buf, flags);
	} else if ((c == 'i') && (strcmp(name2, "index") == 0)) {
	    char buf[80];

	    sprintf(buf, "%d", htPtr->nChars - 1);
	    Tcl_SetVar2(interp, name1, name2, buf, flags);
	} else if ((c == 'f') && (strcmp(name2, "file") == 0)) {
	    char *fileName;

	    fileName = htPtr->fileName;
	    if (fileName == NULL) {
		fileName = "";
	    }
	    Tcl_SetVar2(interp, name1, name2, fileName, flags);
	} else {
	    return "?unknown?";
	}
    }
    return NULL;
}

static char *varNames[] =
{
    "widget", "line", "file", "index", (char *)NULL
};

static void
CreateTraces(htPtr)
    HText *htPtr;
{
    char **ptr;
    static char globalCmd[] = "global htext";

    /*
     * Make the traced variables global to the widget
     */
    Tcl_Eval(htPtr->interp, globalCmd);
    for (ptr = varNames; *ptr != NULL; ptr++) {
	Tcl_TraceVar2(htPtr->interp, "htext", *ptr,
	    (TCL_GLOBAL_ONLY | TCL_TRACE_READS), TextVarProc, htPtr);
    }
}

static void
DeleteTraces(htPtr)
    HText *htPtr;
{
    char **ptr;

    for (ptr = varNames; *ptr != NULL; ptr++) {
	Tcl_UntraceVar2(htPtr->interp, "htext", *ptr,
	    (TCL_GLOBAL_ONLY | TCL_TRACE_READS), TextVarProc, htPtr);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureText --
 *
 * 	This procedure is called to process an argv/argc list, plus
 *	the Tk option database, in order to configure (or reconfigure)
 *	a hypertext widget.
 *
 * 	The layout of the text must be calculated (by ComputeLayout)
 *	whenever particular options change; -font, -file, -linespacing
 *	and -text options. If the user has changes one of these options,
 *	it must be detected so that the layout can be recomputed. Since the
 *	coordinates of the layout are virtual, there is no need to adjust
 *	them if physical window attributes (window size, etc.)
 *	change.
 *
 * Results:
 *	The return value is a standard Tcl result.  If TCL_ERROR is
 * 	returned, then interp->result contains an error message.
 *
 * Side effects:
 *	Configuration information, such as text string, colors, font,
 * 	etc. get set for htPtr;  old resources get freed, if there were any.
 * 	The hypertext is redisplayed.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureText(interp, htPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    HText *htPtr;		/* Information about widget; may or may not
			         * already have values for some fields. */
{
    XGCValues gcValues;
    unsigned long gcMask;
    GC newGC;

    if (Blt_ConfigModified(configSpecs, "-font", "-linespacing", "-file",
	    "-text", "-width", "-height", (char *)NULL)) {
	/*
	 * These options change the layout of the text.  Width/height
	 * and rows/columns may change a relatively sized window or cavity.
	 */
	htPtr->flags |= (REQUEST_LAYOUT | TEXT_DIRTY);	/* Mark for update */
    }
    gcMask = GCForeground | GCFont;
    gcValues.font = Tk_FontId(htPtr->font);
    gcValues.foreground = htPtr->normalFg->pixel;
    newGC = Tk_GetGC(htPtr->tkwin, gcMask, &gcValues);
    if (htPtr->drawGC != NULL) {
	Tk_FreeGC(htPtr->display, htPtr->drawGC);
    }
    htPtr->drawGC = newGC;

    gcValues.foreground = htPtr->selFgColor->pixel;
    newGC = Tk_GetGC(htPtr->tkwin, gcMask, &gcValues);
    if (htPtr->selectGC != NULL) {
	Tk_FreeGC(htPtr->display, htPtr->selectGC);
    }
    htPtr->selectGC = newGC;

    if (htPtr->xScrollUnits < 1) {
	htPtr->xScrollUnits = 1;
    }
    if (htPtr->yScrollUnits < 1) {
	htPtr->yScrollUnits = 1;
    }
    if (htPtr->tile != NULL) {
	Blt_SetTileChangedProc(htPtr->tile, TileChangedProc, htPtr);
    }
    gcValues.foreground = htPtr->normalBg->pixel;
    newGC = Tk_GetGC(htPtr->tkwin, gcMask, &gcValues);
    if (htPtr->fillGC != NULL) {
	Tk_FreeGC(htPtr->display, htPtr->fillGC);
    }
    htPtr->fillGC = newGC;

    if (htPtr->nColumns > 0) {
	htPtr->reqWidth =
	    htPtr->nColumns * Tk_TextWidth(htPtr->font, "0", 1);
    }
    if (htPtr->nRows > 0) {
	Tk_FontMetrics fontMetrics;

	Tk_GetFontMetrics(htPtr->font, &fontMetrics);
	htPtr->reqHeight = htPtr->nRows * fontMetrics.linespace;
    }
    /*
     * If the either the -text or -file option changed, read in the
     * new text.  The -text option supersedes any -file option.
     */
    if (Blt_ConfigModified(configSpecs, "-file", "-text", (char *)NULL)) {
	int result;

	FreeText(htPtr);
	CreateTraces(htPtr);	/* Create variable traces */

	result = IncludeText(interp, htPtr, htPtr->fileName);

	DeleteTraces(htPtr);
	if (result == TCL_ERROR) {
	    FreeText(htPtr);
	    return TCL_ERROR;
	}
	ResetTextInfo(htPtr);
    }
    EventuallyRedraw(htPtr);
    return TCL_OK;
}

/* Layout Procedures */
/*
 * -----------------------------------------------------------------
 *
 * TranslateAnchor --
 *
 * 	Translate the coordinates of a given bounding box based
 *	upon the anchor specified.  The anchor indicates where
 *	the given xy position is in relation to the bounding box.
 *
 *  		nw --- n --- ne
 *  		|            |     x,y ---+
 *  		w   center   e      |     |
 *  		|            |      +-----+
 *  		sw --- s --- se
 *
 * Results:
 *	The translated coordinates of the bounding box are returned.
 *
 * -----------------------------------------------------------------
 */
static XPoint
TranslateAnchor(deltaX, deltaY, anchor)
    int deltaX, deltaY;		/* Difference between outer and inner regions
				 */
    Tk_Anchor anchor;		/* Direction of the anchor */
{
    XPoint point;

    point.x = point.y = 0;
    switch (anchor) {
    case TK_ANCHOR_NW:		/* Upper left corner */
	break;
    case TK_ANCHOR_W:		/* Left center */
	point.y = (deltaY / 2);
	break;
    case TK_ANCHOR_SW:		/* Lower left corner */
	point.y = deltaY;
	break;
    case TK_ANCHOR_N:		/* Top center */
	point.x = (deltaX / 2);
	break;
    case TK_ANCHOR_CENTER:	/* Centered */
	point.x = (deltaX / 2);
	point.y = (deltaY / 2);
	break;
    case TK_ANCHOR_S:		/* Bottom center */
	point.x = (deltaX / 2);
	point.y = deltaY;
	break;
    case TK_ANCHOR_NE:		/* Upper right corner */
	point.x = deltaX;
	break;
    case TK_ANCHOR_E:		/* Right center */
	point.x = deltaX;
	point.y = (deltaY / 2);
	break;
    case TK_ANCHOR_SE:		/* Lower right corner */
	point.x = deltaX;
	point.y = deltaY;
	break;
    }
    return point;
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeCavitySize --
 *
 *	Sets the width and height of the cavity based upon the
 *	requested size of the embedded widget.  The requested space also
 *	includes any external padding which has been designated for
 *	this window.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	The size of the cavity is set in the embedded widget information
 *	structure.  These values can effect how the embedded widget is
 *	packed into the master window.
 *
 *----------------------------------------------------------------------
 */
static void
ComputeCavitySize(winPtr)
    EmbeddedWidget *winPtr;
{
    int width, height;
    int twiceBW;

    twiceBW = 2 * Tk_Changes(winPtr->tkwin)->border_width;
    if (winPtr->reqCavityWidth > 0) {
	width = winPtr->reqCavityWidth;
    } else if (winPtr->relCavityWidth > 0.0) {
	width = (int)((double)Tk_Width(winPtr->htPtr->tkwin) *
	    winPtr->relCavityWidth + 0.5);
    } else {
	width = GetEmbeddedWidgetWidth(winPtr) + PADDING(winPtr->padX) + 
	    twiceBW;
    }
    winPtr->cavityWidth = width;

    if (winPtr->reqCavityHeight > 0) {
	height = winPtr->reqCavityHeight;
    } else if (winPtr->relCavityHeight > 0.0) {
	height = (int)((double)Tk_Height(winPtr->htPtr->tkwin) *
	    winPtr->relCavityHeight + 0.5);
    } else {
	height = GetEmbeddedWidgetHeight(winPtr) + PADDING(winPtr->padY) + 
	    twiceBW;
    }
    winPtr->cavityHeight = height;
}

/*
 *----------------------------------------------------------------------
 *
 * LayoutLine --
 *
 *	This procedure computes the total width and height needed
 *      to contain the text and widgets for a particular line.
 *      It also calculates the baseline of the text on the line with
 *	respect to the other widgets on the line.
 *
 * Results:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static void
LayoutLine(htPtr, linePtr)
    HText *htPtr;
    Line *linePtr;
{
    EmbeddedWidget *winPtr;
    int textStart, textLength;
    int maxAscent, maxDescent, maxHeight;
    int ascent, descent;
    int median;			/* Difference of font ascent/descent values */
    Blt_ChainLink *linkPtr;
    int x, y;
    int newX;
    Tk_FontMetrics fontMetrics;

    /* Initialize line defaults */
    Tk_GetFontMetrics(htPtr->font, &fontMetrics);
    maxAscent = fontMetrics.ascent;
    maxDescent = fontMetrics.descent;
    median = fontMetrics.ascent - fontMetrics.descent;
    ascent = descent = 0;	/* Suppress compiler warnings */

    /*
     * Pass 1: Determine the maximum ascent (baseline) and descent
     * needed for the line.  We'll need this for figuring the top,
     * bottom, and center anchors.
     */
    for (linkPtr = Blt_ChainFirstLink(linePtr->chainPtr); linkPtr != NULL;
	linkPtr = Blt_ChainNextLink(linkPtr)) {
	winPtr = Blt_ChainGetValue(linkPtr);
	if (winPtr->tkwin == NULL) {
	    continue;
	}
	ComputeCavitySize(winPtr);

	switch (winPtr->justify) {
	case JUSTIFY_TOP:
	    ascent = fontMetrics.ascent + winPtr->padTop;
	    descent = winPtr->cavityHeight - fontMetrics.ascent;
	    break;
	case JUSTIFY_CENTER:
	    ascent = (winPtr->cavityHeight + median) / 2;
	    descent = (winPtr->cavityHeight - median) / 2;
	    break;
	case JUSTIFY_BOTTOM:
	    ascent = winPtr->cavityHeight - fontMetrics.descent;
	    descent = fontMetrics.descent;
	    break;
	}
	if (descent > maxDescent) {
	    maxDescent = descent;
	}
	if (ascent > maxAscent) {
	    maxAscent = ascent;
	}
    }

    maxHeight = maxAscent + maxDescent + htPtr->leader;
    x = 0;			/* Always starts from x=0 */
    y = 0;			/* Suppress compiler warning */
    textStart = linePtr->textStart;

    /*
     * Pass 2: Find the placements of the text and widgets along each
     * line.
     */
    for (linkPtr = Blt_ChainFirstLink(linePtr->chainPtr); linkPtr != NULL;
	linkPtr = Blt_ChainNextLink(linkPtr)) {
	winPtr = Blt_ChainGetValue(linkPtr);
	if (winPtr->tkwin == NULL) {
	    continue;
	}
	/* Get the width of the text leading to the widget. */
	textLength = (winPtr->precedingTextEnd - textStart);
	if (textLength > 0) {
	    Tk_MeasureChars(htPtr->font, htPtr->charArr + textStart,
		textLength, 10000, TK_AT_LEAST_ONE, &newX);
	    winPtr->precedingTextWidth = newX;
	    x += newX;
	}
	switch (winPtr->justify) {
	case JUSTIFY_TOP:
	    y = maxAscent - fontMetrics.ascent;
	    break;
	case JUSTIFY_CENTER:
	    y = maxAscent - (winPtr->cavityHeight + median) / 2;
	    break;
	case JUSTIFY_BOTTOM:
	    y = maxAscent + fontMetrics.descent - winPtr->cavityHeight;
	    break;
	}
	winPtr->x = x, winPtr->y = y;

	/* Skip over trailing space */
	textStart = winPtr->precedingTextEnd + 1;

	x += winPtr->cavityWidth;
    }

    /*
     * This can be either the trailing piece of a line after the last widget
     * or the entire line if no widgets are embedded in it.
     */
    textLength = (linePtr->textEnd - textStart) + 1;
    if (textLength > 0) {
	Tk_MeasureChars(htPtr->font, htPtr->charArr + textStart,
	    textLength, 10000, DEF_TEXT_FLAGS, &newX);
	x += newX;
    }
    /* Update line parameters */
    if ((linePtr->width != x) || (linePtr->height != maxHeight) ||
	(linePtr->baseline != maxAscent)) {
	htPtr->flags |= TEXT_DIRTY;
    }
    linePtr->width = x;
    linePtr->height = maxHeight;
    linePtr->baseline = maxAscent;
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeLayout --
 *
 *	This procedure computes the total width and height needed
 *      to contain the text and widgets from all the lines of text.
 *      It merely sums the heights and finds the maximum width of
 *	all the lines.  The width and height are needed for scrolling.
 *
 * Results:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static void
ComputeLayout(htPtr)
    HText *htPtr;
{
    int count;
    Line *linePtr;
    int height, width;

    width = height = 0;
    for (count = 0; count < htPtr->nLines; count++) {
	linePtr = htPtr->lineArr + count;

	linePtr->offset = height;
	LayoutLine(htPtr, linePtr);
	height += linePtr->height;
	if (linePtr->width > width) {
	    width = linePtr->width;
	}
    }
    /*
     * Set changed flag if new layout changed size of virtual text.
     */
    if ((height != htPtr->worldHeight) || (width != htPtr->worldWidth)) {
	htPtr->worldHeight = height, htPtr->worldWidth = width;
	htPtr->flags |= TEXT_DIRTY;
    }
}

/* Display Procedures */
/*
 * ----------------------------------------------------------------------
 *
 * GetVisibleLines --
 *
 * 	Calculates which lines are visible using the height
 *      of the viewport and y offset from the top of the text.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Only those line between first and last inclusive are
 * 	redrawn.
 *
 * ----------------------------------------------------------------------
 */
static int
GetVisibleLines(htPtr)
    HText *htPtr;
{
    int topLine, bottomLine;
    int firstY, lastY;
    int lastLine;

    if (htPtr->nLines == 0) {
	htPtr->first = 0;
	htPtr->last = -1;
	return TCL_OK;
    }
    firstY = htPtr->pendingY;
    lastLine = htPtr->nLines - 1;

    /* First line */
    topLine = LineSearch(htPtr, firstY, 0, lastLine);
    if (topLine < 0) {
	/*
	 * This can't be. The y-coordinate offset must be corrupted.
	 */
	fprintf(stderr, "internal error: First position not found `%d'\n",
	    firstY);
	return TCL_ERROR;
    }
    htPtr->first = topLine;

    /*
     * If there is less text than window space, the bottom line is the
     * last line of text.  Otherwise search for the line at the bottom
     * of the window.
     */
    lastY = firstY + Tk_Height(htPtr->tkwin) - 1;
    if (lastY < htPtr->worldHeight) {
	bottomLine = LineSearch(htPtr, lastY, topLine, lastLine);
    } else {
	bottomLine = lastLine;
    }
    if (bottomLine < 0) {
	/*
	 * This can't be. The newY offset must be corrupted.
	 */
	fprintf(stderr, "internal error: Last position not found `%d'\n",
	    lastY);
#ifdef notdef
	fprintf(stderr, "worldHeight=%d,height=%d,top=%d,first=%d,last=%d\n",
	    htPtr->worldHeight, Tk_Height(htPtr->tkwin), firstY,
	    htPtr->lineArr[topLine].offset, htPtr->lineArr[lastLine].offset);
#endif
	return TCL_ERROR;
    }
    htPtr->last = bottomLine;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawSegment --
 *
 * 	Draws a line segment, designated by the segment structure.
 *	This routine handles the display of selected text by drawing
 *	a raised 3D border underneath the selected text.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The line segment is drawn on *draw*.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawSegment(htPtr, draw, linePtr, x, y, segPtr)
    HText *htPtr;
    Drawable draw;
    Line *linePtr;
    int x, y;
    Segment *segPtr;
{
    int lastX, curPos, nChars;
    int textLength;
    int selStart, selEnd, selLength;
    Tk_FontMetrics fontMetrics;

#ifdef notdef
    fprintf(stderr, "DS select: first=%d,last=%d text: first=%d,last=%d\n",
	htPtr->selFirst, htPtr->selLast, segPtr->textStart, segPtr->textEnd);
#endif
    textLength = (segPtr->textEnd - segPtr->textStart) + 1;
    if (textLength < 1) {
	return;
    }
    Tk_GetFontMetrics(htPtr->font, &fontMetrics);
    if ((segPtr->textEnd < htPtr->selFirst) ||
	(segPtr->textStart > htPtr->selLast)) {	/* No selected text */
	Tk_DrawChars(htPtr->display, draw, htPtr->drawGC, htPtr->font,
	    htPtr->charArr + segPtr->textStart, textLength - 1,
	    x, y + linePtr->baseline);
	return;
    }
    /*
     *	Text in a segment (with selected text) may have
     *	up to three regions:
     *
     *	1) the text before the start the selection
     *	2) the selected text itself (drawn in a raised border)
     *	3) the text following the selection.
     */

    selStart = segPtr->textStart;
    selEnd = segPtr->textEnd;
    if (htPtr->selFirst > segPtr->textStart) {
	selStart = htPtr->selFirst;
    }
    if (htPtr->selLast < segPtr->textEnd) {
	selEnd = htPtr->selLast;
    }
    selLength = (selEnd - selStart) + 1;
    lastX = x;
    curPos = segPtr->textStart;

    if (selStart > segPtr->textStart) {	/* Text preceding selection */
	nChars = (selStart - segPtr->textStart);
	Tk_MeasureChars(htPtr->font, htPtr->charArr + segPtr->textStart,
	    nChars, 10000, DEF_TEXT_FLAGS, &lastX);
	lastX += x;
	Tk_DrawChars(htPtr->display, draw, htPtr->drawGC, htPtr->font,
	    htPtr->charArr + segPtr->textStart, nChars, x,
	    y + linePtr->baseline);
	curPos = selStart;
    }
    if (selLength > 0) {	/* The selection itself */
	int width, nextX;

	Tk_MeasureChars(htPtr->font, htPtr->charArr + selStart,
	    selLength, 10000, DEF_TEXT_FLAGS, &nextX);
	nextX += x;
	width = (selEnd == linePtr->textEnd)
	    ? htPtr->worldWidth - htPtr->xOffset - lastX :
	    nextX - lastX;
	Tk_Fill3DRectangle(htPtr->tkwin, draw, htPtr->selBorder,
	    lastX, y + linePtr->baseline - fontMetrics.ascent,
	    width, fontMetrics.linespace, htPtr->selBorderWidth,
	    TK_RELIEF_RAISED);
	Tk_DrawChars(htPtr->display, draw, htPtr->selectGC,
	    htPtr->font, htPtr->charArr + selStart, selLength,
	    lastX, y + linePtr->baseline);
	lastX = nextX;
	curPos = selStart + selLength;
    }
    nChars = segPtr->textEnd - curPos;
    if (nChars > 0) {		/* Text following the selection */
	Tk_DrawChars(htPtr->display, draw, htPtr->drawGC, htPtr->font,
	    htPtr->charArr + curPos, nChars - 1, lastX, y + linePtr->baseline);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * MoveEmbeddedWidget --
 *
 * 	Move a embedded widget to a new location in the hypertext
 *	parent window.  If the window has no geometry (i.e. width,
 *	or height is 0), simply unmap to window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Each embedded widget is moved to its new location, generating
 *      Expose events in the parent for each embedded widget moved.
 *
 * ----------------------------------------------------------------------
 */
static void
MoveEmbeddedWidget(winPtr, offset)
    EmbeddedWidget *winPtr;
    int offset;
{
    int winWidth, winHeight;
    int width, height;
    int deltaX, deltaY;
    int x, y;
    int intBW;

    winWidth = GetEmbeddedWidgetWidth(winPtr);
    winHeight = GetEmbeddedWidgetHeight(winPtr);
    if ((winWidth < 1) || (winHeight < 1)) {
	if (Tk_IsMapped(winPtr->tkwin)) {
	    Tk_UnmapWindow(winPtr->tkwin);
	}
	return;
    }
    intBW = Tk_Changes(winPtr->tkwin)->border_width;
    x = (winPtr->x + intBW + winPtr->padLeft) -
	winPtr->htPtr->xOffset;
    y = offset + (winPtr->y + intBW + winPtr->padTop) -
	winPtr->htPtr->yOffset;

    width = winPtr->cavityWidth - (2 * intBW + PADDING(winPtr->padX));
    if (width < 0) {
	width = 0;
    }
    if ((width < winWidth) || (winPtr->fill & FILL_X)) {
	winWidth = width;
    }
    deltaX = width - winWidth;

    height = winPtr->cavityHeight - (2 * intBW + PADDING(winPtr->padY));
    if (height < 0) {
	height = 0;
    }
    if ((height < winHeight) || (winPtr->fill & FILL_Y)) {
	winHeight = height;
    }
    deltaY = height - winHeight;

    if ((deltaX > 0) || (deltaY > 0)) {
	XPoint point;

	point = TranslateAnchor(deltaX, deltaY, winPtr->anchor);
	x += point.x, y += point.y;
    }
    winPtr->winWidth = winWidth;
    winPtr->winHeight = winHeight;

    if ((x != Tk_X(winPtr->tkwin)) || (y != Tk_Y(winPtr->tkwin)) ||
	(winWidth != Tk_Width(winPtr->tkwin)) ||
	(winHeight != Tk_Height(winPtr->tkwin))) {
	Tk_MoveResizeWindow(winPtr->tkwin, x, y, winWidth, winHeight);
    }
    if (!Tk_IsMapped(winPtr->tkwin)) {
	Tk_MapWindow(winPtr->tkwin);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawPage --
 *
 * 	This procedure displays the lines of text and moves the widgets
 *      to their new positions.  It draws lines with regard to
 *	the direction of the scrolling.  The idea here is to make the
 *	text and buttons appear to move together. Otherwise you will
 *	get a "jiggling" effect where the windows appear to bump into
 *	the next line before that line is moved.  In the worst case, where
 *	every line has at least one widget, you can get an aquarium effect
 *      (lines appear to ripple up).
 *
 * 	The text area may start between line boundaries (to accommodate
 *	both variable height lines and constant scrolling). Subtract the
 *	difference of the page offset and the line offset from the starting
 *	coordinates. For horizontal scrolling, simply subtract the offset
 *	of the viewport. The window will clip the top of the first line,
 *	the bottom of the last line, whatever text extends to the left
 *	or right of the viewport on any line.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the line in its current
 * 	mode.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawPage(htPtr, deltaY)
    HText *htPtr;
    int deltaY;			/* Change from previous Y coordinate */
{
    Line *linePtr;
    EmbeddedWidget *winPtr;
    Tk_Window tkwin = htPtr->tkwin;
    Segment sgmt;
    Pixmap pixmap;
    int forceCopy = 0;
    int i;
    int lineNum;
    int x, y, lastY;
    Blt_ChainLink *linkPtr;
    int width, height;
    Display *display;

    display = htPtr->display;
    width = Tk_Width(tkwin);
    height = Tk_Height(tkwin);

    /* Create an off-screen pixmap for semi-smooth scrolling. */
    pixmap = Tk_GetPixmap(display, Tk_WindowId(tkwin), width, height,
	  Tk_Depth(tkwin));

    x = -(htPtr->xOffset);
    y = -(htPtr->yOffset);

    if (htPtr->tile != NULL) {
	if (htPtr->tileOffsetPage) {
	    Blt_SetTSOrigin(htPtr->tkwin, htPtr->tile, x, y);
	} else {
	    Blt_SetTileOrigin(htPtr->tkwin, htPtr->tile, 0, 0);
	}
	Blt_TileRectangle(htPtr->tkwin, pixmap, htPtr->tile, 0, 0, width, 
		height);
    } else {
	XFillRectangle(display, pixmap, htPtr->fillGC, 0, 0, width, height);
    }


    if (deltaY >= 0) {
	y += htPtr->lineArr[htPtr->first].offset;
	lineNum = htPtr->first;
	lastY = 0;
    } else {
	y += htPtr->lineArr[htPtr->last].offset;
	lineNum = htPtr->last;
	lastY = height;
    }
    forceCopy = 0;

    /* Draw each line */
    for (i = htPtr->first; i <= htPtr->last; i++) {

	/* Initialize character position in text buffer to start */
	linePtr = htPtr->lineArr + lineNum;
	sgmt.textStart = linePtr->textStart;
	sgmt.textEnd = linePtr->textEnd;

	/* Initialize X position */
	x = -(htPtr->xOffset);
	for (linkPtr = Blt_ChainFirstLink(linePtr->chainPtr); linkPtr != NULL;
	    linkPtr = Blt_ChainNextLink(linkPtr)) {
	    winPtr = Blt_ChainGetValue(linkPtr);

	    if (winPtr->tkwin != NULL) {
		winPtr->flags |= WIDGET_VISIBLE;
		MoveEmbeddedWidget(winPtr, linePtr->offset);
	    }
	    sgmt.textEnd = winPtr->precedingTextEnd - 1;
	    if (sgmt.textEnd >= sgmt.textStart) {
		DrawSegment(htPtr, pixmap, linePtr, x, y, &sgmt);
		x += winPtr->precedingTextWidth;
	    }
	    /* Skip over the extra trailing space which designates the widget */
	    sgmt.textStart = winPtr->precedingTextEnd + 1;
	    x += winPtr->cavityWidth;
	    forceCopy++;
	}

	/*
	 * This may be the text trailing the last widget or the entire
	 * line if no widgets occur on it.
	 */
	sgmt.textEnd = linePtr->textEnd;
	if (sgmt.textEnd >= sgmt.textStart) {
	    DrawSegment(htPtr, pixmap, linePtr, x, y, &sgmt);
	}
	/* Go to the top of the next line */
	if (deltaY >= 0) {
	    y += htPtr->lineArr[lineNum].height;
	    lineNum++;
	}
	if ((forceCopy > 0) && !(htPtr->flags & TEXT_DIRTY)) {
	    if (deltaY >= 0) {
		XCopyArea(display, pixmap, Tk_WindowId(tkwin), htPtr->drawGC,
			  0, lastY, width, y - lastY, 0, lastY);
	    } else {
		XCopyArea(display, pixmap, Tk_WindowId(tkwin), htPtr->drawGC,
			  0, y, width, lastY - y, 0, y);
	    }
	    forceCopy = 0;	/* Reset drawing flag */
	    lastY = y;		/* Record last Y position */
	}
	if ((deltaY < 0) && (lineNum > 0)) {
	    --lineNum;
	    y -= htPtr->lineArr[lineNum].height;
	}
    }
    /*
     * If the viewport was resized, draw the page in one operation.
     * Otherwise draw any left-over block of text (either at the top
     * or bottom of the page)
     */
    if (htPtr->flags & TEXT_DIRTY) {
	XCopyArea(display, pixmap, Tk_WindowId(tkwin),
	    htPtr->drawGC, 0, 0, width, height, 0, 0);
    } else if (lastY != y) {
	if (deltaY >= 0) {
	    height -= lastY;
	    XCopyArea(display, pixmap, Tk_WindowId(tkwin),
		htPtr->drawGC, 0, lastY, width, height, 0, lastY);
	} else {
	    height = lastY;
	    XCopyArea(display, pixmap, Tk_WindowId(tkwin),
		htPtr->drawGC, 0, 0, width, height, 0, 0);
	}
    }
    Tk_FreePixmap(display, pixmap);
}


static void
SendBogusEvent(tkwin)
    Tk_Window tkwin;
{
#define DONTPROPAGATE 0
    XEvent event;

    event.type = event.xexpose.type = Expose;
    event.xexpose.window = Tk_WindowId(tkwin);
    event.xexpose.display = Tk_Display(tkwin);
    event.xexpose.count = 0;
    event.xexpose.x = event.xexpose.y = 0;
    event.xexpose.width = Tk_Width(tkwin);
    event.xexpose.height = Tk_Height(tkwin);

    XSendEvent(Tk_Display(tkwin), Tk_WindowId(tkwin), DONTPROPAGATE,
	ExposureMask, &event);
}

/*
 * ----------------------------------------------------------------------
 *
 * DisplayText --
 *
 * 	This procedure is invoked to display a hypertext widget.
 *	Many of the operations which might ordinarily be performed
 *	elsewhere (e.g. in a configuration routine) are done here
 *	because of the somewhat unusual interactions occurring between
 *	the parent and embedded widgets.
 *
 *      Recompute the layout of the text if necessary. This is
 *	necessary if the world coordinate system has changed.
 *	Specifically, the following may have occurred:
 *
 *	  1.  a text attribute has changed (font, linespacing, etc.).
 *	  2.  widget option changed (anchor, width, height).
 *        3.  actual embedded widget was resized.
 *	  4.  new text string or file.
 *
 *      This is deferred to the display routine since potentially
 *      many of these may occur (especially embedded widget changes).
 *
 *	Set the vertical and horizontal scrollbars (if they are
 *	designated) by issuing a Tcl command.  Done here since
 *	the text window width and height are needed.
 *
 *	If the viewport position or contents have changed in the
 *	vertical direction,  the now out-of-view embedded widgets
 *	must be moved off the viewport.  Since embedded widgets will
 *	obscure the text window, it is imperative that the widgets
 *	are moved off before we try to redraw text in the same area.
 *      This is necessary only for vertical movements.  Horizontal
 *	embedded widget movements are handled automatically in the
 *	page drawing routine.
 *
 *      Get the new first and last line numbers for the viewport.
 *      These line numbers may have changed because either a)
 *      the viewport changed size or position, or b) the text
 *	(embedded widget sizes or text attributes) have changed.
 *
 *	If the viewport has changed vertically (i.e. the first or
 *      last line numbers have changed), move the now out-of-view
 *	embedded widgets off the viewport.
 *
 *      Potentially many expose events may be generated when the
 *	the individual embedded widgets are moved and/or resized.
 *	These events need to be ignored.  Since (I think) expose
 * 	events are guaranteed to happen in order, we can bracket
 *	them by sending phony events (via XSendEvent). The phony
 *      events turn on and off flags indicating which events
*	should be ignored.
 *
 *	Finally, the page drawing routine is called.
 *
 * Results:
 *	None.
 *
 * Side effects:
 * 	Commands are output to X to display the hypertext in its
 *	current mode.
 *
 * ----------------------------------------------------------------------
 */
static void
DisplayText(clientData)
    ClientData clientData;	/* Information about widget. */
{
    HText *htPtr = clientData;
    Tk_Window tkwin = htPtr->tkwin;
    int oldFirst;		/* First line of old viewport */
    int oldLast;		/* Last line of old viewport */
    int deltaY;			/* Change in viewport in Y direction */
    int reqWidth, reqHeight;

#ifdef notdef
    fprintf(stderr, "calling DisplayText(%s)\n", Tk_PathName(htPtr->tkwin));
#endif
    htPtr->flags &= ~REDRAW_PENDING;
    if (tkwin == NULL) {
	return;			/* Window has been destroyed */
    }
    if (htPtr->flags & REQUEST_LAYOUT) {
	/*
	 * Recompute the layout when widgets are created, deleted,
	 * moved, or resized.  Also when text attributes (such as
	 * font, linespacing) have changed.
	 */
	ComputeLayout(htPtr);
    }
    htPtr->lastWidth = Tk_Width(tkwin);
    htPtr->lastHeight = Tk_Height(tkwin);

    /*
     * Check the requested width and height.  We allow two modes:
     * 	1) If the user requested value is greater than zero, use it.
     *  2) Otherwise, let the window be as big as the virtual text.
     *	   This could be too large to display, so constrain it by
     *	   the maxWidth and maxHeight values.
     *
     * In any event, we need to calculate the size of the virtual
     * text and then make a geometry request.  This is so that widgets
     * whose size is relative to the master, will be set once.
     */
    if (htPtr->reqWidth > 0) {
	reqWidth = htPtr->reqWidth;
    } else {
	reqWidth = MIN(htPtr->worldWidth, htPtr->maxWidth);
	if (reqWidth < 1) {
	    reqWidth = 1;
	}
    }
    if (htPtr->reqHeight > 0) {
	reqHeight = htPtr->reqHeight;
    } else {
	reqHeight = MIN(htPtr->worldHeight, htPtr->maxHeight);
	if (reqHeight < 1) {
	    reqHeight = 1;
	}
    }
    if ((reqWidth != Tk_ReqWidth(tkwin)) || (reqHeight != Tk_ReqHeight(tkwin))) {
	Tk_GeometryRequest(tkwin, reqWidth, reqHeight);

	EventuallyRedraw(htPtr);
	return;			/* Try again with new geometry */
    }
    if (!Tk_IsMapped(tkwin)) {
	return;
    }
    /*
     * Turn off layout requests here, after the text window has been
     * mapped.  Otherwise, relative embedded widget size requests wrt
     * to the size of parent text window will be wrong.
     */
    htPtr->flags &= ~REQUEST_LAYOUT;

    /* Is there a pending goto request? */
    if (htPtr->flags & GOTO_PENDING) {
	htPtr->pendingY = htPtr->lineArr[htPtr->reqLineNum].offset;
	htPtr->flags &= ~GOTO_PENDING;
    }
    deltaY = htPtr->pendingY - htPtr->yOffset;
    oldFirst = htPtr->first, oldLast = htPtr->last;

    /*
     * If the viewport has changed size or position, or the text
     * and/or embedded widgets have changed, adjust the scrollbars to
     * new positions.
     */
    if (htPtr->flags & TEXT_DIRTY) {
	int width, height;

	width = Tk_Width(htPtr->tkwin);
	height = Tk_Height(htPtr->tkwin);

	/* Reset viewport origin and world extents */
	htPtr->xOffset = Blt_AdjustViewport(htPtr->pendingX,
	    htPtr->worldWidth, width,
	    htPtr->xScrollUnits, BLT_SCROLL_MODE_LISTBOX);
	htPtr->yOffset = Blt_AdjustViewport(htPtr->pendingY,
	    htPtr->worldHeight, height,
	    htPtr->yScrollUnits, BLT_SCROLL_MODE_LISTBOX);
	if (htPtr->xScrollCmdPrefix != NULL) {
	    Blt_UpdateScrollbar(htPtr->interp, htPtr->xScrollCmdPrefix,
		(double)htPtr->xOffset / htPtr->worldWidth,
		(double)(htPtr->xOffset + width) / htPtr->worldWidth);
	}
	if (htPtr->yScrollCmdPrefix != NULL) {
	    Blt_UpdateScrollbar(htPtr->interp, htPtr->yScrollCmdPrefix,
		(double)htPtr->yOffset / htPtr->worldHeight,
		(double)(htPtr->yOffset + height) / htPtr->worldHeight);
	}
	/*
	 * Given a new viewport or text height, find the first and
	 * last line numbers of the new viewport.
	 */
	if (GetVisibleLines(htPtr) != TCL_OK) {
	    return;
	}
    }
    /*
     * 	This is a kludge: Send an expose event before and after
     * 	drawing the page of text.  Since moving and resizing of the
     * 	embedded widgets will cause redundant expose events in the parent
     * 	window, the phony events will bracket them indicating no
     * 	action should be taken.
     */
    SendBogusEvent(tkwin);

    /*
     * If either the position of the viewport has changed or the size
     * of width or height of the entire text have changed, move the
     * widgets from the previous viewport out of the current
     * viewport. Worry only about the vertical embedded widget movements.
     * The page is always draw at full width and the viewport will clip
     * the text.
     */
    if ((htPtr->first != oldFirst) || (htPtr->last != oldLast)) {
	int offset;
	int i;
	int first, last;
	Blt_ChainLink *linkPtr;
	EmbeddedWidget *winPtr;

	/* Figure out which lines are now out of the viewport */

	if ((htPtr->first > oldFirst) && (htPtr->first <= oldLast)) {
	    first = oldFirst, last = htPtr->first;
	} else if ((htPtr->last < oldLast) && (htPtr->last >= oldFirst)) {
	    first = htPtr->last, last = oldLast;
	} else {
	    first = oldFirst, last = oldLast;
	}

	for (i = first; i <= last; i++) {
	    offset = htPtr->lineArr[i].offset;
	    for (linkPtr = Blt_ChainFirstLink(htPtr->lineArr[i].chainPtr);
		linkPtr != NULL; linkPtr = Blt_ChainNextLink(linkPtr)) {
		winPtr = Blt_ChainGetValue(linkPtr);
		if (winPtr->tkwin != NULL) {
		    MoveEmbeddedWidget(winPtr, offset);
		    winPtr->flags &= ~WIDGET_VISIBLE;
		}
	    }
	}
    }
    DrawPage(htPtr, deltaY);
    SendBogusEvent(tkwin);

    /* Reset flags */
    htPtr->flags &= ~TEXT_DIRTY;
}

/* Selection Procedures */
/*
 *----------------------------------------------------------------------
 *
 * TextSelectionProc --
 *
 *	This procedure is called back by Tk when the selection is
 *	requested by someone.  It returns part or all of the selection
 *	in a buffer provided by the caller.
 *
 * Results:
 *	The return value is the number of non-NULL bytes stored
 *	at buffer.  Buffer is filled (or partially filled) with a
 *	NULL-terminated string containing part or all of the selection,
 *	as given by offset and maxBytes.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static int
TextSelectionProc(clientData, offset, buffer, maxBytes)
    ClientData clientData;	/* Information about Text widget. */
    int offset;			/* Offset within selection of first
				 * character to be returned. */
    char *buffer;		/* Location in which to place
				 * selection. */
    int maxBytes;		/* Maximum number of bytes to place
				 * at buffer, not including terminating
				 * NULL character. */
{
    HText *htPtr = clientData;
    int size;

    if ((htPtr->selFirst < 0) || (!htPtr->exportSelection)) {
	return -1;
    }
    size = (htPtr->selLast - htPtr->selFirst) + 1 - offset;
    if (size > maxBytes) {
	size = maxBytes;
    }
    if (size <= 0) {
	return 0;		/* huh? */
    }
    strncpy(buffer, htPtr->charArr + htPtr->selFirst + offset, size);
    buffer[size] = '\0';
    return size;
}

/*
 *----------------------------------------------------------------------
 *
 * TextLostSelection --
 *
 *	This procedure is called back by Tk when the selection is
 *	grabbed away from a Text widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The existing selection is unhighlighted, and the window is
 *	marked as not containing a selection.
 *
 *----------------------------------------------------------------------
 */
static void
TextLostSelection(clientData)
    ClientData clientData;	/* Information about Text widget. */
{
    HText *htPtr = clientData;

    if ((htPtr->selFirst >= 0) && (htPtr->exportSelection)) {
	htPtr->selFirst = htPtr->selLast = -1;
	EventuallyRedraw(htPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SelectLine --
 *
 *	Modify the selection by moving both its anchored and un-anchored
 *	ends.  This could make the selection either larger or smaller.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The selection changes.
 *
 *----------------------------------------------------------------------
 */
static int
SelectLine(htPtr, tindex)
    HText *htPtr;		/* Information about widget. */
    int tindex;			/* Index of element that is to
				 * become the "other" end of the
				 * selection. */
{
    int selFirst, selLast;
    int lineNum;
    Line *linePtr;

    lineNum = IndexSearch(htPtr, tindex, 0, htPtr->nLines - 1);
    if (lineNum < 0) {
	char string[200];

	sprintf(string, "can't determine line number from index \"%d\"",
	    tindex);
	Tcl_AppendResult(htPtr->interp, string, (char *)NULL);
	return TCL_ERROR;
    }
    linePtr = htPtr->lineArr + lineNum;
    /*
     * Grab the selection if we don't own it already.
     */
    if ((htPtr->exportSelection) && (htPtr->selFirst == -1)) {
	Tk_OwnSelection(htPtr->tkwin, XA_PRIMARY, TextLostSelection, htPtr);
    }
    selFirst = linePtr->textStart;
    selLast = linePtr->textEnd;
    htPtr->selAnchor = tindex;
    if ((htPtr->selFirst != selFirst) ||
	(htPtr->selLast != selLast)) {
	htPtr->selFirst = selFirst;
	htPtr->selLast = selLast;
	EventuallyRedraw(htPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SelectWord --
 *
 *	Modify the selection by moving both its anchored and un-anchored
 *	ends.  This could make the selection either larger or smaller.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The selection changes.
 *
 *----------------------------------------------------------------------
 */
static int
SelectWord(htPtr, tindex)
    HText *htPtr;		/* Information about widget. */
    int tindex;			/* Index of element that is to
				 * become the "other" end of the
				 * selection. */
{
    int selFirst, selLast;
    int i;

    for (i = tindex; i < htPtr->nChars; i++) {
	if (isspace(UCHAR(htPtr->charArr[i]))) {
	    break;
	}
    }
    selLast = i - 1;
    for (i = tindex; i >= 0; i--) {
	if (isspace(UCHAR(htPtr->charArr[i]))) {
	    break;
	}
    }
    selFirst = i + 1;
    if (selFirst > selLast) {
	selFirst = selLast = tindex;
    }
    /*
     * Grab the selection if we don't own it already.
     */
    if ((htPtr->exportSelection) && (htPtr->selFirst == -1)) {
	Tk_OwnSelection(htPtr->tkwin, XA_PRIMARY, TextLostSelection, htPtr);
    }
    htPtr->selAnchor = tindex;
    if ((htPtr->selFirst != selFirst) || (htPtr->selLast != selLast)) {
	htPtr->selFirst = selFirst, htPtr->selLast = selLast;
	EventuallyRedraw(htPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SelectTextBlock --
 *
 *	Modify the selection by moving its un-anchored end.  This
 *	could make the selection either larger or smaller.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The selection changes.
 *
 *----------------------------------------------------------------------
 */
static int
SelectTextBlock(htPtr, tindex)
    HText *htPtr;		/* Information about widget. */
    int tindex;			/* Index of element that is to
				 * become the "other" end of the
				 * selection. */
{
    int selFirst, selLast;

    /*
     * Grab the selection if we don't own it already.
     */

    if ((htPtr->exportSelection) && (htPtr->selFirst == -1)) {
	Tk_OwnSelection(htPtr->tkwin, XA_PRIMARY, TextLostSelection, htPtr);
    }
    /*  If the anchor hasn't been set yet, assume the beginning of the text*/
    if (htPtr->selAnchor < 0) {
	htPtr->selAnchor = 0;
    }
    if (htPtr->selAnchor <= tindex) {
	selFirst = htPtr->selAnchor;
	selLast = tindex;
    } else {
	selFirst = tindex;
	selLast = htPtr->selAnchor;
    }
    if ((htPtr->selFirst != selFirst) || (htPtr->selLast != selLast)) {
	htPtr->selFirst = selFirst, htPtr->selLast = selLast;
	EventuallyRedraw(htPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SelectOp --
 *
 *	This procedure handles the individual options for text
 *	selections.  The selected text is designated by start and end
 *	indices into the text pool.  The selected segment has both a
 *	anchored and unanchored ends.  The following selection
 *	operations are implemented:
 *
 *	  "adjust"	- resets either the first or last index
 *			  of the selection.
 *	  "clear"	- clears the selection. Sets first/last
 *			  indices to -1.
 *	  "from"	- sets the index of the selection anchor.
 *	  "line"	- sets the first of last indices to the
 *			  start and end of the line at the
 *			  designated point.
 *	  "present"	- return "1" if a selection is available,
 *			  "0" otherwise.
 *	  "range"	- sets the first and last indices.
 *	  "to"		- sets the index of the un-anchored end.
 *	  "word"	- sets the first of last indices to the
 *			  start and end of the word at the
 *			  designated point.
 * Results:
 *	None.
 *
 * Side effects:
 *	The selection changes.
 *
 *----------------------------------------------------------------------
 */
static int
SelectOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;
    char **argv;
{
    int iselection;
    unsigned int length;
    int result = TCL_OK;
    char c;

    length = strlen(argv[2]);
    c = argv[2][0];
    if ((c == 'c') && (strncmp(argv[2], "clear", length) == 0)) {
	if (argc != 3) {
	    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
		" selection clear\"", (char *)NULL);
	    return TCL_ERROR;
	}
	if (htPtr->selFirst != -1) {
	    htPtr->selFirst = htPtr->selLast = -1;
	    EventuallyRedraw(htPtr);
	}
	return TCL_OK;
    } else if ((c == 'p') && (strncmp(argv[2], "present", length) == 0)) {
	if (argc != 3) {
	    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
		" selection present\"", (char *)NULL);
	    return TCL_ERROR;
	}
	Tcl_AppendResult(interp, (htPtr->selFirst != -1) ? "0" : "1",
	    (char *)NULL);
	return TCL_OK;
    } else if ((c == 'r') && (strncmp(argv[2], "range", length) == 0)) {
	int selFirst, selLast;

	if (argc != 5) {
	    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
		" selection range first last\"", (char *)NULL);
	    return TCL_ERROR;
	}
	if (GetIndex(htPtr, argv[3], &selFirst) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (GetIndex(htPtr, argv[4], &selLast) != TCL_OK) {
	    return TCL_ERROR;
	}
	htPtr->selAnchor = selFirst;
	result = SelectTextBlock(htPtr, selLast);
	return TCL_OK;
    }
    if (argc != 4) {
	Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
	    " selection ", argv[2], " index\"", (char *)NULL);
	return TCL_ERROR;
    }
    if (GetIndex(htPtr, argv[3], &iselection) != TCL_OK) {
	return TCL_ERROR;
    }
    if ((c == 'f') && (strncmp(argv[2], "from", length) == 0)) {
	htPtr->selAnchor = iselection;
    } else if ((c == 'a') && (strncmp(argv[2], "adjust", length) == 0)) {
	int half1, half2;

	half1 = (htPtr->selFirst + htPtr->selLast) / 2;
	half2 = (htPtr->selFirst + htPtr->selLast + 1) / 2;
	if (iselection < half1) {
	    htPtr->selAnchor = htPtr->selLast;
	} else if (iselection > half2) {
	    htPtr->selAnchor = htPtr->selFirst;
	}
	result = SelectTextBlock(htPtr, iselection);
    } else if ((c == 't') && (strncmp(argv[2], "to", length) == 0)) {
	result = SelectTextBlock(htPtr, iselection);
    } else if ((c == 'w') && (strncmp(argv[2], "word", length) == 0)) {
	result = SelectWord(htPtr, iselection);
    } else if ((c == 'l') && (strncmp(argv[2], "line", length) == 0)) {
	result = SelectLine(htPtr, iselection);
    } else {
	Tcl_AppendResult(interp, "bad selection operation \"", argv[2],
	    "\": should be \"adjust\", \"clear\", \"from\", \"line\", \
\"present\", \"range\", \"to\", or \"word\"", (char *)NULL);
	return TCL_ERROR;
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * GotoOp --
 *
 *	Move the top line of the viewport to the new location based
 *	upon the given line number.  Force out-of-range requests to the
 *	top or bottom of text.
 *
 * Results:
 *	A standard Tcl result. If TCL_OK, interp->result contains the
 *	current line number.
 *
 * Side effects:
 *	At the next idle point, the text viewport will be move to the
 *	new line.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
GotoOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;		/* Not used. */
    int argc;
    char **argv;
{
    int line;

    line = htPtr->first;
    if (argc == 3) {
	int tindex;

	if (GetIndex(htPtr, argv[2], &tindex) != TCL_OK) {
	    return TCL_ERROR;
	}
	line = IndexSearch(htPtr, tindex, 0, htPtr->nLines - 1);
	if (line < 0) {
	    char string[200];

	    sprintf(string, "can't determine line number from index \"%d\"",
		tindex);
	    Tcl_AppendResult(htPtr->interp, string, (char *)NULL);
	    return TCL_ERROR;
	}
	htPtr->reqLineNum = line;
	htPtr->flags |= TEXT_DIRTY;

	/*
	 * Make only a request for a change in the viewport.  Defer
	 * the actual scrolling until the text layout is adjusted at
	 * the next idle point.
	 */
	if (line != htPtr->first) {
	    htPtr->flags |= GOTO_PENDING;
	    EventuallyRedraw(htPtr);
	}
    }
    Tcl_SetResult(htPtr->interp, Blt_Itoa(line), TCL_VOLATILE);
    return TCL_OK;
}


static int
XViewOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;
    char **argv;
{
    int width, worldWidth;

    width = Tk_Width(htPtr->tkwin);
    worldWidth = htPtr->worldWidth;
    if (argc == 2) {
	double fract;

	/* Report first and last fractions */
	fract = (double)htPtr->xOffset / worldWidth;
	Tcl_AppendElement(interp, Blt_Dtoa(interp, CLAMP(fract, 0.0, 1.0)));
	fract = (double)(htPtr->xOffset + width) / worldWidth;
	Tcl_AppendElement(interp, Blt_Dtoa(interp, CLAMP(fract, 0.0, 1.0)));
	return TCL_OK;
    }
    htPtr->pendingX = htPtr->xOffset;
    if (Blt_GetScrollInfo(interp, argc - 2, argv + 2, &(htPtr->pendingX),
	    worldWidth, width, htPtr->xScrollUnits, BLT_SCROLL_MODE_LISTBOX) 
	!= TCL_OK) {
	return TCL_ERROR;
    }
    htPtr->flags |= TEXT_DIRTY;
    EventuallyRedraw(htPtr);
    return TCL_OK;
}

static int
YViewOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;
    char **argv;
{
    int height, worldHeight;

    height = Tk_Height(htPtr->tkwin);
    worldHeight = htPtr->worldHeight;
    if (argc == 2) {
	double fract;

	/* Report first and last fractions */
	fract = (double)htPtr->yOffset / worldHeight;
	Tcl_AppendElement(interp, Blt_Dtoa(interp, CLAMP(fract, 0.0, 1.0)));
	fract = (double)(htPtr->yOffset + height) / worldHeight;
	Tcl_AppendElement(interp, Blt_Dtoa(interp, CLAMP(fract, 0.0, 1.0)));
	return TCL_OK;
    }
    htPtr->pendingY = htPtr->yOffset;
    if (Blt_GetScrollInfo(interp, argc - 2, argv + 2, &(htPtr->pendingY),
	    worldHeight, height, htPtr->yScrollUnits, BLT_SCROLL_MODE_LISTBOX)
	!= TCL_OK) {
	return TCL_ERROR;
    }
    htPtr->flags |= TEXT_DIRTY;
    EventuallyRedraw(htPtr);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * AppendOp --
 *
 * 	This procedure embeds a Tk widget into the hypertext.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	Memory is allocated.  EmbeddedWidget gets configured.
 *
 * ----------------------------------------------------------------------
 */
static int
AppendOp(htPtr, interp, argc, argv)
    HText *htPtr;		/* Hypertext widget */
    Tcl_Interp *interp;		/* Interpreter associated with widget */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings. */
{
    Line *linePtr;
    EmbeddedWidget *winPtr;

    winPtr = CreateEmbeddedWidget(htPtr, argv[2]);
    if (winPtr == NULL) {
	return TCL_ERROR;
    }
    if (Tk_ConfigureWidget(interp, htPtr->tkwin, widgetConfigSpecs,
	    argc - 3, argv + 3, (char *)winPtr, 0) != TCL_OK) {
	return TCL_ERROR;
    }
    /*
     * Append widget to list of embedded widgets of the last line.
     */
    linePtr = GetLastLine(htPtr);
    if (linePtr == NULL) {
	Tcl_AppendResult(htPtr->interp, "can't allocate line structure",
	    (char *)NULL);
	return TCL_ERROR;
    }
    Blt_ChainAppend(linePtr->chainPtr, winPtr);
    linePtr->width += winPtr->cavityWidth;
    winPtr->precedingTextEnd = linePtr->textEnd;

    htPtr->flags |= (WIDGET_APPENDED | REQUEST_LAYOUT);
    EventuallyRedraw(htPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * WindowsOp --
 *
 *	Returns a list of all the pathNames of embedded widgets of the
 *	HText widget.  If a pattern argument is given, only the names
 *	of windows matching it will be placed into the list.
 *
 * Results:
 *	Standard Tcl result.  If TCL_OK, interp->result will contain
 *	the list of the embedded widget pathnames.  Otherwise it will
 *	contain an error message.
 *
 *----------------------------------------------------------------------
 */
static int
WindowsOp(htPtr, interp, argc, argv)
    HText *htPtr;		/* Hypertext widget record */
    Tcl_Interp *interp;		/* Interpreter associated with widget */
    int argc;
    char **argv;
{
    EmbeddedWidget *winPtr;
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    char *name;

    for (hPtr = Blt_FirstHashEntry(&(htPtr->widgetTable), &cursor);
	hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	winPtr = (EmbeddedWidget *)Blt_GetHashValue(hPtr);
	if (winPtr->tkwin == NULL) {
	    fprintf(stderr, "window `%s' is null\n",
		Tk_PathName(Blt_GetHashKey(&(htPtr->widgetTable), hPtr)));
	    continue;
	}
	name = Tk_PathName(winPtr->tkwin);
	if ((argc == 2) || (Tcl_StringMatch(name, argv[2]))) {
	    Tcl_AppendElement(interp, name);
	}
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
CgetOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;			/* Not used. */
    char **argv;
{
    char *itemPtr;
    Tk_ConfigSpec *specsPtr;

    if ((argc > 2) && (argv[2][0] == '.')) {
	Tk_Window tkwin;
	EmbeddedWidget *winPtr;

	/* EmbeddedWidget window to be configured */
	tkwin = Tk_NameToWindow(interp, argv[2], htPtr->tkwin);
	if (tkwin == NULL) {
	    return TCL_ERROR;
	}
	winPtr = FindEmbeddedWidget(htPtr, tkwin);
	if (winPtr == NULL) {
	    Tcl_AppendResult(interp, "window \"", argv[2],
		"\" is not managed by \"", argv[0], "\"", (char *)NULL);
	    return TCL_ERROR;
	}
	specsPtr = widgetConfigSpecs;
	itemPtr = (char *)winPtr;
	argv++;
	argc--;
    } else {
	specsPtr = configSpecs;
	itemPtr = (char *)htPtr;
    }
    return Tk_ConfigureValue(interp, htPtr->tkwin, specsPtr, itemPtr,
	    argv[2], 0);
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 * 	This procedure is called to process an argv/argc list, plus
 *	the Tk option database, in order to configure (or reconfigure)
 *	a hypertext widget.
 *
 * Results:
 *	A standard Tcl result.  If TCL_ERROR is returned, then
 *	interp->result contains an error message.
 *
 * Side effects:
 *	Configuration information, such as text string, colors, font,
 * 	etc. get set for htPtr;  old resources get freed, if there were any.
 * 	The hypertext is redisplayed.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;
    char **argv;
{
    char *itemPtr;
    Tk_ConfigSpec *specsPtr;

    if ((argc > 2) && (argv[2][0] == '.')) {
	Tk_Window tkwin;
	EmbeddedWidget *winPtr;

	/* EmbeddedWidget window to be configured */
	tkwin = Tk_NameToWindow(interp, argv[2], htPtr->tkwin);
	if (tkwin == NULL) {
	    return TCL_ERROR;
	}
	winPtr = FindEmbeddedWidget(htPtr, tkwin);
	if (winPtr == NULL) {
	    Tcl_AppendResult(interp, "window \"", argv[2],
		"\" is not managed by \"", argv[0], "\"", (char *)NULL);
	    return TCL_ERROR;
	}
	specsPtr = widgetConfigSpecs;
	itemPtr = (char *)winPtr;
	argv++;
	argc--;
    } else {
	specsPtr = configSpecs;
	itemPtr = (char *)htPtr;
    }
    if (argc == 2) {
	return Tk_ConfigureInfo(interp, htPtr->tkwin, specsPtr, itemPtr,
		(char *)NULL, 0);
    } else if (argc == 3) {
	return Tk_ConfigureInfo(interp, htPtr->tkwin, specsPtr, itemPtr,
		argv[2], 0);
    }
    if (Tk_ConfigureWidget(interp, htPtr->tkwin, specsPtr, argc - 2,
	    argv + 2, itemPtr, TK_CONFIG_ARGV_ONLY) != TCL_OK) {
	return TCL_ERROR;
    }
    if (itemPtr == (char *)htPtr) {
	/* Reconfigure the master */
	if (ConfigureText(interp, htPtr) != TCL_OK) {
	    return TCL_ERROR;
	}
    } else {
	htPtr->flags |= REQUEST_LAYOUT;
    }
    EventuallyRedraw(htPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ScanOp --
 *
 *	Implements the quick scan for hypertext widgets.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
ScanOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;			/* Not used. */
    char **argv;
{
    int x, y;
    char c;
    unsigned int length;


    if (Blt_GetXY(interp, htPtr->tkwin, argv[3], &x, &y) != TCL_OK) {
	return TCL_ERROR;
    }
    c = argv[2][0];
    length = strlen(argv[2]);
    if ((c == 'm') && (strncmp(argv[2], "mark", length) == 0)) {
	htPtr->scanMark.x = x, htPtr->scanMark.y = y;
	htPtr->scanPt.x = htPtr->xOffset;
	htPtr->scanPt.y = htPtr->yOffset;

    } else if ((c == 'd') && (strncmp(argv[2], "dragto", length) == 0)) {
	int px, py;

	px = htPtr->scanPt.x - (10 * (x - htPtr->scanMark.x));
	py = htPtr->scanPt.y - (10 * (y - htPtr->scanMark.y));

	if (px < 0) {
	    px = htPtr->scanPt.x = 0;
	    htPtr->scanMark.x = x;
	} else if (px >= htPtr->worldWidth) {
	    px = htPtr->scanPt.x = htPtr->worldWidth - htPtr->xScrollUnits;
	    htPtr->scanMark.x = x;
	}
	if (py < 0) {
	    py = htPtr->scanPt.y = 0;
	    htPtr->scanMark.y = y;
	} else if (py >= htPtr->worldHeight) {
	    py = htPtr->scanPt.y = htPtr->worldHeight - htPtr->yScrollUnits;
	    htPtr->scanMark.y = y;
	}
	if ((py != htPtr->pendingY) || (px != htPtr->pendingX)) {
	    htPtr->pendingX = px, htPtr->pendingY = py;
	    htPtr->flags |= TEXT_DIRTY;
	    EventuallyRedraw(htPtr);
	}
    } else {
	Tcl_AppendResult(interp, "bad scan operation \"", argv[2],
	    "\": should be either \"mark\" or \"dragto\"", (char *)NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SearchOp --
 *
 *	Returns the linenumber of the next line matching the given
 *	pattern within the range of lines provided.  If the first
 *	line number is greater than the last, the search is done in
 *	reverse.
 *
 *----------------------------------------------------------------------
 */
static int
SearchOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;
    char **argv;
{
    char *startPtr, *endPtr;
    char saved;
    Tcl_RegExp regExpToken;
    int iFirst, iLast;
    int matchStart, matchEnd;
    int match;

    regExpToken = Tcl_RegExpCompile(interp, argv[2]);
    if (regExpToken == NULL) {
	return TCL_ERROR;
    }
    iFirst = 0;
    iLast = htPtr->nChars;
    if (argc > 3) {
	if (GetIndex(htPtr, argv[3], &iFirst) != TCL_OK) {
	    return TCL_ERROR;
	}
    }
    if (argc == 4) {
	if (GetIndex(htPtr, argv[4], &iLast) != TCL_OK) {
	    return TCL_ERROR;
	}
    }
    if (iLast < iFirst) {
	return TCL_ERROR;
    }
    matchStart = matchEnd = -1;
    startPtr = htPtr->charArr + iFirst;
    endPtr = htPtr->charArr + (iLast + 1);
    saved = *endPtr;
    *endPtr = '\0';		/* Make the line a string by changing the
				 * '\n' into a NUL byte before searching */
    match = Tcl_RegExpExec(interp, regExpToken, startPtr, startPtr);
    *endPtr = saved;
    if (match < 0) {
	return TCL_ERROR;
    } else if (match > 0) {
	Tcl_RegExpRange(regExpToken, 0, &startPtr, &endPtr);
	if ((startPtr != NULL) || (endPtr != NULL)) {
	    matchStart = startPtr - htPtr->charArr;
	    matchEnd = endPtr - htPtr->charArr - 1;
	}
    }
    if (match > 0) {
	Tcl_AppendElement(interp, Blt_Itoa(matchStart));
	Tcl_AppendElement(interp, Blt_Itoa(matchEnd));
    } else {
	Tcl_ResetResult(interp);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RangeOp --
 *
 *	Returns the characters designated by the range of elements.
 *
 *----------------------------------------------------------------------
 */
static int
RangeOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;
    char **argv;
{
    char *startPtr, *endPtr;
    char saved;
    int textFirst, textLast;

    textFirst = htPtr->selFirst;
    textLast = htPtr->selLast;
    if (textFirst < 0) {
	textFirst = 0;
	textLast = htPtr->nChars - 1;
    }
    if (argc > 2) {
	if (GetIndex(htPtr, argv[2], &textFirst) != TCL_OK) {
	    return TCL_ERROR;
	}
    }
    if (argc == 4) {
	if (GetIndex(htPtr, argv[3], &textLast) != TCL_OK) {
	    return TCL_ERROR;
	}
    }
    if (textLast < textFirst) {
	Tcl_AppendResult(interp, "first index is greater than last", (char *)NULL);
	return TCL_ERROR;
    }
    startPtr = htPtr->charArr + textFirst;
    endPtr = htPtr->charArr + (textLast + 1);
    saved = *endPtr;
    *endPtr = '\0';		/* Make the line into a string by
				 * changing the * '\n' into a '\0'
				 * before copying */
    Tcl_SetResult(interp, startPtr, TCL_VOLATILE);
    *endPtr = saved;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * IndexOp --
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
IndexOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;			/* Not used. */
    char **argv;
{
    int tindex;

    if (GetIndex(htPtr, argv[2], &tindex) != TCL_OK) {
	return TCL_ERROR;
    }
    Tcl_SetResult(interp, Blt_Itoa(tindex), TCL_VOLATILE);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * LinePosOp --
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
LinePosOp(htPtr, interp, argc, argv)
    HText *htPtr;
    Tcl_Interp *interp;
    int argc;			/* Not used. */
    char **argv;
{
    int line, cpos, tindex;
    char string[200];

    if (GetIndex(htPtr, argv[2], &tindex) != TCL_OK) {
	return TCL_ERROR;
    }
    if (GetTextPosition(htPtr, tindex, &line, &cpos) != TCL_OK) {
	return TCL_ERROR;
    }
    sprintf(string, "%d.%d", line, cpos);
    Tcl_SetResult(interp, string, TCL_VOLATILE);
    return TCL_OK;
}

/*
 * --------------------------------------------------------------
 *
 * TextWidgetCmd --
 *
 * 	This procedure is invoked to process the Tcl command that
 *	corresponds to a widget managed by this module. See the user
 * 	documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 * --------------------------------------------------------------
 */

static Blt_OpSpec textOps[] =
{
    {"append", 1, (Blt_Op)AppendOp, 3, 0, "window ?option value?...",},
    {"cget", 2, (Blt_Op)CgetOp, 3, 3, "?window? option",},
    {"configure", 2, (Blt_Op)ConfigureOp, 2, 0,
	"?window? ?option value?...",},
    {"gotoline", 2, (Blt_Op)GotoOp, 2, 3, "?line?",},
    {"index", 1, (Blt_Op)IndexOp, 3, 3, "string",},
    {"linepos", 1, (Blt_Op)LinePosOp, 3, 3, "string",},
    {"range", 2, (Blt_Op)RangeOp, 2, 4, "?from? ?to?",},
    {"scan", 2, (Blt_Op)ScanOp, 4, 4, "oper @x,y",},
    {"search", 3, (Blt_Op)SearchOp, 3, 5, "pattern ?from? ?to?",},
    {"selection", 3, (Blt_Op)SelectOp, 3, 5, "oper ?index?",},
    {"windows", 6, (Blt_Op)WindowsOp, 2, 3, "?pattern?",},
    {"xview", 1, (Blt_Op)XViewOp, 2, 5,
	"?moveto fract? ?scroll number what?",},
    {"yview", 1, (Blt_Op)YViewOp, 2, 5,
	"?moveto fract? ?scroll number what?",},
};
static int nTextOps = sizeof(textOps) / sizeof(Blt_OpSpec);

static int
TextWidgetCmd(clientData, interp, argc, argv)
    ClientData clientData;	/* Information about hypertext widget. */
    Tcl_Interp *interp;		/* Current interpreter. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings. */
{
    Blt_Op proc;
    int result;
    HText *htPtr = clientData;

    proc = Blt_GetOp(interp, nTextOps, textOps, BLT_OP_ARG1, argc, argv, 0);
    if (proc == NULL) {
	return TCL_ERROR;
    }
    Tcl_Preserve(htPtr);
    result = (*proc) (htPtr, interp, argc, argv);
    Tcl_Release(htPtr);
    return result;
}

/*
 * --------------------------------------------------------------
 *
 * TextCmd --
 *
 * 	This procedure is invoked to process the "htext" Tcl command.
 *	See the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 * --------------------------------------------------------------
 */
/* ARGSUSED */
static int
TextCmd(clientData, interp, argc, argv)
    ClientData clientData;	/* Main window associated with interpreter. */
    Tcl_Interp *interp;		/* Current interpreter. */
    int argc;			/* Number of arguments. */
    char **argv;		/* Argument strings. */
{
    HText *htPtr;
    Screen *screenPtr;
    Tk_Window tkwin;

    if (argc < 2) {
	Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
	    " pathName ?option value?...\"", (char *)NULL);
	return TCL_ERROR;
    }
    htPtr = Blt_Calloc(1, sizeof(HText));
    assert(htPtr);
    tkwin = Tk_MainWindow(interp);
    tkwin = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *)NULL);
    if (tkwin == NULL) {
	Blt_Free(htPtr);
	return TCL_ERROR;
    }
    /* Initialize the new hypertext widget */

    Tk_SetClass(tkwin, "Htext");
    htPtr->tkwin = tkwin;
    htPtr->display = Tk_Display(tkwin);
    htPtr->interp = interp;
    htPtr->nLines = htPtr->arraySize = 0;
    htPtr->leader = 1;
    htPtr->xScrollUnits = htPtr->yScrollUnits = 10;
    htPtr->nRows = htPtr->nColumns = 0;
    htPtr->selFirst = htPtr->selLast = -1;
    htPtr->selAnchor = 0;
    htPtr->exportSelection = TRUE;
    htPtr->selBorderWidth = 2;
    screenPtr = Tk_Screen(htPtr->tkwin);
    htPtr->maxWidth = WidthOfScreen(screenPtr);
    htPtr->maxHeight = HeightOfScreen(screenPtr);
    Blt_InitHashTable(&(htPtr->widgetTable), BLT_ONE_WORD_KEYS);

    Tk_CreateSelHandler(tkwin, XA_PRIMARY, XA_STRING, TextSelectionProc,
	htPtr, XA_STRING);
    Tk_CreateEventHandler(tkwin, ExposureMask | StructureNotifyMask,
	TextEventProc, htPtr);
#if (TK_MAJOR_VERSION > 4)
    Blt_SetWindowInstanceData(tkwin, htPtr);
#endif
    /*
     * -----------------------------------------------------------------
     *
     *  Create the widget command before configuring the widget. This
     *  is because the "-file" and "-text" options may have embedded
     *  commands that self-reference the widget through the
     *  "$blt_htext(widget)" variable.
     *
     * ------------------------------------------------------------------
     */
    htPtr->cmdToken = Tcl_CreateCommand(interp, argv[1], TextWidgetCmd, htPtr, 
	TextDeleteCmdProc);
#ifdef ITCL_NAMESPACES
    Itk_SetWidgetCommand(htPtr->tkwin, htPtr->cmdToken);
#endif
    if ((Tk_ConfigureWidget(interp, htPtr->tkwin, configSpecs, argc - 2,
		argv + 2, (char *)htPtr, 0) != TCL_OK) ||
	(ConfigureText(interp, htPtr) != TCL_OK)) {
	Tk_DestroyWindow(htPtr->tkwin);
	return TCL_ERROR;
    }
    Tcl_SetResult(interp, Tk_PathName(htPtr->tkwin), TCL_VOLATILE);
    return TCL_OK;
}

int
Blt_HtextInit(interp)
    Tcl_Interp *interp;
{
    static Blt_CmdSpec cmdSpec =
    {"htext", TextCmd,};

    if (Blt_InitCmd(interp, "blt", &cmdSpec) == NULL) {
	return TCL_ERROR;
    }
    return TCL_OK;
}

#endif /* NO_HTEXT */