File: NSLayoutManager.m

package info (click to toggle)
gnustep-gui 0.7.6-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 16,464 kB
  • ctags: 7,163
  • sloc: objc: 84,669; ansic: 14,192; yacc: 290; makefile: 196; cpp: 87; sh: 21
file content (3099 lines) | stat: -rw-r--r-- 79,155 bytes parent folder | download
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
/** <title>NSLayoutManager</title>

   <abstract>The text layout manager class</abstract>

   Copyright (C) 1999 Free Software Foundation, Inc.

   Author: Jonathan Gapen <jagapen@smithlab.chem.wisc.edu>
   Date: July 1999
   Author:  Michael Hanni <mhanni@sprintmail.com>
   Date: August 1999
   Author: Richard Frith-Macdonald <rfm@gnu.org>
   Date: January 2001

   This file is part of the GNUstep GUI Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.
   If not, write to the Free Software Foundation,
   59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <AppKit/NSLayoutManager.h>
#include <AppKit/NSParagraphStyle.h>
#include "GSSimpleLayoutManager.h"

#include <AppKit/NSWindow.h>
#include <Foundation/NSException.h>

#define	USE_GLYPHS	0
#define	ALL_CHECKS	0

#define	BOTH	(NSTextStorageEditedCharacters | NSTextStorageEditedAttributes)

#if	ALL_CHECKS
static void missmatch(SEL s)
{
  NSLog(@"Missmatch in %@", NSStringFromSelector(s));
}
#endif

/*
 * Glyph attributes known to the layout manager.
 */
typedef enum {
  GSGlyphDrawsOutsideLineFragment,
  GSGlyphIsNotShown,
  GSGlyphGeneration,
  GSGlyphInscription,
} GSGlyphAttributes;

typedef	union {
  /*
   * A structure to hold information about a glyph in the glyph stream
   * NB. This structure should be no more than 64 bits, so it can fit
   * in as a GSIArray element of the same size as the NSRange structure
   * used to hold gap information.
   */
  struct {
    unsigned offset:24;			// characters in from start of chunk
    unsigned drawsOutsideLineFragment:1;	// glyph bigger than fragment?
    unsigned isNotShown:1;		// glyph invisible (space, tab etc)
    unsigned inscription:3;		// NSGlyphInscription info
    unsigned generation:3;		// Other attributes
    NSGlyph  glyph;			// The glyph itsself
  } g;
  NSRange	r;			// A range of invalidated glyphs (gap)
} GSGlyphAttrs;

#define	gRange(A)		((A).ext.r)
#define	gGlyph(A)		((A).ext.g.glyph)
#define	gOffset(A)		((A).ext.g.offset)
#define	gDrawsOutside(A)	((A).ext.g.drawsOutsideLineFragment)
#define	gIsNotShown(A)		((A).ext.g.isNotShown)
#define	gInscription(A)		((A).ext.g.inscription)
#define	gGeneration(A)		((A).ext.g.generation)



/*
 * We need a fast array that can store -
 * pointers, objects, glyphs (long) and attributes.
 */
#define GSI_ARRAY_TYPES		GSUNION_PTR|GSUNION_OBJ|GSUNION_INT|GSUNION_LONG
#define	GSI_ARRAY_TYPE		GSGlyphAttrs

/*
 * We handle retain/release explicitly, so we can use GSIArrays to hold
 * non-object values.
 */
#define GSI_ARRAY_NO_RELEASE	1
#define GSI_ARRAY_NO_RETAIN	1

#ifdef GSIArray
#undef GSIArray
#endif
#include <base/GSIArray.h>

/*
 * The glyph attributes within a chunk must be ordered by their offset fields,
 * so we can use a binary search to find the item for a particular offset.
 */
static NSComparisonResult
offsetSort(GSIArrayItem i0, GSIArrayItem i1)
{
  if (gOffset(i0) < gOffset(i1))
    return NSOrderedAscending;
  else if (gOffset(i0) > gOffset(i1))
    return NSOrderedDescending;
  else
    return NSOrderedSame;
}




/*
 * Glyph management implementation notes (January 2001)
 * Author - Richard Frith-Macdonald <rfm@gnu.org>
 *
 * An NSLayoutManager object maintains a 'glyph stream' which contains the
 * actual symbols to be displayed in text.  This glyph stream is conceptually
 * an array of glyphs and certain attributes.
 *
 * Each glyph has an associated index of the corresponding character in the
 * text storage object.  Since more than one character may map to a single
 * glyphs, the character index for a glyph is the index of the first
 * character corresponing to the glyph.  Since more than one glyph may map
 * on to the same character, adjacent glyphs in the glyph stream may have
 * the same character index.
 *
 * Other attributes of a glyph include flags to say whether the glyph is to
 * be drawn or not, and how it should be layed out with respect to the
 * preceeding glyph in the stream (allowing for overstrike etc).
 *
 * Since the state of the text storage object may change, glyphs may be
 * deleted from the stream from time to time, leaving a situation where
 * not all characters in the text storage have corresponding glyphs in
 * the glyph stream.  This state is called a 'gap'.  We maintain an array
 * of the locations of the gaps in the glyph stream.  When we attempt to
 * access a glyph, we must generate new glyphs from the text storage to
 * fill any gaps in the glyphs stream and insert them into the stream.
 *
 *
 * The glyph stream is actually implemented as an array of 'chunks' -
 * where a chunk contains an array of glyphs, and array of the glyph
 * attributes, and the glyph and character indices of the first glyph
 * in the chunk.  The remaining character/glyph indices are calculated
 * as offsets from the first glyph in the chunk.
 *
 * This implementation is used for speed of manipulation of very large
 * documents - modifications to a single chunk may have their effects
 * to some degree localised to that chunk.
 *
 * Invariants ...
 * 1. The glyph stream is a continuous array of glyphs ranging from 0 up.
 * 2. The character index of a glyph in the glyph stream is greater than
 *    or equal to that of the glyph that preceeds it.
 * 3. The gap array contains ranges of invalidated glyphs in numeric order
 *    and where no index exceeds the length of the glyph stream.
 * 4. The glyph stream consists of at least one chunk whose glyph index
 *    is zero.
 */


/*
 * Structure to handle the storage of the glyph stream.
 * This is done as an array of chunks.
 * Each chunk contains an array of glyphs and corresponding attributes.
 */
typedef struct {
  unsigned	charIndex;	// Index of character at start of chunk
  unsigned	glyphIndex;	// Index of glyph at start of chunk
  GSIArray_t	glyphs;		// Array of glyphs and their attributes.
} GSGlyphChunk;

/*
 * The glyph chunks must be ordered by their charIndex offset fields,
 * so we can use a binary search to find the item for a particular
 * character index.
 */
static NSComparisonResult
charIndexSort(GSIArrayItem i0, GSIArrayItem i1)
{
  if (((GSGlyphChunk*)(i0.ptr))->charIndex
    < (((GSGlyphChunk*)(i1.ptr))->charIndex))
    return NSOrderedAscending;
  else if (((GSGlyphChunk*)(i0.ptr))->charIndex
    > (((GSGlyphChunk*)(i1.ptr))->charIndex))
    return NSOrderedDescending;
  else
    return NSOrderedSame;
}

/*
 * The glyph chunks must be ordered by their glyphIndex offset fields,
 * so we can use a binary search to find the item for a particular
 * glyph index.
 */
static NSComparisonResult
glyphIndexSort(GSIArrayItem i0, GSIArrayItem i1)
{
  if (((GSGlyphChunk*)(i0.ptr))->glyphIndex
    < (((GSGlyphChunk*)(i1.ptr))->glyphIndex))
    return NSOrderedAscending;
  else if (((GSGlyphChunk*)(i0.ptr))->glyphIndex
    > (((GSGlyphChunk*)(i1.ptr))->glyphIndex))
    return NSOrderedDescending;
  else
    return NSOrderedSame;
}

/*
 * Glyph management functions.
 */
static GSGlyphChunk*
GSCreateGlyphChunk(unsigned glyphIndex, unsigned charIndex)
{
  GSGlyphChunk	*chunk;

  chunk = NSZoneMalloc(NSDefaultMallocZone(), sizeof(GSGlyphChunk));
  chunk->charIndex = charIndex;
  chunk->glyphIndex = glyphIndex;
  GSIArrayInitWithZoneAndCapacity(&chunk->glyphs, NSDefaultMallocZone(), 8);
  return chunk;
}

static void
GSDestroyGlyphChunk(GSGlyphChunk *chunk)
{
  GSIArrayClear(&chunk->glyphs);
  NSZoneFree(NSDefaultMallocZone(), chunk);
}

static unsigned
GSChunkForCharIndex(GSIArray chunks, unsigned charIndex)
{
  unsigned	pos;
  GSGlyphChunk	tmp;

  tmp.charIndex = charIndex;
  pos = GSIArrayInsertionPosition(chunks, (GSIArrayItem)(void*)&tmp,
    charIndexSort); 
  /*
   * pos is the index of the next chunk *after* the one we want,
   * unless we want something in the very first chunk.
   */
  if (pos > 0)
    {
      pos--;
    }
  return pos;
}

static unsigned
GSChunkForGlyphIndex(GSIArray chunks, unsigned glyphIndex)
{
  unsigned	pos;
  GSGlyphChunk	tmp;

  tmp.glyphIndex = glyphIndex;
  pos = GSIArrayInsertionPosition(chunks, (GSIArrayItem)(void*)&tmp,
    glyphIndexSort); 
  /*
   * pos is the index of the next chunk *after* the one we want,
   * unless we want something in the very first chunk.
   */
  NSCAssert(pos > 0, @"No glyph chunks present"); 
  if (pos > 0)
    {
      pos--;
    }
  return pos;
}



/*
 * Medium level functions for accessing and manipulating glyphs.
 */

typedef struct {
  @defs(NSLayoutManager)
} *lmDefs;

#define	glyphChunks	((GSIArray)_glyphData)

#define	_chunks		((GSIArray)(((lmDefs)lm)->_glyphData))
#define	_chunk		((GSGlyphChunk*)(((lmDefs)lm)->_currentGlyphs))
#define	_gindex		(((lmDefs)lm)->_glyphIndex)
#define	_cindex		(((lmDefs)lm)->_chunkIndex)
#define	_offset		(((lmDefs)lm)->_glyphOffset)
#define	_gaps		((GSIArray)(((lmDefs)lm)->_glyphGaps))


static BOOL		_Back(NSLayoutManager *lm);
static unsigned		_CharEnd(NSLayoutManager *lm);
static unsigned		_CharIndex(NSLayoutManager *lm);
static unsigned		_GlyphEnd(NSLayoutManager *lm);
static unsigned		_GlyphIndex(NSLayoutManager *lm);
static GSIArrayItem	*_Info(NSLayoutManager *lm);
static BOOL		_JumpToChar(NSLayoutManager *lm, unsigned charIndex);
static BOOL		_JumpToGlyph(NSLayoutManager *lm, unsigned glyphIndex);
static BOOL		_Step(NSLayoutManager *lm);


/*
 * Move 'current' glyph index back one place in glyph stream.
 * return NO on failure (start of stream).
 */
static inline BOOL
_Back(NSLayoutManager *lm)
{
  if (_offset > 0)
    {
      _offset--;
      _gindex--;
      return YES;
    }
  else if (_cindex > 0)
    {
      _cindex--;
      _chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, _cindex).ptr;
      _offset = GSIArrayCount(&_chunk->glyphs) - 1;
      _gindex--;
      return YES;
    }
  else
    {
      return NO;
    }
}

/*
 * Move 'current' glyph index forward one place in glyph stream.
 * return NO on failure (end of stream).
 */
static inline BOOL
_Step(NSLayoutManager *lm)
{
  if (_offset < GSIArrayCount(&_chunk->glyphs) - 1)
    {
      _offset++;
      _gindex++;
      return YES;
    }
  else
    {
      if (_cindex < GSIArrayCount(_chunks) - 1)
	{
	  _cindex++;
	  _chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, _cindex).ptr;
	  _offset = 0;
	  _gindex++;
	  return YES;
	}
      else
	{
	  return NO;
	}
    }
}

/*
 * Adjust the character indices for all the glyphs from the specified
 * location onwards. Leave the current glyphs set to the 'from' location.
 */
static void
_Adjust(NSLayoutManager *lm, unsigned from, int lengthChange)
{
  if (_JumpToGlyph(lm, from) == YES)
    {
      GSGlyphChunk	*chunk = _chunk;
      unsigned		index = _cindex;
      unsigned		offset = _offset;

      /*
       * Adjust character offsets for all glyphs in this chunk.
       */
      if (offset > 0)
	{
	  while (offset < GSIArrayCount(&chunk->glyphs))
	    {
	      gOffset(GSIArrayItems(&chunk->glyphs)[offset]) += lengthChange;
	      offset--;
	    }
	  index++;
	}
      
      /*
       * Now adjust character offsets for remaining chunks.
       */
      while (index < GSIArrayCount(_chunks))
	{
	  chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, index).ptr;
	  index++;
	  chunk->charIndex += lengthChange;
	}
    }
}

/*
 * Return the index of the character immediately beyond the last
 * generated glyph.
 */
static inline unsigned
_CharEnd(NSLayoutManager *lm)
{
  unsigned	i;

  i =  GSIArrayCount(_chunks);
  while (i-- > 0)
    {
      GSGlyphChunk	*c;
      unsigned		j;

      c = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, i).ptr;
      j = GSIArrayCount(&c->glyphs);
      if (j-- > 0)
	{
          return c->charIndex + gOffset(GSIArrayItemAtIndex(&c->glyphs, j)) + 1;
	}
    }
  return 0;
}

/*
 * Return the glyph index immediately beyond the last generated glyph.
 */
static inline unsigned
_GlyphEnd(NSLayoutManager *lm)
{
  unsigned	i;

  i =  GSIArrayCount(_chunks);
  while (i-- > 0)
    {
      GSGlyphChunk	*c;
      unsigned		j;

      c = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, i).ptr;
      j = GSIArrayCount(&c->glyphs);
      if (j > 0)
	{
          return c->glyphIndex + j;
	}
    }
  return 0;
}

/*
 * return the character index of the current glyph.
 */
static inline unsigned
_CharIndex(NSLayoutManager *lm)
{
  return _chunk->charIndex
    + gOffset(GSIArrayItemAtIndex(&_chunk->glyphs, _offset));
}

/*
 * return the index of the current glyph.
 */
static inline unsigned
_GlyphIndex(NSLayoutManager *lm)
{
  return _chunk->glyphIndex + _offset;
}

/*
 * Return the current glyph and attributes
 */
static GSIArrayItem *
_Info(NSLayoutManager *lm)
{
  return GSIArrayItems(&_chunk->glyphs) + _offset;
}

/*
 * Locate the first glyph corresponding to the specified character index
 * and make it the current glyph.
 */
static BOOL
_JumpToChar(NSLayoutManager *lm, unsigned charIndex)
{
  GSIArrayItem	tmp;
  GSGlyphChunk	*c;
  unsigned	i;
  unsigned	o;
  unsigned	co;

  i = GSChunkForCharIndex(_chunks, charIndex);
  c = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, i).ptr;
  gOffset(tmp) = charIndex - c->charIndex;
  o = GSIArrayInsertionPosition(&c->glyphs, tmp, offsetSort); 
  if (o == 0)
    {
      return NO;	// Insertion position not found.
    }
  o--;

  /*
   * Check the character index of this glyph to see if it matches the
   * character index we were asked for.  If it doesn't we have probably
   * failed to find a glyph matching the character.
   */
  co = gOffset(GSIArrayItemAtIndex(&c->glyphs, o));
  if (co + c->charIndex != charIndex)
    {
      if ([((lmDefs)lm)->_textStorage length] > charIndex)
	{
	  NSRange	r;

	  r = [[((lmDefs)lm)->_textStorage string]
	    rangeOfComposedCharacterSequenceAtIndex: charIndex];
	  if (r.length > 0 && r.location == co + c->charIndex)
	    {
	      /*
	       * The requested character is part of a composed character
	       * sequence whose first character maps on to the glyph we found.
	       */
	      _chunk = c;
	      _cindex = i;
	      _offset = o;
	      _gindex = c->glyphIndex + o;
	      return YES;
	    }
	}
      return NO;
    }

  /*
   * Locate the *first* glyph for this character index...
   */
  while (o > 0 && gOffset(GSIArrayItemAtIndex(&c->glyphs, o-1)) == co)
    {
      o--;
    }
  _chunk = c;
  _cindex = i;
  _offset = o;
  _gindex = c->glyphIndex + o;
  return YES;
}

/*
 * Make the specified glyph index the current glyph
 */
static BOOL
_JumpToGlyph(NSLayoutManager *lm, unsigned glyphIndex)
{
  GSGlyphChunk	*c;
  unsigned	i;
  unsigned	o;

  /*
   * Optimise for glyph index zero ... easy to find.
   */
  if (glyphIndex == 0)
    {
      c = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, 0).ptr;
      if (GSIArrayCount(&c->glyphs) > 0)
	{
	  _chunk = c;
	  _cindex = 0;
	  _offset = 0;
	  _gindex = 0;
	  return YES;
	}
      return NO;
    }

  i = GSChunkForGlyphIndex(_chunks, glyphIndex);
  c = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, i).ptr;
  o = glyphIndex - c->glyphIndex;
  if (o < GSIArrayCount(&c->glyphs))
    {
      _chunk = c;
      _cindex = i;
      _offset = o;
      _gindex = glyphIndex;
      return YES;
    }
  else
    {
      return NO;
    }
}

#if	USE_GLYPHS
static void
_Sane(NSLayoutManager *lm)
{
  unsigned	lastGlyph = 0;
  unsigned	lastChar = 0;
  unsigned	pos;

  /*
   * Check gaps.
   */
  for (pos = 0; pos < GSIArrayCount(_gaps); pos++)
    {
      unsigned val = GSIArrayItemAtIndex(_gaps, pos).ulng;

      NSCAssert(val > lastGlyph || (val == 0 && pos == 0),
	NSInternalInconsistencyException);
      lastGlyph = val;
    }
  
  NSCAssert(GSIArrayCount(_chunks) > 0, NSInternalInconsistencyException);
  lastGlyph = 0;
  for (pos = 0; pos < GSIArrayCount(_chunks); pos++)
    {
      GSGlyphChunk	*chunk;
      unsigned		count;

      chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, pos).ptr;
      NSCAssert(chunk->glyphIndex == (pos == 0 ? 0 : lastGlyph+1),
	NSInternalInconsistencyException);
      NSCAssert(chunk->charIndex >= lastChar, NSInternalInconsistencyException);
      count = GSIArrayCount(&chunk->glyphs);
      if (count > 0)
	{
	  GSIArrayItem	a;
	  unsigned	i;

	  for (i = 0; i < count; i++)
	    {
	      a = GSIArrayItemAtIndex(&chunk->glyphs, i);
	      NSCAssert(chunk->charIndex + gOffset(a) >= lastChar,
		NSInternalInconsistencyException);
	      lastChar = chunk->charIndex + gOffset(a);
	    }
	  lastGlyph = chunk->glyphIndex + count - 1;
	}
    }
}
static void
_GLog(NSLayoutManager *lm, SEL _cmd)
{
#if	ALL_CHECKS
  unsigned	pos;

  /*
   * Check gaps.
   */
  fprintf(stderr, "%s, %x\ngaps (%u) - ",
    _cmd ? sel_get_name(_cmd) : "", (unsigned)lm, GSIArrayCount(_gaps));
  for (pos = 0; pos < GSIArrayCount(_gaps); pos++)
    {
      unsigned val = GSIArrayItemAtIndex(_gaps, pos).ulng;

      fprintf(stderr, " %u", val);
    }
  fprintf(stderr, "\n");
  
  fprintf(stderr, "chunks (%u) -\n", GSIArrayCount(_chunks));
  for (pos = 0; pos < GSIArrayCount(_chunks); pos++)
    {
      GSGlyphChunk	*chunk;
      unsigned		count;

      chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(_chunks, pos).ptr;
      count = GSIArrayCount(&chunk->glyphs);
      fprintf(stderr, "  glyphs (%u) - gi %d, ci %d\n",
        count, chunk->glyphIndex, chunk->charIndex);
      if (count > 0)
	{
	  GSIArrayItem	a;
	  unsigned	i;

	  for (i = 0; i < count; i++)
	    {
	      a = GSIArrayItemAtIndex(&chunk->glyphs, i);
	      fprintf(stderr, "     %4d %4d %c",
		chunk->glyphIndex + i,
	     	chunk->charIndex + gOffset(a),
		(char)GSIArrayItemAtIndex(&chunk->glyphs, i).ulng);
	    }
	  fprintf(stderr, "\n");
	}
    }
#endif
}
#else
static inline void
_Sane(NSLayoutManager *lm)
{
}
static inline void
_GLog(NSLayoutManager *lm, SEL _cmd)
{
}
#endif



@interface NSLayoutManager (Private)

- (void) _doLayout;
- (int) _rebuildLayoutForTextContainer: (NSTextContainer*)aContainer
		  startingAtGlyphIndex: (int)glyphIndex;

@end


/**
 * <p>
 * A layout manager handles layout and glyph management for a text
 * storage.  A glyph is a symbol draewn to a display, and while
 * there is usually a one to one correspondence between glyphs
 * and characters in the text storage, that is no always the case.</p>
 * <p>
 * Sometimes a group of characters (a unicode composed character sequence)
 * can represent a single glyph, sometimes a single unicode character is
 * represented by multiple glyphs.</p>
 * <p>
 * eg. The text storage may contain the unichar o-umlaut and
 * the glyph stream could contain the two glyphs "o" and umlaut.
 * In this case, we would have two glyphs, with different glyph indexes,
 * both corresponding to a single character index.</p>
 */
@implementation NSLayoutManager

+ (id) allocWithZone: (NSZone*)z
{
  // Return a simple layout manager as this is the only working subclass
  if (self == [NSLayoutManager class])
    {
      return [GSSimpleLayoutManager allocWithZone: z];
    }
  else
    {
      return NSAllocateObject (self, 0, z);
    }
}

/** <init />
 * Sets up this instance. We should in future find a glyph generator and a
 * typesetter to use with glyphs management, but for now we just set up
 * the glyph storage.
 */
- (id) init
{
  self = [super init];

  if (self != nil)
    {
      GSIArray	a;

      _backgroundLayout = YES;
      _delegate = nil;
      _textContainers = [[NSMutableArray alloc] initWithCapacity: 2];

      /*
       * Initialise glyph storage and ivars to contain 'current' glyph
       * location information.
       */
      a = NSZoneMalloc(NSDefaultMallocZone(), sizeof(GSIArray_t));
      GSIArrayInitWithZoneAndCapacity(a, NSDefaultMallocZone(), 8);
      _glyphData = a;
      _currentGlyphs = GSCreateGlyphChunk(0, 0);
      GSIArrayInsertItem(glyphChunks, (GSIArrayItem)_currentGlyphs, 0);
      _chunkIndex = 0;
      _glyphOffset = 0;
      
      /*
       * Initialise storage of gaps in the glyph stream.
       * Initially there are no gaps in the stream.
       */
      a = NSZoneMalloc(NSDefaultMallocZone(), sizeof(GSIArray_t));
      GSIArrayInitWithZoneAndCapacity(a, NSDefaultMallocZone(), 8);
      _glyphGaps = a;
    }

  return self;
}

- (void) dealloc
{
  unsigned	i;

  /* We check that the _glyphData and _glyphGaps are not NULL so that
   * we can dealloc an object which has not been -init (some
   * regression tests need it).
   */

  /*
   * Release all glyph chunk information.
   */
  if (_glyphData != NULL)
    {
      i = GSIArrayCount(glyphChunks);
      while (i-- > 0)
	{
	  GSGlyphChunk	*chunk;
	  
	  chunk = (GSGlyphChunk*)(GSIArrayItemAtIndex(glyphChunks, i).ptr);
	  GSDestroyGlyphChunk(chunk);
	}
      GSIArrayEmpty(glyphChunks);
      NSZoneFree(NSDefaultMallocZone(), _glyphData);
    }

  if (_glyphGaps != NULL)
    {
      GSIArrayEmpty((GSIArray)_glyphGaps);
      NSZoneFree(NSDefaultMallocZone(), _glyphGaps);
    }
  
  RELEASE (_textContainers);

  [super dealloc];
}

/**
 * Sets the text storage for the layout manager.
 * Use -replaceTextStorage: instead as a rule. - this method is really
 * more for internal use by the text system.
 * Invalidates the entire layout (should it??)
 */
- (void) setTextStorage: (NSTextStorage*)aTextStorage
{
  unsigned int	length;
  NSRange	aRange;

  /*
   * Mark the entire existing text storage as invalid.
   */
  length = [_textStorage length];
  aRange = NSMakeRange(0, length);
  [self textStorage: _textStorage
	     edited: BOTH
	      range: aRange
     changeInLength: -length 
   invalidatedRange: aRange];

  /*
   * Make a note of the new text storage object, but don't retain it.
   * The text storage is owning us - it retains us.
   */
  _textStorage = aTextStorage;

  length = [aTextStorage length];
  aRange = NSMakeRange (0, length);
  // force complete re - layout
  [self textStorage: aTextStorage
	     edited: BOTH
	      range: aRange
     changeInLength: length 
   invalidatedRange: aRange];
}

/**
 * Returns the text storage for this layout manager.
 */
- (NSTextStorage*) textStorage
{
  return _textStorage;
}

/**
 * Replaces the test storage with a new one.<br />
 * Takes care (since layout managers are owned by text storages)
 * not to get self deallocated.
 */
- (void) replaceTextStorage: (NSTextStorage*)newTextStorage
{
  NSArray		*layoutManagers = [_textStorage layoutManagers];
  NSEnumerator		*enumerator = [layoutManagers objectEnumerator];
  NSLayoutManager	*object;

  /* Remove layout managers from old NSTextStorage object and add them to the
     new one.  NSTextStorage's addLayoutManager invokes NSLayoutManager's
     setTextStorage method automatically, and that includes self.  */

  while ((object = (NSLayoutManager*)[enumerator nextObject]) != nil)
    {
      RETAIN(object);
      [_textStorage removeLayoutManager: object];
      [newTextStorage addLayoutManager: object];
      RELEASE(object);
    }
}

/**
 * Return the text containers
 */
- (NSArray*) textContainers
{
  return _textContainers;
}

/**
 * Adds a container to the layout manager.
 */
- (void) addTextContainer: (NSTextContainer*)obj
{
  if ([_textContainers indexOfObjectIdenticalTo: obj] == NSNotFound)
    {
      int i;
      
      [_textContainers addObject: obj];
      [obj setLayoutManager: self];
      // FIXME: Invalidate layout beyond previous last container
      _textContainersCount++;
      /* NB: We do not retain this here !  It's already retained in the
	 array. */
      _firstTextView = [(NSTextContainer *)[_textContainers objectAtIndex: 0] 
					   textView];
      for (i = 0; i < _textContainersCount; i++)
	{
	  NSTextView *tv = [[_textContainers objectAtIndex: i] textView]; 
	  
	  [tv _updateMultipleTextViews];
	}
    }
}

/**
 * Inserts a new text container at index.
 */
- (void) insertTextContainer: (NSTextContainer*)aTextContainer
		     atIndex: (unsigned)index
{
  int i;

  [_textContainers insertObject: aTextContainer  atIndex: index];
  _textContainersCount++;
  _firstTextView = [(NSTextContainer *)[_textContainers objectAtIndex: 0] 
				       textView];
  for (i = 0; i < _textContainersCount; i++)
    {
      NSTextView *tv = [[_textContainers objectAtIndex: i] textView]; 
	
      [tv _updateMultipleTextViews];
    }
  // FIXME: Invalidate layout from thsi container onwards
}

/**
 * Removes the text container at index.
 */
- (void) removeTextContainerAtIndex: (unsigned)index
{
  int i;

  // FIXME  invalidate from thsi point onwards.
  [_textContainers removeObjectAtIndex: index];
  _textContainersCount--;
  if (_textContainersCount > 0)
    {
      _firstTextView = [(NSTextContainer *)[_textContainers objectAtIndex: 0] 
					   textView];  
    }
  else
    {
      _firstTextView = nil;
    }

  for (i = 0; i < _textContainersCount; i++)
    {
      NSTextView *tv = [[_textContainers objectAtIndex: i] textView]; 
      
      [tv _updateMultipleTextViews];
    }
}

/**
 * This determines the glyph range corresponding to aRange and
 * marks the glyphs as invalid.  It adjusts the character locations
 * of all glyphs beyond this by lengthChange.  It returns the
 * actual character range corresponding to the invalidated glyphs
 * if actualRange is non-nul.
 */
- (void) invalidateGlyphsForCharacterRange: (NSRange)aRange
			    changeInLength: (int)lengthChange
		      actualCharacterRange: (NSRange*)actualRange
{
  GSIArrayItem	item;
  NSRange	cRange;
  NSRange	gRange;
  unsigned	count;

_GLog(self,_cmd);
  if (actualRange != 0)
    {
      *actualRange = cRange;
    }
  if (aRange.length == 0)
    {
      return;	// Empty ... nothing to do.
    }
  if (aRange.location >= _CharEnd(self))
    {
      return;	// No glyphs generated for that character index.
    }

  gRange = [self glyphRangeForCharacterRange: aRange
			actualCharacterRange: &cRange];
  if (actualRange != 0)
    {
      *actualRange = cRange;
    }
  if (gRange.length == 0)
    {
      return;		// Nothing to do.
    }

  /*
   * Now adjust character locations for glyphs if necessary.
   */
  _Adjust(self, gRange.location, lengthChange);

  /*
   * Now adjust invalidated gaps in the glyph stream.
   */
  count = GSIArrayCount((GSIArray)_glyphGaps);
  if (count == 0)
    {
      gRange(item) = gRange;
      GSIArrayInsertItem((GSIArray)_glyphGaps, item, 0);
    }
  else
    {
      unsigned	pos;

      for (pos = 0; pos < count; pos++)
	{
	  NSRange	val;
	  NSRange	tmp;

	  val = gRange(GSIArrayItemAtIndex((GSIArray)_glyphGaps, pos));

	  /*
	   * If there is no overlap, we must either insert the new gap
	   * before the found one, or continue to look at the next gap.
	   */
	  tmp = NSIntersectionRange(gRange, val);
	  if (tmp.length == 0)
	    {
	      if (gRange.location < val.location)
		{
		  gRange(item) = gRange;
		  GSIArrayInsertItem((GSIArray)_glyphGaps, item, pos);
		  break;
		}
	      continue;
	    }

	  /*
	   * If the new gap is entirely within an existing one, we
	   * don't need to do anything.
	   */
	  if (val.location <= gRange.location
	    && NSMaxRange(val) >= NSMaxRange(gRange))
	    {
	      break;
	    }

	  /*
	   * Update the existing gap to be a union with our new gap.
	   */
	  gRange = NSUnionRange(gRange, val);
	  gRange(item) = gRange;
	  GSIArraySetItemAtIndex((GSIArray)_glyphGaps, item, pos);

	  while (pos + 1 < count)
	    {
	      val = gRange(GSIArrayItemAtIndex((GSIArray)_glyphGaps, pos + 1));

	      /*
	       * If there is no overlap with the next gap, we have
	       * nothing more to do.
	       */
	      tmp = NSIntersectionRange(gRange, val);
	      if (tmp.length == 0)
		{
		  break;
		}

	      /*
	       * If the next gap extends beyond our gap, we can remove
	       * the current one and replace the next one with a union.
	       */
	      if (val.location <= gRange.location
		&& NSMaxRange(val) >= NSMaxRange(gRange))
		{
		  GSIArrayRemoveItemsFromIndex((GSIArray)_glyphGaps, pos);
		  count--;
		  gRange(item) = NSUnionRange(gRange, val);
		  GSIArraySetItemAtIndex((GSIArray)_glyphGaps, item, pos);
		  break;
		}

	      /*
	       * The next gap is contained within our gap, so we can
	       * simply remove it. Then loop to examine the one beyond
	       */
	      GSIArrayRemoveItemsFromIndex((GSIArray)_glyphGaps, pos + 1);
	      count--;
	    }
	}
    }

// FIXME - should invalidate the character range ... but what does that mean?
_GLog(self,_cmd);
_Sane(self);
}

/**
 * This invalidates glyph positions for all glyphs corresponding
 * to the specified character range.<br />
 * If flag is YES then the layout information needs to be redone from
 * scratch, but if it's NO, the layout manager may try to optimise
 * layout from the old information.<br />
 * If actualRange is non-nul, returns the actual range invalidated.
 */
- (void) invalidateLayoutForCharacterRange: (NSRange)aRange
				    isSoft: (BOOL)flag
		      actualCharacterRange: (NSRange*)actualRange
{
  [self _doLayout];
}

/**
 * Causes redisplay of aRange, but does not lose the alyout information.
 */
- (void) invalidateDisplayForCharacterRange: (NSRange)aRange
{
/* FIXME */
}

/**
 * Causes redisplay of aRange, but does not lose the alyout information.
 */
- (void) invalidateDisplayForGlyphRange: (NSRange)aRange
{
/* FIXME */
}

/**
 * Invalidates the layout of all glyphs in aContainer and all containers
 * following it.
 */
- (void) textContainerChangedGeometry: (NSTextContainer*)aContainer
{
  // find the first character in that text container
  NSRange aRange = [self glyphRangeForTextContainer: aContainer];
  unsigned first = aRange.location;

  // invalidate the layout from here on
  [self invalidateLayoutForCharacterRange: 
	  NSMakeRange(first, [_textStorage length] - first)
	isSoft: NO
	actualCharacterRange: NULL];
}

/**
 * Notifies the layout manager that one of its text containers has
 * changed its view and an update of the display is needed.
 */
- (void) textContainerChangedTextView: (NSTextContainer*)aContainer
{
  unsigned index;
  
  index = [_textContainers indexOfObjectIdenticalTo: aContainer];
  
  if (index != NSNotFound)
    {
      if (index == 0)
	{
	  _firstTextView = [aContainer textView];
	  
	  /* It only makes sense to update the other text views if we
             have more than one text container */
	  if (_textContainersCount > 1)
	    {
	      /* It's the first text view.  Need to update everything. */
	      int i;

	      for (i = 0; i < _textContainersCount; i++)
		{
		  NSTextView *tv;
		  
		  tv = [[_textContainers objectAtIndex: i] textView]; 
		  [tv _updateMultipleTextViews];
		}
	    }
	}
    }
}

/**
 * This method is used to handle an editing change to aTextStorage.
 * The mask value indicates whether characters or attribuytes or both
 * have changed.<br />
 * If characters have not changed, the lengthChange argument is ignored.<br/>
 * The newCharRange is the effected range currently in the storage, while
 * invalidatedRange is the original range effected.
 */
- (void) textStorage: (NSTextStorage*)aTextStorage
	      edited: (unsigned)mask
	       range: (NSRange)newCharRange
      changeInLength: (int)lengthChange
    invalidatedRange: (NSRange)invalidatedRange
{
/*
  NSLog(@"NSLayoutManager was just notified that a change in the text
storage occured.");
  NSLog(@"range: (%d, %d) changeInLength: %d invalidatedRange (%d, %d)",
newCharRange.location, newCharRange.length, lengthChange, invalidatedRange.location,
invalidatedRange.length);
*/
  int		delta = 0;
  unsigned int	last;

_GLog(self,_cmd);
  if (mask & NSTextStorageEditedCharacters)
    {
      delta = lengthChange;
    }
  else if (mask == 0)
    {
      return;		// No changes to make.
    }
  last = NSMaxRange (invalidatedRange);

  // hard invalidation occures here.
  [self invalidateGlyphsForCharacterRange: newCharRange 
			   changeInLength: delta
		     actualCharacterRange: NULL];
  [self invalidateLayoutForCharacterRange: invalidatedRange 
				   isSoft: NO
		     actualCharacterRange: NULL];

  // the following range is soft invalidated
  newCharRange = NSMakeRange (last, [_textStorage length] - last);
  [self invalidateLayoutForCharacterRange: newCharRange
				   isSoft: YES
		     actualCharacterRange: NULL];
_GLog(self,_cmd);
}

/**
 * Sets flag to say if text should get laid out in
 * the background when the run lopp is idle.
 */
- (void) setBackgroundLayoutEnabled: (BOOL)flag
{
  _backgroundLayout = flag;
}

/**
 * Returns flag to say if text should get laid out in
 * the background when the run lopp is idle.
 */
- (BOOL) backgroundLayoutEnabled
{
  return _backgroundLayout;
}

/**
 * Used by the internal glyph generation system to insert aGlyph into
 * the glyph stream athe the specified glyphIndex and charIndex.<br />
 * Invariants ...<br />
 * a)  Glyph chunks are ordered sequentially from zero by character index.<br />
 * b)  Glyph chunks are ordered sequentially from zero by glyph index.<br />
 * c)  Adjacent glyphs may share a character index.<br />
 */
- (void) insertGlyph: (NSGlyph)aGlyph
	atGlyphIndex: (unsigned)glyphIndex
      characterIndex: (unsigned)charIndex
{
  unsigned		chunkCount = GSIArrayCount(glyphChunks);
  GSIArrayItem		info = { 0 };
  GSGlyphChunk		*chunk;
  unsigned		pos;

_GLog(self,_cmd);
  if (glyphIndex == 0 && chunkCount == 0)
    {
      /*
       * Special case - if there are no chunks, this is the
       * very first glyph and can simply be added to a new chunk.
       */
      chunk = GSCreateGlyphChunk(glyphIndex, charIndex);
      gGlyph(info) = aGlyph;
      GSIArrayAddItem(&chunk->glyphs, info);
      GSIArrayAddItem(glyphChunks, (GSIArrayItem)(void*)chunk);
    }
  else
    {
      unsigned		gCount;
      unsigned		gOffset;
      unsigned		chunkIndex;

      /*
       * Locate the chunk that we should insert into - the last one with
       * a glyphIndex less than or equal to the index we were given.
       */
      chunkIndex = GSChunkForGlyphIndex(glyphChunks, glyphIndex);
      chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks, chunkIndex).ptr;

      /*
       * Check for the case where we have been given an index that's
       * beyond the end of the last chunk.
       */
      gCount = GSIArrayCount(&chunk->glyphs);
      gOffset = glyphIndex - chunk->glyphIndex;
      if (gOffset > gCount)
	{
	  [NSException raise: NSRangeException
		      format: @"insertGlyph:glyphIndex:characterIndex: "
			@"glyph index out of range"];
	}
      
      if (gOffset == 0)			// Before first glyph in chunk
	{
	  if (chunk->charIndex < charIndex)
	    {
	      [NSException raise: NSRangeException
			  format: @"insertGlyph:glyphIndex:characterIndex: "
		@"character index greater than that of next glyph"];
	    }
	  if (chunkIndex > 0)
	    {
	      GSGlyphChunk	*previous;
	      unsigned		c;

	      previous = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks,
		chunkIndex-1).ptr;
	      c = GSIArrayCount(&previous->glyphs);
	      c = previous->charIndex
		+ gOffset(GSIArrayItemAtIndex(&previous->glyphs, c));
	      if (c > charIndex)
		{
		  [NSException raise: NSRangeException
			      format: @"insertGlyph:glyphIndex:characterIndex: "
		    @"character index less than that of previous glyph"];
		}
	      else if (c == charIndex)
		{
		  /*
		   * Inserting with the same character index as the last glyph
		   * in the previous chunk - so we should append to that chunk
		   * rather than prepending to this one.
		   */ 
		  chunkIndex--;
		  chunk = previous;
		  gCount = GSIArrayCount(&chunk->glyphs);
		  gOffset = glyphIndex - chunk->glyphIndex;
		}
	    }
	}
      else if (gOffset == gCount)	// After last glyph in chunk
	{
	  unsigned	c = chunk->charIndex;

	  if (gOffset > 0)
	    {
	      c += gOffset(GSIArrayItemAtIndex(&chunk->glyphs, gOffset-1));
	    }
	  if (charIndex < c)
	    {
	      [NSException raise: NSRangeException
			  format: @"insertGlyph:glyphIndex:characterIndex: "
		@"character index less than that of previous glyph"];
	    }
	  if (chunkIndex < chunkCount - 1)
	    {
	      GSGlyphChunk	*next;

	      next = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks,
		chunkIndex+1).ptr;
	      if (next->charIndex < charIndex)
		{
		  [NSException raise: NSRangeException
			      format: @"insertGlyph:glyphIndex:characterIndex: "
		    @"character index greater than that of next glyph"];
		}
	      else if (next->charIndex == charIndex)
		{
		  /*
		   * Inserting with the same character index as the first glyph
		   * in the next chunk - so we should insert in that chunk
		   * rather than appending to this one.
		   */ 
		  chunkIndex++;
		  chunk = next;
		  gCount = GSIArrayCount(&chunk->glyphs);
		  gOffset = glyphIndex - chunk->glyphIndex;
		}
	    }
	}
      else		// In middle of chunk somewhere.
	{
	  unsigned	n; 
	  unsigned	p; 

	  p = chunk->charIndex
	    + gOffset(GSIArrayItemAtIndex(&chunk->glyphs, gOffset-1));
	  if (p > charIndex)
	    {
	      [NSException raise: NSRangeException
			  format: @"insertGlyph:glyphIndex:characterIndex: "
		@"character index less than that of previous glyph"];
	    }
	  n = chunk->charIndex
	    + gOffset(GSIArrayItemAtIndex(&chunk->glyphs, gOffset));
	  if (n < charIndex)
	    {
	      [NSException raise: NSRangeException
			  format: @"insertGlyph:glyphIndex:characterIndex: "
		@"character index greater than that of next glyph"];
	    }
	}

      /*
       * Shall we add to the chunk or is it big enough already?
       */
      if (gCount > 4 && gCount == GSIArrayCapacity(&chunk->glyphs))
	{
	  GSGlyphChunk	*newChunk = 0;
	  unsigned	from;
	  unsigned	pos;
	  unsigned	splitAt = gCount/2;
	  unsigned	splitChar;

	  splitChar = gOffset(GSIArrayItemAtIndex(&chunk->glyphs, splitAt));
	  while (splitAt > 0 && splitChar
	    == gOffset(GSIArrayItemAtIndex(&chunk->glyphs, splitAt-1)))
	    {
	      splitAt--;
	    }
	  /*
	   * Arbitrary check that we could make a sane splitup of the
	   * chunk.  Conceivably we could have every glyph in the
	   * chunk set to the same character - which would force us to
	   * break our invariant that all glyphs for a particular
	   * character lie in the same chunk.
	   */
	  if (splitAt <= gCount/4)
	    {
	      [NSException raise: NSInternalInconsistencyException
			  format: @"unable to split glyph chunk"];
	    }
	  /*
	   * Ok - split the chunk into two (roughly) equal parts.
	   */
	  splitChar
	    = gOffset(GSIArrayItemAtIndex(&chunk->glyphs, splitAt));
	  newChunk = GSCreateGlyphChunk(chunk->glyphIndex + splitAt,
	    chunk->charIndex + splitChar);
	  GSIArrayInsertItem(glyphChunks, (GSIArrayItem)(void*)newChunk,
	    chunkIndex+1);
	  pos = 0;
	  from = splitAt;
	  while (from < GSIArrayCount(&chunk->glyphs))
	    {
	      GSIArrayItem	info;

	      /*
	       * Remove attributes from old chunk and add to new.
	       * Adjust offset for character index of new chunk.
	       */
	      info = GSIArrayItemAtIndex(&chunk->glyphs, from);
	      gOffset(info) -= splitChar;
	      GSIArrayInsertItem(&newChunk->glyphs, info, pos);

	      from++;
	      pos++;
	    }
	  GSIArrayRemoveItemsFromIndex(&chunk->glyphs, splitAt);
	  /*
	   * And set up so we point at the correct half of the split chunk.
	   */
	  if (glyphIndex >= newChunk->glyphIndex)
	    {
	      chunkIndex++;
	      chunk = newChunk;
	      gOffset = glyphIndex - chunk->glyphIndex;
	    }
	  gCount = GSIArrayCount(&chunk->glyphs);
	}

      /*
       * Special handling for insertion at the start of a chunk - we
       * need to update the index values for the chunk, and (possibly)
       * the character offsets of every glyph in the chunk.
       */
      if (gOffset == 0)
	{
	  chunk->glyphIndex = glyphIndex;
	  if (chunk->charIndex != charIndex)
	    {
	      int	diff = charIndex - chunk->charIndex;

	      /*
	       * Changing character index of entire chunk.
	       */
	      for (pos = 0; pos < gCount; pos++)
		{
		  gOffset(GSIArrayItems(&chunk->glyphs)[pos]) += diff;
		}
	      chunk->charIndex = charIndex;
	    }
	}

      /*
       * At last we insert the glyph and its attributes into the chunk.
       */
      gOffset(info) = charIndex - chunk->charIndex;
      gGlyph(info) = aGlyph;
      GSIArrayInsertItem(&chunk->glyphs, info, gOffset);

      /*
       * Now adjust the glyph index for all following chunks so we will
       * still know the index of the first glyph in each chunk.
       */
      for (pos = chunkIndex+1; pos < chunkCount; pos++)
	{
	  chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks, pos).ptr;
	  chunk->glyphIndex++;
	}
    }

  /*
   * Now adjust gaps to handle glyph insertion.
   */
  pos = 0;
  while (pos < GSIArrayCount((GSIArray)_glyphGaps))
    {
      unsigned long val;

      val = GSIArrayItemAtIndex((GSIArray)_glyphGaps, pos).ulng;
      if (val >= glyphIndex)
	{
	  GSIArraySetItemAtIndex((GSIArray)_glyphGaps, (GSIArrayItem)(val+1),
	    pos);
	}
      pos++;
    }
_GLog(self,_cmd);
_Sane(self);
}

/**
 * Returns the glyph at the specified index.<br />
 * Causes any gaps (areas where glyphs have been invalidated) before this
 * index to be re-filled.<br />
 * Raises an exception if the index is out of range.
 */
- (NSGlyph) glyphAtIndex: (unsigned)index
{
  BOOL		flag;
  NSGlyph	glyph;

  glyph = [self glyphAtIndex: index isValidIndex: &flag];
  if (flag == NO)
    {
      [NSException raise: NSRangeException
		  format: @"glyph index out of range"];
    }
  return glyph;
}

/**
 * Returns the glyph at the specified index.<br />
 * Causes any gaps (areas where glyphs have been invalidated) before this
 * index to be re-filled.<br />
 * Sets the flag to indicate whether the index was found ... if it wasn't
 * the returned glyph is meaningless.
 */
- (NSGlyph) glyphAtIndex: (unsigned)index
	    isValidIndex: (BOOL*)flag
{
#if USE_GLYPHS
  NSGlyph	glyph;
  NSString	*string = nil;
  unsigned	textLength = [_textStorage length];

_GLog(self,_cmd);
  if (GSIArrayCount((GSIArray)_glyphGaps) > 0
    && (GSIArrayItemAtIndex((GSIArray)_glyphGaps, 0).ulng) <= index)
    {
      unsigned long	gap;

      string = [_textStorage string];

      while (GSIArrayCount((GSIArray)_glyphGaps) > 0
	&& (gap = GSIArrayItemAtIndex((GSIArray)_glyphGaps, 0).ulng) <= index)
	{
	  unsigned	endChar;
	  unsigned	startChar;

	  if (gap == 0)
	    {
	      startChar = 0;
	    }
	  else
	    {
	      /*
	       * Locate the glyph that preceeds the gap, and start with the
	       * a character one beyond the one that generated that glyph.
	       * This guarantees that we won't try to re-generate the
	       * preceeding glyph.
	       * FIXME ... probably too simplistic an algorithm if we have
	       * decomposed unicode characters to deal with 0 we should
	       * probably skip forward to the next character sequence.
	       */
	      _JumpToGlyph(self, gap - 1);
	      startChar = _CharIndex(self) + 1;
	    }
	  if (gap == _GlyphEnd(self))
	    {
	      endChar = textLength;
	    }
	  else
	    {
	      _JumpToGlyph(self, gap);
	      endChar = _CharIndex(self);
	    }

	  /*
	   * FIXME
	   * Here we put some simple-minded code to generate glyphs from
	   * characters assuming that a glyph is the same as a character.
	   */
	  while (startChar < endChar)
	    {
	      unichar	c = [string characterAtIndex: startChar];

	      [self insertGlyph: (NSGlyph)c
		   atGlyphIndex: gap++
		 characterIndex: startChar++];
	    }
          /*
	   * We have generated glyphs upto or beyond the gap, so we
	   * can remove this gap and any others we have gone past.
	   */
	  while (GSIArrayCount((GSIArray)_glyphGaps) > 0
	    && GSIArrayItemAtIndex((GSIArray)_glyphGaps, 0).ulng < gap)
	    {
	      GSIArrayRemoveItemAtIndex((GSIArray)_glyphGaps, 0);
	    }
	}
    }

  if (index >= _GlyphEnd(self) && _CharEnd(self) < textLength)
    {
      unsigned	endChar = textLength;
      unsigned	startChar = _CharEnd(self);
      unsigned	glyphIndex = _GlyphEnd(self);

      if (string == nil)
	{
	  string = [_textStorage string];
	}
      /* FIXME ... should generate glyphs properly here */
      while (startChar < endChar && glyphIndex <= index)
	{
	  unichar	c = [string characterAtIndex: startChar];

	  [self insertGlyph: (NSGlyph)c
	       atGlyphIndex: glyphIndex++
	     characterIndex: startChar++];
	}
    }

_GLog(self,_cmd);
_Sane(self);
  if (_JumpToGlyph(self, index) == YES)
    {
      *flag = YES;
      glyph = gGlyph(*_Info(self));
    }
  else
    {
      *flag = NO;
      glyph = NSNullGlyph;
    }
#if	ALL_CHECKS
  if (index >= [_textStorage length])
    {
      if (glyph != NSNullGlyph)
	{
	  missmatch(_cmd);
	  *flag = NO;
	  glyph = NSNullGlyph;
	}
    }
  else if (glyph != (NSGlyph)[[_textStorage string] characterAtIndex: index])
    {
      missmatch(_cmd);
      *flag = YES;
      glyph = (NSGlyph)[[_textStorage string] characterAtIndex: index];
    }
#endif
  return glyph;
#else
  return (NSGlyph)[[_textStorage string] characterAtIndex: index];
#endif
}

/**
 * Replaces the glyph at index with newGlyph without changing
 * character index or other attributes.
 */
- (void) replaceGlyphAtIndex: (unsigned)index
		   withGlyph: (NSGlyph)newGlyph
{
_GLog(self,_cmd);
  if (_JumpToGlyph(self, index) == NO)
    {
      [NSException raise: NSRangeException
		  format: @"glyph index out of range"];
    }
  gGlyph(*_Info(self)) = newGlyph;
_GLog(self,_cmd);
}

/**
 * This returns a nul terminated array of glyphs ... so glyphArray
 * should contain space for glyphRange.length+1 glyphs.
 */
- (unsigned) getGlyphs: (NSGlyph*)glyphArray
		 range: (NSRange)glyphRange
{
  unsigned	packed = 0;
  unsigned	toFetch = glyphRange.length;

_GLog(self,_cmd);
  if (toFetch > 0)
    {
      /*
       * Force generation of glyphs to fill range.
       */
      [self glyphAtIndex: NSMaxRange(glyphRange)-1];

      _JumpToGlyph(self, glyphRange.location);

      /*
       * Now return glyphs, excluding those 'not shown'
       */
      while (toFetch-- > 0)
	{
	  GSIArrayItem	info = *_Info(self);

	  if (gIsNotShown(info) == 0)
	    {
	      glyphArray[packed++] = gGlyph(info);
	    }
	  _Step(self);	// Move to next glyph.
	}
    }
  glyphArray[packed] = 0;
_GLog(self,_cmd);
  return packed;
}

/**
 * Removes all the glyphs in aRange from the glyph stream, causing all
 * subsequent glyphs to have their index decreased by aRange.length
 */
- (void) deleteGlyphsInRange: (NSRange)aRange
{
  unsigned	chunkStart;
  unsigned	chunkEnd;
  unsigned	offset;
  unsigned	from;
  unsigned	pos;
  GSGlyphChunk	*chunk;

_GLog(self,_cmd);
  if (aRange.length == 0)
    {
      return;					// Nothing to delete.
    }
  pos = GSIArrayCount(glyphChunks) - 1;
  chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks, pos).ptr;
  pos = chunk->glyphIndex + GSIArrayCount(&chunk->glyphs);
  if (aRange.location >= pos)
    {
      return;					// Range is beyond glyphs.
    }
  if (NSMaxRange(aRange) > pos)
    {
      aRange.length = pos - aRange.location;	// Truncate range to glyphs.
    }

  chunkStart = GSChunkForGlyphIndex(glyphChunks, aRange.location);
  chunkEnd = GSChunkForGlyphIndex(glyphChunks, NSMaxRange(aRange)-1);

  /*
   * Remove all chunks wholy contained in the range.
   */
  while (chunkEnd - chunkStart > 1)
    {
      chunkEnd--;
      chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks, chunkEnd).ptr;
      GSIArrayRemoveItemAtIndex(glyphChunks, chunkEnd);
      GSDestroyGlyphChunk(chunk);
    }

  /*
   * Get start chunk and remove any glyphs in specified range.
   */
  chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks, chunkStart).ptr;
  if (chunkStart == chunkEnd)
    {
      pos = chunk->glyphIndex;
    }
  else
    {
      offset = aRange.location - chunk->glyphIndex;
      if (offset == 0)
	{
	  /*
	   * Start chunk is fully enclosed in range - remove it.
	   */
	  pos = chunk->glyphIndex;
	  GSIArrayRemoveItemAtIndex(glyphChunks, chunkStart);
	  GSDestroyGlyphChunk(chunk);
	  chunkEnd--;
	}
      else
	{
	  pos = chunk->glyphIndex + offset;
	  GSIArrayRemoveItemsFromIndex(&chunk->glyphs, offset);
	}
      chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks, chunkEnd).ptr;
    }

  offset = NSMaxRange(aRange) - chunk->glyphIndex;
  if (chunk->glyphIndex < aRange.location)
    {
      from = aRange.location - chunk->glyphIndex;
    }
  else
    {
      from = 0;
    }
  chunk->glyphIndex = pos;
  while (offset-- > from)
    {
      GSIArrayRemoveItemAtIndex(&chunk->glyphs, from);
    }
  while (++chunkEnd < GSIArrayCount(glyphChunks))
    {
      chunk = (GSGlyphChunk*)GSIArrayItemAtIndex(glyphChunks, chunkEnd).ptr;
      chunk->glyphIndex -= aRange.length;
    }

  /*
   * Remove any gaps that were in the deleted range and adjust the
   * indices of any remaining gaps to allow for the deletion.
   */
  pos = 0;
  while (pos < GSIArrayCount((GSIArray)_glyphGaps))
    {
      unsigned	val = GSIArrayItemAtIndex((GSIArray)_glyphGaps, pos).ulng;

      if (val < aRange.location)
	{
	  pos++;	// Not modified by deletion
	}
      else if (val <= NSMaxRange(aRange))
	{
	  /*
	   * Gap is within (or immediately after) the deleted area ...
	   * we set it to the end of the deleted area, or remove it if
	   * there is already a gap at that location.
	   */
	  if (pos > 0
	    && GSIArrayItemAtIndex((GSIArray)_glyphGaps, pos-1).ulng
	    == aRange.location)
	    {
	      GSIArrayRemoveItemAtIndex((GSIArray)_glyphGaps, pos);
	    }
	  else
	    {
	      GSIArraySetItemAtIndex((GSIArray)_glyphGaps,
		(GSIArrayItem)aRange.location, pos);
	      pos++;
	    }
	}
      else
	{
	  /*
	   * Gap is beyond deleted area ... simply adjust downwards.
	   */
	  val -= aRange.length;
	  GSIArraySetItemAtIndex((GSIArray)_glyphGaps,
	    (GSIArrayItem)val, pos);
	  pos++;
	}
    }

_GLog(self,_cmd);
_Sane(self);
}

/**
 * Returns the number of glyphs in the glyph stream ... causing generation
 * of new glyphs to fill gaps and to extend the stream until all characters
 * in the text storage have had glyphs generated.
 */
- (unsigned) numberOfGlyphs
{
  unsigned	result;
#if	USE_GLYPHS
  BOOL	valid;

  /*
   * Force generation of all glyphs.
   */
  [self glyphAtIndex: 0x7fffffff isValidIndex: &valid];
  result = _GlyphEnd(self);
#if	ALL_CHECKS
  if (result != [_textStorage length])
    {
      missmatch(_cmd);
      result = [_textStorage length];
    }
#endif
#else
  result = [_textStorage length];
#endif
  return result;
}

/**
 * Sets the glyph at glyphIndex to correspond to the character at charIndex.
 */
- (void) setCharacterIndex: (unsigned)charIndex
	   forGlyphAtIndex: (unsigned)glyphIndex
{
  int		diff;

_GLog(self,_cmd);
  if (_JumpToGlyph(self, glyphIndex) == NO)
    {
      [self glyphAtIndex: glyphIndex];
      _JumpToGlyph(self, glyphIndex);
    }
  diff = charIndex - _CharIndex(self);
  if (diff == 0)
    {
      return;		// Already set - nothing to do.
    }

  if (_Back(self) == NO)
    {
      if (charIndex != 0)
	{
	  [NSException raise: NSRangeException
		      format: @"set non-zero index for initial glyph"];
	}
      return;
    }
  if (_CharIndex(self) > charIndex)
    {
      [NSException raise: NSRangeException
		  format: @"set index lower than preceeding glyph"];
    }
  _Step(self);
  if (_Step(self) == YES && charIndex > _CharIndex(self))
    {
      [NSException raise: NSRangeException
		  format: @"set index higher than following glyph"];
    }
  
  _Back(self);
  /*
   * If this is the start of a chunk, we adjust the character position
   * for the chunk as a whole, then fix each glyph in turn.  Otherwise
   * we simply adjust the glyph concerned.
   */
  if (_glyphOffset == 0)
    {
      GSGlyphChunk	*chunk = (GSGlyphChunk*)_currentGlyphs;

      diff = charIndex - _CharIndex(self);
      chunk->charIndex += diff;
      while (_Step(self) == YES && (GSGlyphChunk*)_currentGlyphs == chunk)
	{
	  gOffset(*_Info(self)) += diff;
	}
    }
  else
    {
      gOffset(*_Info(self)) += diff;
    }
_GLog(self,_cmd);
_Sane(self);
}

/**
 * Returns the character index for the specified glyphIndex.<br />
 * If there are invalidated ranges (gaps) in the glyph stream before
 * glyphIndex, this will cause glyph generation to fill them.
 */
- (unsigned) characterIndexForGlyphAtIndex: (unsigned)glyphIndex
{
  unsigned	result;

#if	USE_GLYPHS
_GLog(self,_cmd);
  if (_JumpToGlyph(self, glyphIndex) == NO)
    {
      BOOL	exists;

      [self glyphAtIndex: glyphIndex isValidIndex: &exists];
      if (exists == YES)
	{
	  _JumpToGlyph(self, glyphIndex);
	  result = _CharIndex(self);  
	}
      else
	{
	  /*
	   * As a special case, the glyph index just beyond the end of
	   * the glyph stream is known to map to the character index just
	   * beyond the end of the text.
	   */
	  if (glyphIndex == _GlyphEnd(self))
	    {
	      result = [_textStorage length];
	    }
	  else
	    {
	      [NSException raise: NSRangeException
			  format: @"glyph index out of range"];
	    }
	}
    }
  else
    {
      result = _CharIndex(self);  
    }
#if	ALL_CHECKS
  if (result != glyphIndex)
    {
      missmatch(_cmd);
      result = glyphIndex;
    }
#endif
_GLog(self,_cmd);
#else
  result = glyphIndex;
#endif
  return result;
}

/**
 * Returns the range of characters that generated the glyphs in glyphRange.
 * Sets actualGlyphRange (if non-nul) to the range of glyphs generated by
 * those characters.
 */
- (NSRange) characterRangeForGlyphRange: (NSRange)glyphRange
		       actualGlyphRange: (NSRange*)actualGlyphRange
{
  NSRange	cRange;
  NSRange	gRange = glyphRange;
#if	USE_GLYPHS
  unsigned	cEnd;
  BOOL		exists;

_GLog(self,_cmd);
  /*
   * Force generation of glyphs to fill gaps.
   */
  [self glyphAtIndex: NSMaxRange(glyphRange)
	isValidIndex: &exists];

  /*
   * Locate character index of location immediately beyond last glyph in range.
   */
  if (exists == NO)
    {
      if (NSMaxRange(glyphRange) > _GlyphEnd(self))
	{
	  [NSException raise: NSRangeException
		      format: @"glyph range too large"];
	}
      cEnd = [_textStorage length];
    }
  else
    {
      _JumpToGlyph(self, NSMaxRange(glyphRange));
      cEnd = _CharIndex(self);
    }

  /*
   * Locate the first glyph and step backwards to the earliest glyph with
   * the same character index.
   */
  _JumpToGlyph(self, glyphRange.location);
  cRange.location = _CharIndex(self);
  cRange.length = cEnd - cRange.location;
  while (_Back(self) == YES && _CharIndex(self) == cRange.location)
    {
      gRange.location--;
      gRange.length++;
    }

#if	ALL_CHECKS
  if (NSEqualRanges(cRange, glyphRange) == NO)
    {
      missmatch(_cmd);
      cRange = glyphRange;
    }
  if (NSEqualRanges(gRange, glyphRange) == NO)
    {
      missmatch(_cmd);
      gRange = glyphRange;
    }
#endif
#else
  // Currently gyphIndex is the same as character index
  gRange = glyphRange;
  cRange = glyphRange;
#endif
  if (actualGlyphRange != 0)
    {
      *actualGlyphRange = gRange;
    }
  return cRange;
}

/**
 * Returns the range of glyphs that are generated from the characters in
 * charRange.
 * Sets actualCharRange (if non-nul) to the full range of characters which
 * generated those glyphs.
 */
- (NSRange) glyphRangeForCharacterRange: (NSRange)charRange
		   actualCharacterRange: (NSRange*)actualCharRange
{
  NSRange	gRange;
#if	USE_GLYPHS
  unsigned	pos;
  NSRange	cRange = charRange;
  unsigned	numGlyphs;
  BOOL		valid;

  /*
   * If the range we have been given begins or ends with a composed
   * character sequence, we must extend it to encompass the entire
   * sequence.  We store the actual range in cRange.
   */
  if (charRange.length > 0)
    {
      NSString	*s = [_textStorage string];
      NSRange	r;

      r = [s rangeOfComposedCharacterSequenceAtIndex: cRange.location];
      if (r.length > 0)
	{
	  cRange.length += (cRange.location - r.location);
	  cRange.location = r.location;
	}
      if (NSMaxRange(charRange) > NSMaxRange(r))
	{
	  pos = NSMaxRange(charRange) - 1;
	  r = [s rangeOfComposedCharacterSequenceAtIndex: pos];
	  if (r.length > 0)
	    {
	      cRange.length += r.length - 1;
	    }
	}
    }

_GLog(self,_cmd);
  // Force generation of glyphs.
  [self glyphAtIndex: NSMaxRange(cRange) - 1 isValidIndex: &valid];

  /*
   * Locate the first glyph corresponding to the start character.
   * If it doesn't exist, we either have a zero length range at the end.
   * or we must return a not found marker.
   */
  if (_JumpToChar(self, charRange.location) == NO)
    {
      if (charRange.location == _CharEnd(self))
	{
	  cRange = NSMakeRange(charRange.location, 0);
	  gRange = NSMakeRange(numGlyphs, 0);
	}
      else
	{
	  cRange = NSMakeRange(NSNotFound, 0);
	  gRange = NSMakeRange(NSNotFound, 0);
	}
    }
  else
    {
      gRange.location = _GlyphIndex(self);

      /*
       * Adjust start character if necessary.  The glyph may have a lower
       * index if the start char is part of a composed character sequence.
       */
      pos = _CharIndex(self);
      if (pos < cRange.location)
	{
	  cRange.length += (cRange.location - pos);
	  cRange.location = pos;
	}

      if (charRange.length == 0)
	{
	  /*
	   * For a zero length range, we don't need to locate an end character.
	   */
	  cRange.length = 0;	// May have been lengthened above.
	  gRange.length = 0;
	}
      else if (NSMaxRange(charRange) == [_textStorage length])
	{
	  /*
	   * Special case - range extends to end of text storage.
	   */
	  gRange.length = numGlyphs - gRange.location;
	}
      else
	{
	  /*
	   * Locate the glyph immediately beyond the range,
	   * and calculate the length of the range from that.
	   */
	  _JumpToChar(self, NSMaxRange(charRange));
	  pos = _GlyphIndex(self);
	  gRange.length = pos - gRange.location;
	  pos = _CharIndex(self);
	  cRange.length = pos - cRange.location;
	}
    }
#if	ALL_CHECKS
  if (NSEqualRanges(gRange, charRange) == NO)
    {
      missmatch(_cmd);
      gRange = charRange;
    }
  if (NSEqualRanges(cRange, charRange) == NO)
    {
      missmatch(_cmd);
      cRange = charRange;
    }
#endif
  if (actualCharRange != 0)
    {
      *actualCharRange = cRange;
    }
_GLog(self,_cmd);
#else
  // Currently gyphIndex is the same as character index
  if (actualCharRange != NULL)
    {
      *actualCharRange = charRange;
    }
  gRange = charRange;
#endif
  return gRange;
}

/**
 * This method modifies the attributes of an existing glyph at glyphIndex.
 * It only deals with the existing attribute types ... if you subclass and
 * add new attributed, you must replace this method with one which can
 * store your new attributes.
 */
- (void) setIntAttribute: (int)attribute
		   value: (int)anInt
	 forGlyphAtIndex: (unsigned)glyphIndex
{
  GSIArrayItem	info;

_GLog(self,_cmd);
  if (_JumpToGlyph(self, glyphIndex) == NO)
    {
      [NSException raise: NSRangeException
		  format: @"glyph index out of range"];
    }
  info = *_Info(self);
  if (attribute == GSGlyphDrawsOutsideLineFragment)
    {
      if (anInt == 0)
	{
	  gDrawsOutside(info) = 0;
	}
      else
	{
	  gDrawsOutside(info) = 1;
	}
    }
  else if (attribute == GSGlyphIsNotShown)
    {
      if (anInt == 0)
	{
	  gIsNotShown(info) = 0;
	}
      else
	{
	  gIsNotShown(info) = 1;
	}
    }
  else if (attribute == GSGlyphGeneration)
    {
      gGeneration(info) = anInt;
    }
  else if (attribute == GSGlyphInscription)
    {
      gInscription(info) = anInt;
    }
  *_Info(self) = info;
_GLog(self,_cmd);
}

/**
 * Returns the value for the attribute at the glyphIndex.
 */
- (int) intAttribute: (int)attribute
     forGlyphAtIndex: (unsigned)glyphIndex
{
  GSIArrayItem	info;

_GLog(self,_cmd);
  if (_JumpToGlyph(self, glyphIndex) == NO)
    {
      [NSException raise: NSRangeException
		  format: @"glyph index out of range"];
    }
  info = *_Info(self);

  if (attribute == GSGlyphDrawsOutsideLineFragment)
    {
      if (gDrawsOutside(info) == 0)
	{
	  return 0;
	}
      else
	{
	  return 1;
	}
    }
  else if (attribute == GSGlyphIsNotShown)
    {
      if (gIsNotShown(info) == 0)
	{
	  return 0;
	}
      else
	{
	  return 1;
	}
    }
  else if (attribute == GSGlyphGeneration)
    {
      return gGeneration(info);
    }
  else if (attribute == GSGlyphInscription)
    {
      return gInscription(info);
    }

  return 0;
}

- (void) setTextContainer: (NSTextContainer*)aTextContainer
	    forGlyphRange: (NSRange)glyphRange
{
  /* TODO */
}

- (NSRange) glyphRangeForTextContainer: (NSTextContainer*)aTextContainer
{
  /* TODO */
  return NSMakeRange(NSNotFound, 0);
}

/**
 * Returns the text container in which the glyph at glyphIndex is laid.
 * If effectiveRange is non-nul, returns the range of all glyphs in the
 * container.
 */
- (NSTextContainer*) textContainerForGlyphAtIndex: (unsigned)glyphIndex
                                   effectiveRange: (NSRange*)effectiveRange
{
/* FIXME ... needs to be properly implemented */
  if (effectiveRange != 0)
    {
      *effectiveRange = NSMakeRange(0, [self numberOfGlyphs]);
    }
  if ([_textContainers count] == 0)
    {
      return nil;
    }
  else
    {
      return  [_textContainers objectAtIndex: 0];
    }
}

- (void) setLineFragmentRect: (NSRect)fragmentRect
	       forGlyphRange: (NSRange)glyphRange
		    usedRect: (NSRect)usedRect
{
  /* TODO */
}

- (NSRect) lineFragmentRectForGlyphAtIndex: (unsigned)glyphIndex
			    effectiveRange: (NSRange*)lineFragmentRange
{
  /* TODO */
  return NSZeroRect;
}

- (NSRect) lineFragmentUsedRectForGlyphAtIndex: (unsigned)glyphIndex
				effectiveRange: (NSRange*)lineFragmentRange
{
  /* TODO */
  return NSZeroRect;
}

- (void) setExtraLineFragmentRect: (NSRect)aRect
			 usedRect: (NSRect)usedRect
		    textContainer: (NSTextContainer*)aTextContainer
{
  _extraLineFragmentRect = aRect;
  _extraLineFragmentUsedRect = usedRect;
  _extraLineFragmentContainer = aTextContainer;
}

- (NSRect) extraLineFragmentRect 
{
  return _extraLineFragmentRect;
}

- (NSRect) extraLineFragmentUsedRect 
{
  return _extraLineFragmentUsedRect;
}

- (NSTextContainer*) extraLineFragmentTextContainer 
{
  return _extraLineFragmentContainer;
}

- (NSRect)usedRectForTextContainer:(NSTextContainer *)container
{
  /* TODO */
  return NSZeroRect;
}

- (void)setAttachmentSize:(NSSize)attachmentSize 
	    forGlyphRange:(NSRange)glyphRange
{
  /* TODO */
}

- (void) setDrawsOutsideLineFragment: (BOOL)flag
		     forGlyphAtIndex: (unsigned)glyphIndex
{
  [self setIntAttribute: GSGlyphDrawsOutsideLineFragment
	value: 1
	forGlyphAtIndex: glyphIndex];
}

- (BOOL) drawsOutsideLineFragmentForGlyphAtIndex: (unsigned)glyphIndex
{
  if ([self intAttribute: GSGlyphDrawsOutsideLineFragment
	    forGlyphAtIndex: glyphIndex] == 1)
    {
      return YES;
    }
  return NO;
}

- (void) setLocation: (NSPoint)aPoint
forStartOfGlyphRange: (NSRange)glyphRange
{
  /* TODO */
}

- (NSPoint) locationForGlyphAtIndex: (unsigned)glyphIndex
{
  /* TODO */
  return NSZeroPoint;
}

- (NSRange) rangeOfNominallySpacedGlyphsContainingIndex: (unsigned)glyphIndex
{
  /* TODO */
  return NSMakeRange(NSNotFound, 0);
}

- (NSRect*) rectArrayForCharacterRange: (NSRange)charRange
          withinSelectedCharacterRange: (NSRange)selChareRange
                       inTextContainer: (NSTextContainer*)aTextContainer
                             rectCount: (unsigned*)rectCount
{
  /* TODO */
  return NULL;
}

- (NSRect*) rectArrayForGlyphRange: (NSRange)glyphRange
          withinSelectedGlyphRange: (NSRange)selectedGlyphRange
                   inTextContainer: (NSTextContainer*)aTextContainer
                         rectCount: (unsigned*)rectCount
{
  /* TODO */
  return _cachedRectArray;
}

- (NSRect) boundingRectForGlyphRange: (NSRange)glyphRange
		     inTextContainer: (NSTextContainer*)aTextContainer
{
  /* TODO */
  return NSZeroRect;
}

- (NSRange) glyphRangeForBoundingRect: (NSRect)aRect
		      inTextContainer: (NSTextContainer*)aTextContainer
{
  /* TODO */
  return NSMakeRange(0, 0);
}

- (NSRange) glyphRangeForBoundingRectWithoutAdditionalLayout: (NSRect)bounds
                           inTextContainer: (NSTextContainer*)aTextContainer
{
  /* TODO */
  return NSMakeRange(0, 0);
}

- (unsigned) glyphIndexForPoint: (NSPoint)aPoint
		inTextContainer: (NSTextContainer*)aTextContainer
 fractionOfDistanceThroughGlyph: (float*)partialFraction
{
  /* TODO */
  return 0;
}

- (unsigned) glyphIndexForPoint: (NSPoint)aPoint 
		inTextContainer: (NSTextContainer *)aTextContainer
{
  /* TODO */
  return [self glyphIndexForPoint: aPoint
	       inTextContainer: aTextContainer
	       fractionOfDistanceThroughGlyph: NULL];
}

- (void) setNotShownAttribute: (BOOL)flag
	      forGlyphAtIndex: (unsigned)glyphIndex
{
  [self setIntAttribute: GSGlyphIsNotShown
	          value: 1
	forGlyphAtIndex: glyphIndex];
}

- (BOOL) notShownAttributeForGlyphAtIndex: (unsigned)glyphIndex
{
  if ([self intAttribute: GSGlyphIsNotShown forGlyphAtIndex: glyphIndex] == 1)
    {
      return YES;
    }
  return NO;
}

- (void) setShowsInvisibleCharacters: (BOOL)flag
{
  _showsInvisibleChars = flag;
}

- (BOOL) showsInvisibleCharacters 
{
  return _showsInvisibleChars;
}

- (void) setShowsControlCharacters: (BOOL)flag
{
  _showsControlChars = flag;
}

- (BOOL) showsControlCharacters
{
  return _showsControlChars;
}

- (void) setHyphenationFactor: (float)factor
{
  _hyphenationFactor = factor;
}

- (float) hyphenationFactor
{
  return _hyphenationFactor;
}

- (void) getFirstUnlaidCharacterIndex: (unsigned*)charIndex
			   glyphIndex: (unsigned*)glyphIndex
{
  if (charIndex)
    {
      *charIndex = [self firstUnlaidCharacterIndex];
    }
  
  if (glyphIndex)
    {
      *glyphIndex = [self firstUnlaidGlyphIndex];
    }
}

- (unsigned int) firstUnlaidCharacterIndex
{
  return _firstUnlaidCharIndex;
}

- (unsigned int) firstUnlaidGlyphIndex
{
  return _firstUnlaidGlyphIndex;
}

- (void) setUsesScreenFonts: (BOOL)flag
{
  _usesScreenFonts = flag;
}

- (BOOL) usesScreenFonts 
{
  return _usesScreenFonts;
}

- (NSFont*) substituteFontForFont: (NSFont*)originalFont
{
  NSFont *replaceFont;

  if (! _usesScreenFonts)
    {
      return originalFont;
    }

  // FIXME: Should check if any NSTextView is scaled or rotated
  replaceFont = [originalFont screenFont];
  
  if (replaceFont != nil)
    {
      return replaceFont;
    }
  else
    {
      return originalFont;    
    }
}

- (NSView*) rulerAccessoryViewForTextView: (NSTextView*)aTextView
                           paragraphStyle: (NSParagraphStyle*)paragraphStyle
                                    ruler: (NSRulerView*)aRulerView
                                  enabled: (BOOL)flag
{
  /* TODO */
  return NULL;
}

- (NSArray*) rulerMarkersForTextView: (NSTextView*)aTextView
                      paragraphStyle: (NSParagraphStyle*)paragraphStyle
                               ruler: (NSRulerView*)aRulerView
{
  NSRulerMarker *marker;
  NSTextTab *tab;
  NSImage *image;
  NSArray *tabs = [paragraphStyle tabStops];
  NSEnumerator *enumerator = [tabs objectEnumerator];
  NSMutableArray *markers = [NSMutableArray arrayWithCapacity: [tabs count]];

  while ((tab = [enumerator nextObject]) != nil)
    {
      switch ([tab tabStopType])
        {
	  case NSLeftTabStopType:
	    image = [NSImage imageNamed: @"common_LeftTabStop"];
	    break;
	  case NSRightTabStopType:
	    image = [NSImage imageNamed: @"common_RightTabStop"];
	    break;
	  case NSCenterTabStopType:
	    image = [NSImage imageNamed: @"common_CenterTabStop"];
	    break;
	  case NSDecimalTabStopType:
	    image = [NSImage imageNamed: @"common_DecimalTabStop"];
	    break;
	  default:
	    image = nil;
	    break;
	}
      marker = [[NSRulerMarker alloc] 
		   initWithRulerView: aRulerView
		   markerLocation: [tab location]
		   image: image
		   imageOrigin: NSMakePoint(0, 0)];
      [marker setRepresentedObject: tab];
      [markers addObject: marker];
    }

  return markers;
}

/*
 * Managing the responder chain 
 */
- (BOOL) layoutManagerOwnsFirstResponderInWindow: (NSWindow*)aWindow
{
  id firstResponder = [aWindow firstResponder];

  if (_textContainersCount == 1)
    {
      if (_firstTextView == firstResponder)
	{
	  return YES;
	}
    }
  else
    {
      int i;

      for (i = 0; i < _textContainersCount; i++)
	{
	  id tv = [[_textContainers objectAtIndex: i] textView]; 
	  
	  if (tv == firstResponder)
	    {
	      return YES;
	    }
	}
    }

  return NO;
}

- (NSTextView*) firstTextView 
{
  return _firstTextView;
}

- (NSTextView*) textViewForBeginningOfSelection
{
  return nil;
}

- (void) drawBackgroundForGlyphRange: (NSRange)glyphRange
			     atPoint: (NSPoint)containerOrigin
{
  NSTextContainer *aTextContainer;
  
  aTextContainer = [self textContainerForGlyphAtIndex: glyphRange.location
			 effectiveRange: NULL];
  
  [[[aTextContainer textView] backgroundColor] set];
  
  NSRectFill ([self boundingRectForGlyphRange: glyphRange 
		    inTextContainer: aTextContainer]);
}

- (void) drawGlyphsForGlyphRange: (NSRange)glyphRange
			 atPoint: (NSPoint)containerOrigin
{
  /* TODO */
}

- (void) drawUnderlineForGlyphRange: (NSRange)glyphRange
		      underlineType: (int)underlineType
		     baselineOffset: (float)baselineOffset
		   lineFragmentRect: (NSRect)lineRect
	     lineFragmentGlyphRange: (NSRange)lineGlyphRange
		    containerOrigin: (NSPoint)containerOrigin
{
  /* TODO */
}

- (void) underlineGlyphRange: (NSRange)glyphRange
	       underlineType: (int)underlineType
	    lineFragmentRect: (NSRect)lineRect
      lineFragmentGlyphRange: (NSRange)lineGlyphRange
	     containerOrigin: (NSPoint)containerOrigin
{
  /* TODO */
}

- (void) setDelegate: (id)aDelegate
{
  _delegate = aDelegate;
}

- (id) delegate
{
  return _delegate;
}

- (unsigned) _charIndexForInsertionPointMovingFromY: (float)position
					      bestX: (float)wanted
						 up: (BOOL)upFlag
				      textContainer: (NSTextContainer *)tc
{
  [self subclassResponsibility: _cmd];
  return 0;
}


@end /* NSLayoutManager */

/* The methods laid out here are not correct, however the code they
contain for the most part is. Therefore, my country and a handsome
gift of Ghiradelli chocolate to he who puts all the pieces together :) */

/*
 * A little utility function to determine the range of characters in a
 * scanner that are present in a specified character set.  */
static inline NSRange
scanRange (NSScanner *scanner, NSCharacterSet* aSet)
{
  unsigned	start = [scanner scanLocation];
  unsigned	end = start;

  if ([scanner scanCharactersFromSet: aSet  intoString: 0] == YES)
    {
      end = [scanner scanLocation];
    }
  return NSMakeRange (start, end - start);
}

@implementation NSLayoutManager (Private)
- (int) _rebuildLayoutForTextContainer: (NSTextContainer*)aContainer
		  startingAtGlyphIndex: (int)glyphIndex
{
  NSSize cSize = [aContainer containerSize];
  float i = 0.0;
  NSMutableArray *lineStarts = [NSMutableArray new];
  NSMutableArray *lineEnds = [NSMutableArray new];
  int indexToAdd;
  NSScanner		*lineScanner;
  NSScanner		*paragraphScanner;
  BOOL lastLineForContainerReached = NO;
  int previousScanLocation;
  int previousParagraphLocation;
  int endScanLocation;
  int startIndex;
  NSRect firstProposedRect;
  NSRect secondProposedRect;
  NSCharacterSet *selectionParagraphGranularitySet = [NSCharacterSet characterSetWithCharactersInString: @"\n"];
  NSCharacterSet *selectionWordGranularitySet = [NSCharacterSet characterSetWithCharactersInString: @" "];
  NSCharacterSet *invSelectionWordGranularitySet = [selectionWordGranularitySet invertedSet];
  NSCharacterSet *invSelectionParagraphGranularitySet = [selectionParagraphGranularitySet invertedSet];
  NSRange paragraphRange;
  NSRange leadingSpacesRange;
  NSRange currentStringRange;
  NSRange trailingSpacesRange;
  NSRange leadingNlRange;
  NSRange trailingNlRange;
  NSSize lSize;
  float lineWidth = 0.0;
  float ourLines = 0.0;
  int beginLineIndex = 0;

  NSLog(@"rebuilding Layout at index: %d.\n", glyphIndex);

  // 1.) figure out how many glyphs we can fit in our container by
  // breaking up glyphs from the first unlaid out glyph and breaking it
  // into lines.
  //
  // 2.) 
  //     a.) set the range for the container
  //     b.) for each line in step 1 we need to set a lineFragmentRect and
  //         an origin point.


  // Here we go at part 1.

  startIndex = glyphIndex;

  paragraphScanner = [NSScanner scannerWithString: [_textStorage string]];
  [paragraphScanner setCharactersToBeSkipped: nil];

  [paragraphScanner setScanLocation: startIndex];

  NSLog(@"length of textStorage: %d", [[_textStorage string] length]);

//  NSLog(@"buffer: %@", [_textStorage string]);

  /*
   * This scanner eats one word at a time, we should have it imbeded in
   * another scanner that snacks on paragraphs (i.e. lines that end with
   * \n). Look in NSText.
   */
  while (![paragraphScanner isAtEnd])
    {
      previousParagraphLocation = [paragraphScanner scanLocation];
      beginLineIndex = previousParagraphLocation;
      lineWidth = 0.0;

      leadingNlRange
	= scanRange(paragraphScanner, selectionParagraphGranularitySet);
      paragraphRange
	= scanRange(paragraphScanner, invSelectionParagraphGranularitySet);
      trailingNlRange
	= scanRange(paragraphScanner, selectionParagraphGranularitySet);

//      NSLog(@"leadingNlRange: (%d, %d)", leadingNlRange.location, leadingNlRange.length);

//      if (leadingNlRange.length)
//	paragraphRange = NSUnionRange (leadingNlRange,paragraphRange);
//      if (trailingNlRange.length)
//	paragraphRange = NSUnionRange (trailingNlRange,paragraphRange);

      NSLog(@"paragraphRange: (%d, %d)", paragraphRange.location, paragraphRange.length);

      lineScanner = [NSScanner scannerWithString:
	[[_textStorage string] substringWithRange: paragraphRange]];
      [lineScanner setCharactersToBeSkipped: nil];

      while (![lineScanner isAtEnd])
        {
          previousScanLocation = [lineScanner scanLocation];

           // snack next word
          leadingSpacesRange
	    = scanRange(lineScanner, selectionWordGranularitySet);
          currentStringRange
	    = scanRange(lineScanner, invSelectionWordGranularitySet);
          trailingSpacesRange
	    = scanRange(lineScanner, selectionWordGranularitySet);

          if (leadingSpacesRange.length)
	    currentStringRange = NSUnionRange(leadingSpacesRange,currentStringRange);
          if (trailingSpacesRange.length)
	    currentStringRange = NSUnionRange(trailingSpacesRange,currentStringRange);

	  lSize = [_textStorage sizeRange: currentStringRange];

//	  lSize = [_textStorage sizeRange: 
//NSMakeRange(currentStringRange.location+paragraphRange.location+startIndex,
//currentStringRange.length)];

	  if ((lineWidth + lSize.width) < cSize.width)
	    {
	      if ([lineScanner isAtEnd])
                {
		  NSLog(@"we are at end before finishing a line: %d.\n",  [lineScanner scanLocation]);
		NSLog(@"scanLocation = %d, previousParagraphLocation = %d, beginLineIndex = %d",
		      [lineScanner scanLocation],
		      previousParagraphLocation,
		      beginLineIndex);
		[lineStarts addObject: [NSNumber
					 numberWithInt: beginLineIndex]];
		[lineEnds addObject: [NSNumber
				       numberWithInt: (int)[lineScanner scanLocation] + previousParagraphLocation - (beginLineIndex)]];
		lineWidth = 0.0;
                }
	      
	      lineWidth += lSize.width;
	      //NSLog(@"lineWidth: %f", lineWidth);
	    }
	  else
	    {
	      if (ourLines > cSize.height)
                {
                   lastLineForContainerReached = YES;
                   break;
                 }
	      
	      [lineScanner setScanLocation: previousScanLocation];
	      indexToAdd = previousScanLocation + previousParagraphLocation 
		- (beginLineIndex);
	      
	      NSLog(@"previousScanLocation = %d, previousParagraphLocation = %d, beginLineIndex = %d indexToAdd = %d",
		    previousScanLocation,
		    previousParagraphLocation,
		    beginLineIndex,
		    indexToAdd);
	      
	      ourLines += 20.0;  // 14
	      lineWidth = 0.0;
	      
	      [lineStarts addObject: [NSNumber
				       numberWithInt: beginLineIndex]];
	      [lineEnds addObject: [NSNumber numberWithInt: indexToAdd]];
	      beginLineIndex = previousScanLocation + previousParagraphLocation;
	    }
	}

      if (lastLineForContainerReached)
        break;
    }

  endScanLocation = [paragraphScanner scanLocation];

  NSLog(@"endScanLocation: %d", endScanLocation);

  // set this container for that glyphrange

  [self setTextContainer: aContainer
    forGlyphRange: NSMakeRange(startIndex, endScanLocation - startIndex)];

  NSLog(@"ok, move on to step 2.");

  // step 2. break the lines up and assign rects to them.

  for (i = 0; i < [lineStarts count]; i++)
    {
      NSRect aRect, bRect;
      float padding = [aContainer lineFragmentPadding];
      NSRange ourRange;

//      NSLog(@"\t\t===> %d", [[lines objectAtIndex: i] intValue]);

      ourRange = NSMakeRange ([[lineStarts objectAtIndex: i] intValue],
			      [[lineEnds objectAtIndex: i] intValue]);

/*
      if (i == 0)
        {
          ourRange = NSMakeRange (startIndex, 
			[[lines objectAtIndex: i] intValue] - startIndex);
        }
      else
        {
          ourRange = NSMakeRange ([[lines objectAtIndex: i-1] intValue],
[[lines objectAtIndex: i] intValue] - [[lines objectAtIndex: i-1]
intValue]);
        }
*/
      NSLog(@"line: %@|", [[_textStorage string]
substringWithRange: ourRange]);

      firstProposedRect = NSMakeRect (0, i * 14, cSize.width, 14);

      // ask our textContainer to fix our lineFragment.

      secondProposedRect = [aContainer
	lineFragmentRectForProposedRect: firstProposedRect
                            sweepDirection: NSLineSweepLeft
                         movementDirection: NSLineMoveLeft
			     remainingRect: &bRect];

      // set the line fragmentRect for this range.

      [self setLineFragmentRect: secondProposedRect
		  forGlyphRange: ourRange
		       usedRect: aRect];

      // set the location for this string to be 'show'ed.

      [self setLocation: NSMakePoint(secondProposedRect.origin.x + padding,
				    secondProposedRect.origin.y + padding) 
	    forStartOfGlyphRange: ourRange];
    }

// bloody hack.
//      if (moreText)
//      	[delegate layoutManager: self
//	  didCompleteLayoutForTextContainer: [textContainers objectAtIndex: i]
//          atEnd: NO];
//      else
//      	[delegate layoutManager: self
//	  didCompleteLayoutForTextContainer: [textContainers objectAtIndex: i]
//          atEnd: YES];

  [lineStarts release];
  [lineEnds release];

  return endScanLocation;
}

- (void) _doLayout
{
  NSEnumerator		*enumerator;
  NSTextContainer	*container;
  int			gIndex = 0;

  NSLog(@"doLayout called.\n");

  enumerator = [_textContainers objectEnumerator];
  while ((container = [enumerator nextObject]) != nil)
    {
      gIndex = [self _rebuildLayoutForTextContainer: container
			       startingAtGlyphIndex: gIndex];
    }
}

@end