API Overview API Index Package Overview Direct link to this page
JDK 1.6
  javax.swing.text. AbstractDocument View Javadoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111

/*
 * @(#)AbstractDocument.java	1.157 06/04/07
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package javax.swing.text;

import java.util.*;
import java.io.*;
import java.awt.font.TextAttribute;
import java.text.Bidi;

import javax.swing.UIManager;
import javax.swing.undo.*;
import javax.swing.event.ChangeListener;
import javax.swing.event.*;
import javax.swing.tree.TreeNode;

import sun.font.BidiUtils;
import sun.swing.SwingUtilities2;

/**
 * An implementation of the document interface to serve as a 
 * basis for implementing various kinds of documents.  At this
 * level there is very little policy, so there is a corresponding
 * increase in difficulty of use.
 * <p>
 * This class implements a locking mechanism for the document.  It
 * allows multiple readers or one writer, and writers must wait until 
 * all observers of the document have been notified of a previous 
 * change before beginning another mutation to the document.  The
 * read lock is acquired and released using the <code>render</code>
 * method.  A write lock is aquired by the methods that mutate the
 * document, and are held for the duration of the method call.
 * Notification is done on the thread that produced the mutation, 
 * and the thread has full read access to the document for the
 * duration of the notification, but other readers are kept out
 * until the notification has finished.  The notification is a
 * beans event notification which does not allow any further 
 * mutations until all listeners have been notified.
 * <p>
 * Any models subclassed from this class and used in conjunction
 * with a text component that has a look and feel implementation
 * that is derived from BasicTextUI may be safely updated
 * asynchronously, because all access to the View hierarchy
 * is serialized by BasicTextUI if the document is of type
 * <code>AbstractDocument</code>.  The locking assumes that an
 * independent thread will access the View hierarchy only from
 * the DocumentListener methods, and that there will be only
 * one event thread active at a time.
 * <p>
 * If concurrency support is desired, there are the following 
 * additional implications.  The code path for any DocumentListener 
 * implementation and any UndoListener implementation must be threadsafe, 
 * and not access the component lock if trying to be safe from deadlocks.  
 * The <code>repaint</code> and <code>revalidate</code> methods 
 * on JComponent are safe.
 * <p>
 * AbstractDocument models an implied break at the end of the document.
 * Among other things this allows you to position the caret after the last
 * character. As a result of this, <code>getLength</code> returns one less
 * than the length of the Content. If you create your own Content, be
 * sure and initialize it to have an additional character. Refer to
 * StringContent and GapContent for examples of this. Another implication
 * of this is that Elements that model the implied end character will have
 * an endOffset == (getLength() + 1). For example, in DefaultStyledDocument
 * <code>getParagraphElement(getLength()).getEndOffset() == getLength() + 1
 * </code>.
 * <p>
 * <strong>Warning:</strong>
 * Serialized objects of this class will not be compatible with
 * future Swing releases. The current serialization support is
 * appropriate for short term storage or RMI between applications running
 * the same version of Swing.  As of 1.4, support for long term storage
 * of all JavaBeans<sup><font size="-2">TM</font></sup>
 * has been added to the <code>java.beans</code> package.
 * Please see {@link java.beans.XMLEncoder}.
 *
 * @author  Timothy Prinzing
 * @version 1.157 04/07/06
 */
public abstract class AbstractDocument implements Document, Serializable {

    /**
     * Constructs a new <code>AbstractDocument</code>, wrapped around some
     * specified content storage mechanism.
     *
     * @param data the content
     */
    protected AbstractDocument(Content data) {
	this(data, StyleContext.getDefaultStyleContext());
    }

    /**
     * Constructs a new <code>AbstractDocument</code>, wrapped around some
     * specified content storage mechanism.
     *
     * @param data the content
     * @param context the attribute context
     */
    protected AbstractDocument(Content data, AttributeContext context) {
	this.data = data;
	this.context = context;
        bidiRoot = new BidiRootElement();

	if (defaultI18NProperty == null) {
	    // determine default setting for i18n support
	    Object o = java.security.AccessController.doPrivileged(
		new java.security.PrivilegedAction() {
                    public Object run() {
			return System.getProperty(I18NProperty);
		    }
                }
	    );
	    if (o != null) {
		defaultI18NProperty = Boolean.valueOf((String)o);
	    } else {
		defaultI18NProperty = Boolean.FALSE;
	    }
	}
	putProperty( I18NProperty, defaultI18NProperty);

        //REMIND(bcb) This creates an initial bidi element to account for
        //the \n that exists by default in the content.  Doing it this way
        //seems to expose a little too much knowledge of the content given
        //to us by the sub-class.  Consider having the sub-class' constructor
        //make an initial call to insertUpdate.
	writeLock();
        try {
            Element[] p = new Element[1];
            p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
            bidiRoot.replace(0,0,p);
        } finally {
            writeUnlock();
        }
    }

    /**
     * Supports managing a set of properties. Callers
     * can use the <code>documentProperties</code> dictionary
     * to annotate the document with document-wide properties.
     * 
     * @return a non-<code>null</code> <code>Dictionary</code>
     * @see #setDocumentProperties
     */
    public Dictionary<Object,Object> getDocumentProperties() {
	if (documentProperties == null) {
	    documentProperties = new Hashtable(2);
	}
	return documentProperties;
    }

    /**
     * Replaces the document properties dictionary for this document.
     * 
     * @param x the new dictionary
     * @see #getDocumentProperties
     */
    public void setDocumentProperties(Dictionary<Object,Object> x) {
	documentProperties = x;
    }

    /**
     * Notifies all listeners that have registered interest for
     * notification on this event type.  The event instance 
     * is lazily created using the parameters passed into 
     * the fire method.
     *
     * @param e the event
     * @see EventListenerList
     */
    protected void fireInsertUpdate(DocumentEvent e) {
        notifyingListeners = true;
        try {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length-2; i>=0; i-=2) {
                if (listeners[i]==DocumentListener.class) {
                    // Lazily create the event:
                    // if (e == null)
                    // e = new ListSelectionEvent(this, firstIndex, lastIndex);
                    ((DocumentListener)listeners[i+1]).insertUpdate(e);
                }
            }
        } finally {
            notifyingListeners = false;
        }
    }

    /**
     * Notifies all listeners that have registered interest for
     * notification on this event type.  The event instance 
     * is lazily created using the parameters passed into 
     * the fire method.
     *
     * @param e the event
     * @see EventListenerList
     */
    protected void fireChangedUpdate(DocumentEvent e) {
        notifyingListeners = true;
        try {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length-2; i>=0; i-=2) {
                if (listeners[i]==DocumentListener.class) {
                    // Lazily create the event:
                    // if (e == null)
                    // e = new ListSelectionEvent(this, firstIndex, lastIndex);
                    ((DocumentListener)listeners[i+1]).changedUpdate(e);
                }	       
            }
        } finally {
            notifyingListeners = false;
        }
    }

    /**
     * Notifies all listeners that have registered interest for
     * notification on this event type.  The event instance 
     * is lazily created using the parameters passed into 
     * the fire method.
     *
     * @param e the event
     * @see EventListenerList
     */
    protected void fireRemoveUpdate(DocumentEvent e) {
        notifyingListeners = true;
        try {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length-2; i>=0; i-=2) {
                if (listeners[i]==DocumentListener.class) {
                    // Lazily create the event:
                    // if (e == null)
                    // e = new ListSelectionEvent(this, firstIndex, lastIndex);
                    ((DocumentListener)listeners[i+1]).removeUpdate(e);
                }	       
            }
        } finally {
            notifyingListeners = false;
        }
    }

    /**
     * Notifies all listeners that have registered interest for
     * notification on this event type.  The event instance 
     * is lazily created using the parameters passed into 
     * the fire method.
     *
     * @param e the event
     * @see EventListenerList
     */
    protected void fireUndoableEditUpdate(UndoableEditEvent e) {
	// Guaranteed to return a non-null array
	Object[] listeners = listenerList.getListenerList();
	// Process the listeners last to first, notifying
	// those that are interested in this event
	for (int i = listeners.length-2; i>=0; i-=2) {
	    if (listeners[i]==UndoableEditListener.class) {
		// Lazily create the event:
		// if (e == null)
		// e = new ListSelectionEvent(this, firstIndex, lastIndex);
		((UndoableEditListener)listeners[i+1]).undoableEditHappened(e);
	    }	       
	}
    }

    /**
     * Returns an array of all the objects currently registered
     * as <code><em>Foo</em>Listener</code>s
     * upon this document.
     * <code><em>Foo</em>Listener</code>s are registered using the
     * <code>add<em>Foo</em>Listener</code> method.
     *
     * <p>
     * You can specify the <code>listenerType</code> argument
     * with a class literal, such as
     * <code><em>Foo</em>Listener.class</code>.
     * For example, you can query a
     * document <code>d</code>
     * for its document listeners with the following code:
     *
     * <pre>DocumentListener[] mls = (DocumentListener[])(d.getListeners(DocumentListener.class));</pre>
     *
     * If no such listeners exist, this method returns an empty array.
     *
     * @param listenerType the type of listeners requested; this parameter
     *          should specify an interface that descends from
     *          <code>java.util.EventListener</code>
     * @return an array of all objects registered as
     *          <code><em>Foo</em>Listener</code>s on this component,
     *          or an empty array if no such
     *          listeners have been added
     * @exception ClassCastException if <code>listenerType</code>
     *          doesn't specify a class or interface that implements
     *          <code>java.util.EventListener</code>
     *
     * @see #getDocumentListeners
     * @see #getUndoableEditListeners
     *
     * @since 1.3
     */
    public <T extends EventListener> T[] getListeners(Class<T> listenerType) { 
	return listenerList.getListeners(listenerType); 
    }

    /**
     * Gets the asynchronous loading priority.  If less than zero,
     * the document should not be loaded asynchronously.
     *
     * @return the asynchronous loading priority, or <code>-1</code>
     *   if the document should not be loaded asynchronously
     */
    public int getAsynchronousLoadPriority() {
	Integer loadPriority = (Integer) 
	    getProperty(AbstractDocument.AsyncLoadPriority);
	if (loadPriority != null) {
	    return loadPriority.intValue();
	}
	return -1;
    }

    /**
     * Sets the asynchronous loading priority. 
     * @param p the new asynchronous loading priority; a value
     *   less than zero indicates that the document should not be
     *   loaded asynchronously
     */
    public void setAsynchronousLoadPriority(int p) {
	Integer loadPriority = (p >= 0) ? new Integer(p) : null;
	putProperty(AbstractDocument.AsyncLoadPriority, loadPriority);
    }

    /**
     * Sets the <code>DocumentFilter</code>. The <code>DocumentFilter</code>
     * is passed <code>insert</code> and <code>remove</code> to conditionally
     * allow inserting/deleting of the text.  A <code>null</code> value
     * indicates that no filtering will occur.
     *
     * @param filter the <code>DocumentFilter</code> used to constrain text
     * @see #getDocumentFilter
     * @since 1.4
     */
    public void setDocumentFilter(DocumentFilter filter) {
        documentFilter = filter;
    }

    /**
     * Returns the <code>DocumentFilter</code> that is responsible for
     * filtering of insertion/removal. A <code>null</code> return value 
     * implies no filtering is to occur.
     *
     * @since 1.4
     * @see #setDocumentFilter
     * @return the DocumentFilter
     */
    public DocumentFilter getDocumentFilter() {
        return documentFilter;
    }

    // --- Document methods -----------------------------------------

    /**
     * This allows the model to be safely rendered in the presence
     * of currency, if the model supports being updated asynchronously.
     * The given runnable will be executed in a way that allows it
     * to safely read the model with no changes while the runnable
     * is being executed.  The runnable itself may <em>not</em>
     * make any mutations. 
     * <p>
     * This is implemented to aquire a read lock for the duration
     * of the runnables execution.  There may be multiple runnables
     * executing at the same time, and all writers will be blocked
     * while there are active rendering runnables.  If the runnable
     * throws an exception, its lock will be safely released.
     * There is no protection against a runnable that never exits,
     * which will effectively leave the document locked for it's
     * lifetime.
     * <p>
     * If the given runnable attempts to make any mutations in
     * this implementation, a deadlock will occur.  There is
     * no tracking of individual rendering threads to enable
     * detecting this situation, but a subclass could incur
     * the overhead of tracking them and throwing an error.
     * <p>
     * This method is thread safe, although most Swing methods
     * are not. Please see 
     * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
     * to Use Threads</A> for more information.
     *
     * @param r the renderer to execute
     */
    public void render(Runnable r) {
	readLock();
	try {
	    r.run();
	} finally {
	    readUnlock();
	}
    }

    /**
     * Returns the length of the data.  This is the number of
     * characters of content that represents the users data.
     *
     * @return the length >= 0
     * @see Document#getLength
     */
    public int getLength() {
	return data.length() - 1;
    }

    /**
     * Adds a document listener for notification of any changes.
     *
     * @param listener the <code>DocumentListener</code> to add
     * @see Document#addDocumentListener
     */
    public void addDocumentListener(DocumentListener listener) {
	listenerList.add(DocumentListener.class, listener);
    }

    /**
     * Removes a document listener.
     *
     * @param listener the <code>DocumentListener</code> to remove
     * @see Document#removeDocumentListener
     */
    public void removeDocumentListener(DocumentListener listener) {
	listenerList.remove(DocumentListener.class, listener);
    }

    /**
     * Returns an array of all the document listeners
     * registered on this document.
     *
     * @return all of this document's <code>DocumentListener</code>s 
     *         or an empty array if no document listeners are
     *         currently registered
     *
     * @see #addDocumentListener
     * @see #removeDocumentListener
     * @since 1.4
     */
    public DocumentListener[] getDocumentListeners() {
        return (DocumentListener[])listenerList.getListeners(
                DocumentListener.class);
    }

    /**
     * Adds an undo listener for notification of any changes.
     * Undo/Redo operations performed on the <code>UndoableEdit</code>
     * will cause the appropriate DocumentEvent to be fired to keep
     * the view(s) in sync with the model.
     *
     * @param listener the <code>UndoableEditListener</code> to add
     * @see Document#addUndoableEditListener
     */
    public void addUndoableEditListener(UndoableEditListener listener) {
	listenerList.add(UndoableEditListener.class, listener);
    }

    /**
     * Removes an undo listener.
     *
     * @param listener the <code>UndoableEditListener</code> to remove
     * @see Document#removeDocumentListener
     */
    public void removeUndoableEditListener(UndoableEditListener listener) {
	listenerList.remove(UndoableEditListener.class, listener);
    }

    /**
     * Returns an array of all the undoable edit listeners
     * registered on this document.
     *
     * @return all of this document's <code>UndoableEditListener</code>s 
     *         or an empty array if no undoable edit listeners are
     *         currently registered
     *
     * @see #addUndoableEditListener
     * @see #removeUndoableEditListener
     *
     * @since 1.4
     */
    public UndoableEditListener[] getUndoableEditListeners() {
        return (UndoableEditListener[])listenerList.getListeners(
                UndoableEditListener.class);
    }

    /**
     * A convenience method for looking up a property value. It is
     * equivalent to:
     * <pre>
     * getDocumentProperties().get(key);
     * </pre>
     * 
     * @param key the non-<code>null</code> property key
     * @return the value of this property or <code>null</code>
     * @see #getDocumentProperties
     */
    public final Object getProperty(Object key) {
        return getDocumentProperties().get(key);
    }


    /**
     * A convenience method for storing up a property value.  It is
     * equivalent to:
     * <pre>
     * getDocumentProperties().put(key, value);
     * </pre>
     * If <code>value</code> is <code>null</code> this method will
     * remove the property.
     * 
     * @param key the non-<code>null</code> key
     * @param value the property value
     * @see #getDocumentProperties
     */
    public final void putProperty(Object key, Object value) {
	if (value != null) {
	    getDocumentProperties().put(key, value);
	} else {
            getDocumentProperties().remove(key);
        }
        if( key == TextAttribute.RUN_DIRECTION 
            && Boolean.TRUE.equals(getProperty(I18NProperty)) )
        {
            //REMIND - this needs to flip on the i18n property if run dir
            //is rtl and the i18n property is not already on.
            writeLock();
            try {
                DefaultDocumentEvent e 
                    = new DefaultDocumentEvent(0, getLength(),
                                               DocumentEvent.EventType.INSERT);
                updateBidi( e );
            } finally {
                writeUnlock();
            }
        }
    }

    /**
     * Removes some content from the document.
     * Removing content causes a write lock to be held while the
     * actual changes are taking place.  Observers are notified
     * of the change on the thread that called this method.
     * <p>
     * This method is thread safe, although most Swing methods
     * are not. Please see 
     * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
     * to Use Threads</A> for more information.
     * 
     * @param offs the starting offset >= 0
     * @param len the number of characters to remove >= 0
     * @exception BadLocationException  the given remove position is not a valid 
     *   position within the document
     * @see Document#remove
     */
    public void remove(int offs, int len) throws BadLocationException {
        DocumentFilter filter = getDocumentFilter();

        writeLock();
        try {
            if (filter != null) {
                filter.remove(getFilterBypass(), offs, len);
            }
            else {
                handleRemove(offs, len);
            }
        } finally {
            writeUnlock();
        }
    }

    /**
     * Performs the actual work of the remove. It is assumed the caller
     * will have obtained a <code>writeLock</code> before invoking this.
     */
    void handleRemove(int offs, int len) throws BadLocationException {
	if (len > 0) {
            if (offs < 0 || (offs + len) > getLength()) {
                throw new BadLocationException("Invalid remove",
                                               getLength() + 1); 
            }
            DefaultDocumentEvent chng = 
		    new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE);

            boolean isComposedTextElement = false;
            // Check whether the position of interest is the composed text
            isComposedTextElement = Utilities.isComposedTextElement(this, offs);
		
            removeUpdate(chng);
            UndoableEdit u = data.remove(offs, len);
            if (u != null) {
                chng.addEdit(u);
            }
            postRemoveUpdate(chng);
            // Mark the edit as done.
            chng.end();
            fireRemoveUpdate(chng);
            // only fire undo if Content implementation supports it
            // undo for the composed text is not supported for now
            if ((u != null) && !isComposedTextElement) {
                fireUndoableEditUpdate(new UndoableEditEvent(this, chng));
            }
	}
    }
    
    /**
     * Deletes the region of text from <code>offset</code> to
     * <code>offset + length</code>, and replaces it with <code>text</code>.
     * It is up to the implementation as to how this is implemented, some
     * implementations may treat this as two distinct operations: a remove
     * followed by an insert, others may treat the replace as one atomic  
     * operation.
     * 
     * @param offset index of child element
     * @param length length of text to delete, may be 0 indicating don't
     *               delete anything
     * @param text text to insert, <code>null</code> indicates no text to insert
     * @param attrs AttributeSet indicating attributes of inserted text,
     *              <code>null</code>
     *              is legal, and typically treated as an empty attributeset,
     *              but exact interpretation is left to the subclass
     * @exception BadLocationException the given position is not a valid 
     *            position within the document
     * @since 1.4
     */
    public void replace(int offset, int length, String text,
                        AttributeSet attrs) throws BadLocationException {
        if (length == 0 && (text == null || text.length() == 0)) {
            return;
        }
        DocumentFilter filter = getDocumentFilter();

	writeLock();
	try {
            if (filter != null) {
                filter.replace(getFilterBypass(), offset, length, text,
                               attrs);
            }
            else {
                if (length > 0) {
                    remove(offset, length);
                }
                if (text != null && text.length() > 0) {
                    insertString(offset, text, attrs);
                }
            }
        } finally {
            writeUnlock();
        }
    }

    /**
     * Inserts some content into the document.
     * Inserting content causes a write lock to be held while the
     * actual changes are taking place, followed by notification
     * to the observers on the thread that grabbed the write lock.
     * <p>
     * This method is thread safe, although most Swing methods
     * are not. Please see 
     * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
     * to Use Threads</A> for more information.
     *
     * @param offs the starting offset >= 0
     * @param str the string to insert; does nothing with null/empty strings
     * @param a the attributes for the inserted content
     * @exception BadLocationException  the given insert position is not a valid 
     *   position within the document
     * @see Document#insertString
     */
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if ((str == null) || (str.length() == 0)) {
	    return;
	}
        DocumentFilter filter = getDocumentFilter();

	writeLock();
	try {
            if (filter != null) {
                filter.insertString(getFilterBypass(), offs, str, a);
            }
            else {
                handleInsertString(offs, str, a);
            }
        } finally {
            writeUnlock();
        }
    }

    /**
     * Performs the actual work of inserting the text; it is assumed the
     * caller has obtained a write lock before invoking this.
     */
    void handleInsertString(int offs, String str, AttributeSet a)
                         throws BadLocationException {
        if ((str == null) || (str.length() == 0)) {
	    return;
	}
        UndoableEdit u = data.insertString(offs, str);
        DefaultDocumentEvent e = 
            new DefaultDocumentEvent(offs, str.length(), DocumentEvent.EventType.INSERT);
        if (u != null) {
            e.addEdit(u);
        }
	    
        // see if complex glyph layout support is needed
        if( getProperty(I18NProperty).equals( Boolean.FALSE ) ) {
            // if a default direction of right-to-left has been specified,
            // we want complex layout even if the text is all left to right.
            Object d = getProperty(TextAttribute.RUN_DIRECTION);
            if ((d != null) && (d.equals(TextAttribute.RUN_DIRECTION_RTL))) {
                putProperty( I18NProperty, Boolean.TRUE);
            } else {
		char[] chars = str.toCharArray();
		if (SwingUtilities2.isComplexLayout(chars, 0, chars.length)) {
		    putProperty( I18NProperty, Boolean.TRUE);
                }
            }
        }

        insertUpdate(e, a);
        // Mark the edit as done.
        e.end();
        fireInsertUpdate(e);
        // only fire undo if Content implementation supports it
        // undo for the composed text is not supported for now
        if (u != null && 
            (a == null || !a.isDefined(StyleConstants.ComposedTextAttribute))) {
            fireUndoableEditUpdate(new UndoableEditEvent(this, e));
        }
    }

    /**
     * Gets a sequence of text from the document.  
     *
     * @param offset the starting offset >= 0
     * @param length the number of characters to retrieve >= 0
     * @return the text
     * @exception BadLocationException  the range given includes a position 
     *   that is not a valid position within the document
     * @see Document#getText
     */
    public String getText(int offset, int length) throws BadLocationException {
	if (length < 0) {
	    throw new BadLocationException("Length must be positive", length);
	}
	String str = data.getString(offset, length);
	return str;
    }

    /**
     * Fetches the text contained within the given portion 
     * of the document.
     * <p>
     * If the partialReturn property on the txt parameter is false, the
     * data returned in the Segment will be the entire length requested and
     * may or may not be a copy depending upon how the data was stored.
     * If the partialReturn property is true, only the amount of text that
     * can be returned without creating a copy is returned.  Using partial
     * returns will give better performance for situations where large 
     * parts of the document are being scanned.  The following is an example
     * of using the partial return to access the entire document:
     * <p>
     * <pre>
     * &nbsp; int nleft = doc.getDocumentLength();
     * &nbsp; Segment text = new Segment();
     * &nbsp; int offs = 0;
     * &nbsp; text.setPartialReturn(true);   
     * &nbsp; while (nleft > 0) {
     * &nbsp;     doc.getText(offs, nleft, text);
     * &nbsp;     // do something with text
     * &nbsp;     nleft -= text.count;
     * &nbsp;     offs += text.count;
     * &nbsp; }
     * </pre>
     *
     * @param offset the starting offset >= 0
     * @param length the number of characters to retrieve >= 0
     * @param txt the Segment object to retrieve the text into
     * @exception BadLocationException  the range given includes a position 
     *   that is not a valid position within the document
     */
    public void getText(int offset, int length, Segment txt) throws BadLocationException {
	if (length < 0) {
	    throw new BadLocationException("Length must be positive", length);
	}
	data.getChars(offset, length, txt);
    }

    /**
     * Returns a position that will track change as the document
     * is altered.
     * <p>
     * This method is thread safe, although most Swing methods
     * are not. Please see 
     * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
     * to Use Threads</A> for more information.
     *
     * @param offs the position in the model >= 0
     * @return the position
     * @exception BadLocationException  if the given position does not
     *   represent a valid location in the associated document
     * @see Document#createPosition
     */
    public synchronized Position createPosition(int offs) throws BadLocationException {
	return data.createPosition(offs);
    }

    /**
     * Returns a position that represents the start of the document.  The 
     * position returned can be counted on to track change and stay 
     * located at the beginning of the document.
     *
     * @return the position
     */
    public final Position getStartPosition() {
	Position p;
	try {
	    p = createPosition(0);
	} catch (BadLocationException bl) {
	    p = null;
	}
	return p;
    }
    
    /**
     * Returns a position that represents the end of the document.  The
     * position returned can be counted on to track change and stay 
     * located at the end of the document.
     *
     * @return the position
     */
    public final Position getEndPosition() {
	Position p;
	try {
	    p = createPosition(data.length());
	} catch (BadLocationException bl) {
	    p = null;
	}
	return p;
    }

    /**
     * Gets all root elements defined.  Typically, there
     * will only be one so the default implementation
     * is to return the default root element.
     *
     * @return the root element
     */
    public Element[] getRootElements() {
	Element[] elems = new Element[2];
	elems[0] = getDefaultRootElement();
        elems[1] = getBidiRootElement();
	return elems;
    }

    /**
     * Returns the root element that views should be based upon
     * unless some other mechanism for assigning views to element
     * structures is provided.
     *
     * @return the root element
     * @see Document#getDefaultRootElement
     */
    public abstract Element getDefaultRootElement();

    // ---- local methods -----------------------------------------

    /**
     * Returns the <code>FilterBypass</code>. This will create one if one
     * does not yet exist.
     */
    private DocumentFilter.FilterBypass getFilterBypass() {
        if (filterBypass == null) {
            filterBypass = new DefaultFilterBypass();
        }
        return filterBypass;
    }

    /**
     * Returns the root element of the bidirectional structure for this
     * document.  Its children represent character runs with a given
     * Unicode bidi level.
     */
    public Element getBidiRootElement() {
        return bidiRoot;
    }

    /**
     * Returns true if the text in the range <code>p0</code> to
     * <code>p1</code> is left to right.
     */
    boolean isLeftToRight(int p0, int p1) {
        if(!getProperty(I18NProperty).equals(Boolean.TRUE)) {
	    return true;
	}
	Element bidiRoot = getBidiRootElement();
	int index = bidiRoot.getElementIndex(p0);
	Element bidiElem = bidiRoot.getElement(index);
	if(bidiElem.getEndOffset() >= p1) {
	    AttributeSet bidiAttrs = bidiElem.getAttributes();
	    return ((StyleConstants.getBidiLevel(bidiAttrs) % 2) == 0);
	}
	return true;
    }

    /**
     * Get the paragraph element containing the given position.  Sub-classes
     * must define for themselves what exactly constitutes a paragraph.  They
     * should keep in mind however that a paragraph should at least be the
     * unit of text over which to run the Unicode bidirectional algorithm.
     *
     * @param pos the starting offset >= 0
     * @return the element */
    public abstract Element getParagraphElement(int pos);


    /**
     * Fetches the context for managing attributes.  This
     * method effectively establishes the strategy used 
     * for compressing AttributeSet information.
     *
     * @return the context
     */
    protected final AttributeContext getAttributeContext() {
	return context;
    }

    /**
     * Updates document structure as a result of text insertion.  This
     * will happen within a write lock.  If a subclass of
     * this class reimplements this method, it should delegate to the
     * superclass as well.
     *
     * @param chng a description of the change
     * @param attr the attributes for the change
     */
    protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) {
        if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
            updateBidi( chng );

        // Check if a multi byte is encountered in the inserted text.
        if (chng.type == DocumentEvent.EventType.INSERT &&
                        chng.getLength() > 0 &&
                        !Boolean.TRUE.equals(getProperty(MultiByteProperty))) {
            Segment segment = SegmentCache.getSharedSegment();
            try {
                getText(chng.getOffset(), chng.getLength(), segment);
                segment.first();
                do {
                    if ((int)segment.current() > 255) {
                        putProperty(MultiByteProperty, Boolean.TRUE);
                        break;
                    }
                } while (segment.next() != Segment.DONE);
            } catch (BadLocationException ble) {
                // Should never happen
            }
            SegmentCache.releaseSharedSegment(segment);
        }
    }

    /**
     * Updates any document structure as a result of text removal.  This
     * method is called before the text is actually removed from the Content.
     * This will happen within a write lock. If a subclass
     * of this class reimplements this method, it should delegate to the
     * superclass as well.
     *
     * @param chng a description of the change
     */
    protected void removeUpdate(DefaultDocumentEvent chng) {
    }

    /**
     * Updates any document structure as a result of text removal.  This
     * method is called after the text has been removed from the Content.
     * This will happen within a write lock. If a subclass
     * of this class reimplements this method, it should delegate to the
     * superclass as well.
     *
     * @param chng a description of the change
     */
    protected void postRemoveUpdate(DefaultDocumentEvent chng) {
        if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
            updateBidi( chng );
    }

    
    /**
     * Update the bidi element structure as a result of the given change
     * to the document.  The given change will be updated to reflect the
     * changes made to the bidi structure.
     *
     * This method assumes that every offset in the model is contained in
     * exactly one paragraph.  This method also assumes that it is called
     * after the change is made to the default element structure.
     */
    void updateBidi( DefaultDocumentEvent chng ) {

        // Calculate the range of paragraphs affected by the change.
        int firstPStart;
        int lastPEnd;
        if( chng.type == DocumentEvent.EventType.INSERT 
            || chng.type == DocumentEvent.EventType.CHANGE )
        {
            int chngStart = chng.getOffset();
            int chngEnd =  chngStart + chng.getLength();
            firstPStart = getParagraphElement(chngStart).getStartOffset();
            lastPEnd = getParagraphElement(chngEnd).getEndOffset();
        } else if( chng.type == DocumentEvent.EventType.REMOVE ) {
            Element paragraph = getParagraphElement( chng.getOffset() );
            firstPStart = paragraph.getStartOffset();
            lastPEnd = paragraph.getEndOffset();
        } else {
            throw new Error("Internal error: unknown event type.");
        }
        //System.out.println("updateBidi: firstPStart = " + firstPStart + " lastPEnd = " + lastPEnd );

        
        // Calculate the bidi levels for the affected range of paragraphs.  The
        // levels array will contain a bidi level for each character in the
        // affected text.
        byte levels[] = calculateBidiLevels( firstPStart, lastPEnd );

        
        Vector newElements = new Vector();
        
        // Calculate the first span of characters in the affected range with
        // the same bidi level.  If this level is the same as the level of the
        // previous bidi element (the existing bidi element containing
        // firstPStart-1), then merge in the previous element.  If not, but
        // the previous element overlaps the affected range, truncate the
        // previous element at firstPStart.
        int firstSpanStart = firstPStart;
        int removeFromIndex = 0;
        if( firstSpanStart > 0 ) {
            int prevElemIndex = bidiRoot.getElementIndex(firstPStart-1);
            removeFromIndex = prevElemIndex;
            Element prevElem = bidiRoot.getElement(prevElemIndex);
            int prevLevel=StyleConstants.getBidiLevel(prevElem.getAttributes());
            //System.out.println("createbidiElements: prevElem= " + prevElem  + " prevLevel= " + prevLevel + "level[0] = " + levels[0]);
            if( prevLevel==levels[0] ) {
                firstSpanStart = prevElem.getStartOffset();
            } else if( prevElem.getEndOffset() > firstPStart ) {
                newElements.addElement(new BidiElement(bidiRoot,
                                                       prevElem.getStartOffset(),
                                                       firstPStart, prevLevel));
            } else {
                removeFromIndex++;
            }
        }
        
        int firstSpanEnd = 0;
        while((firstSpanEnd<levels.length) && (levels[firstSpanEnd]==levels[0]))
            firstSpanEnd++;


        // Calculate the last span of characters in the affected range with
        // the same bidi level.  If this level is the same as the level of the
        // next bidi element (the existing bidi element containing lastPEnd),
        // then merge in the next element.  If not, but the next element
        // overlaps the affected range, adjust the next element to start at
        // lastPEnd.
        int lastSpanEnd = lastPEnd;
        Element newNextElem = null;
        int removeToIndex = bidiRoot.getElementCount() - 1;
        if( lastSpanEnd <= getLength() ) {
            int nextElemIndex = bidiRoot.getElementIndex( lastPEnd );
            removeToIndex = nextElemIndex;
            Element nextElem = bidiRoot.getElement( nextElemIndex );
            int nextLevel = StyleConstants.getBidiLevel(nextElem.getAttributes());
            if( nextLevel == levels[levels.length-1] ) {
                lastSpanEnd = nextElem.getEndOffset();
            } else if( nextElem.getStartOffset() < lastPEnd ) {
                newNextElem = new BidiElement(bidiRoot, lastPEnd, 
                                              nextElem.getEndOffset(),
                                              nextLevel);
            } else {
                removeToIndex--;
            }
        }
        
        int lastSpanStart = levels.length;
        while( (lastSpanStart>firstSpanEnd)
               && (levels[lastSpanStart-1]==levels[levels.length-1]) )
            lastSpanStart--;


        // If the first and last spans are contiguous and have the same level,
        // merge them and create a single new element for the entire span.
        // Otherwise, create elements for the first and last spans as well as
        // any spans in between.
        if((firstSpanEnd==lastSpanStart)&&(levels[0]==levels[levels.length-1])){
            newElements.addElement(new BidiElement(bidiRoot, firstSpanStart,
                                                   lastSpanEnd, levels[0]));
        } else {
            // Create an element for the first span.
            newElements.addElement(new BidiElement(bidiRoot, firstSpanStart,
                                                   firstSpanEnd+firstPStart,
                                                   levels[0]));
            // Create elements for the spans in between the first and last
            for( int i=firstSpanEnd; i<lastSpanStart; ) {
                //System.out.println("executed line 872");
                int j;
                for( j=i;  (j<levels.length) && (levels[j] == levels[i]); j++ );
                newElements.addElement(new BidiElement(bidiRoot, firstPStart+i,
                                                       firstPStart+j,
                                                       (int)levels[i]));
                i=j;
            }
            // Create an element for the last span.
            newElements.addElement(new BidiElement(bidiRoot,
                                                   lastSpanStart+firstPStart,
                                                   lastSpanEnd,
                                                   levels[levels.length-1]));
        }
        
        if( newNextElem != null )
            newElements.addElement( newNextElem );

        
        // Calculate the set of existing bidi elements which must be
        // removed.
        int removedElemCount = 0;
        if( bidiRoot.getElementCount() > 0 ) {
            removedElemCount = removeToIndex - removeFromIndex + 1;
        }
        Element[] removedElems = new Element[removedElemCount];
        for( int i=0; i<removedElemCount; i++ ) {
            removedElems[i] = bidiRoot.getElement(removeFromIndex+i);
        }            

        Element[] addedElems = new Element[ newElements.size() ];
        newElements.copyInto( addedElems );
        
        // Update the change record.
        ElementEdit ee = new ElementEdit( bidiRoot, removeFromIndex,
                                          removedElems, addedElems );
        chng.addEdit( ee );

        // Update the bidi element structure.
        bidiRoot.replace( removeFromIndex, removedElems.length, addedElems );
    }

    
    /**
     * Calculate the levels array for a range of paragraphs.  
     */
    private byte[] calculateBidiLevels( int firstPStart, int lastPEnd ) {
        
        byte levels[] = new byte[ lastPEnd - firstPStart ];
        int  levelsEnd = 0;
	Boolean defaultDirection = null;  
	Object d = getProperty(TextAttribute.RUN_DIRECTION);
	if (d instanceof Boolean) {
	    defaultDirection = (Boolean) d;
	}

        // For each paragraph in the given range of paragraphs, get its
        // levels array and add it to the levels array for the entire span.
        for(int o=firstPStart; o<lastPEnd; ) {
            Element p = getParagraphElement( o );
            int pStart = p.getStartOffset();
            int pEnd = p.getEndOffset();

	    // default run direction for the paragraph.  This will be
	    // null if there is no direction override specified (i.e. 
	    // the direction will be determined from the content).
            Boolean direction = defaultDirection;
	    d = p.getAttributes().getAttribute(TextAttribute.RUN_DIRECTION);
	    if (d instanceof Boolean) {
		direction = (Boolean) d;
	    }

            //System.out.println("updateBidi: paragraph start = " + pStart + " paragraph end = " + pEnd);
            
            // Create a Bidi over this paragraph then get the level
            // array.
            Segment seg = SegmentCache.getSharedSegment();
            try {
                getText(pStart, pEnd-pStart, seg);
            } catch (BadLocationException e ) {
                throw new Error("Internal error: " + e.toString());
            }
            // REMIND(bcb) we should really be using a Segment here.
            Bidi bidiAnalyzer;
	    int bidiflag = Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
	    if (direction != null) {
		if (TextAttribute.RUN_DIRECTION_LTR.equals(direction)) {
		    bidiflag = Bidi.DIRECTION_LEFT_TO_RIGHT;
		} else {
		    bidiflag = Bidi.DIRECTION_RIGHT_TO_LEFT;
		}
	    }
	    bidiAnalyzer = new Bidi(seg.array, seg.offset, null, 0, seg.count, 
                    bidiflag);
	    BidiUtils.getLevels(bidiAnalyzer, levels, levelsEnd);
	    levelsEnd += bidiAnalyzer.getLength();

            o =  p.getEndOffset();
            SegmentCache.releaseSharedSegment(seg);
        }

        // REMIND(bcb) remove this code when debugging is done.
        if( levelsEnd != levels.length )
            throw new Error("levelsEnd assertion failed.");

        return levels;
    }

    /**
     * Gives a diagnostic dump.
     *
     * @param out the output stream
     */
    public void dump(PrintStream out) {
	Element root = getDefaultRootElement();
	if (root instanceof AbstractElement) {
	    ((AbstractElement)root).dump(out, 0);
	}
        bidiRoot.dump(out,0);
    }

    /**
     * Gets the content for the document.
     *
     * @return the content
     */
    protected final Content getContent() {
	return data;
    }

    /**
     * Creates a document leaf element.
     * Hook through which elements are created to represent the 
     * document structure.  Because this implementation keeps 
     * structure and content separate, elements grow automatically
     * when content is extended so splits of existing elements 
     * follow.  The document itself gets to decide how to generate 
     * elements to give flexibility in the type of elements used.
     *
     * @param parent the parent element
     * @param a the attributes for the element
     * @param p0 the beginning of the range >= 0
     * @param p1 the end of the range >= p0
     * @return the new element
     */
    protected Element createLeafElement(Element parent, AttributeSet a, int p0, int p1) {
	return new LeafElement(parent, a, p0, p1);
    }

    /**
     * Creates a document branch element, that can contain other elements.
     *
     * @param parent the parent element
     * @param a the attributes
     * @return the element
     */
    protected Element createBranchElement(Element parent, AttributeSet a) {
	return new BranchElement(parent, a);
    }

    // --- Document locking ----------------------------------

    /**
     * Fetches the current writing thread if there is one.
     * This can be used to distinguish whether a method is
     * being called as part of an existing modification or
     * if a lock needs to be acquired and a new transaction
     * started.  
     *
     * @return the thread actively modifying the document
     *  or <code>null</code> if there are no modifications in progress
     */
    protected synchronized final Thread getCurrentWriter() {
	return currWriter;
    }

    /**
     * Acquires a lock to begin mutating the document this lock
     * protects.  There can be no writing, notification of changes, or
     * reading going on in order to gain the lock.  Additionally a thread is
     * allowed to gain more than one <code>writeLock</code>,
     * as long as it doesn't attempt to gain additional <code>writeLock</code>s
     * from within document notification.  Attempting to gain a 
     * <code>writeLock</code> from within a DocumentListener notification will
     * result in an <code>IllegalStateException</code>.  The ability
     * to obtain more than one <code>writeLock</code> per thread allows
     * subclasses to gain a writeLock, perform a number of operations, then
     * release the lock.
     * <p>
     * Calls to <code>writeLock</code>
     * must be balanced with calls to <code>writeUnlock</code>, else the
     * <code>Document</code> will be left in a locked state so that no
     * reading or writing can be done.
     *
     * @exception IllegalStateException thrown on illegal lock
     *  attempt.  If the document is implemented properly, this can
     *  only happen if a document listener attempts to mutate the 
     *  document.  This situation violates the bean event model
     *  where order of delivery is not guaranteed and all listeners
     *  should be notified before further mutations are allowed.
     */
    protected synchronized final void writeLock() {
	try {
	    while ((numReaders > 0) || (currWriter != null)) {
		if (Thread.currentThread() == currWriter) {
                    if (notifyingListeners) {
                        // Assuming one doesn't do something wrong in a
                        // subclass this should only happen if a
                        // DocumentListener tries to mutate the document.
                        throw new IllegalStateException(
                                      "Attempt to mutate in notification");
                    }
                    numWriters++;
                    return;
                }
		wait();
	    }
	    currWriter = Thread.currentThread();
            numWriters = 1;
	} catch (InterruptedException e) {
	    throw new Error("Interrupted attempt to aquire write lock");
	}
    }

    /**
     * Releases a write lock previously obtained via <code>writeLock</code>.
     * After decrementing the lock count if there are no oustanding locks
     * this will allow a new writer, or readers.
     *
     * @see #writeLock
     */
    protected synchronized final void writeUnlock() {
        if (--numWriters <= 0) {
            numWriters = 0;
            currWriter = null;
            notifyAll();
        }
    }

    /**
     * Acquires a lock to begin reading some state from the 
     * document.  There can be multiple readers at the same time.
     * Writing blocks the readers until notification of the change
     * to the listeners has been completed.  This method should
     * be used very carefully to avoid unintended compromise
     * of the document.  It should always be balanced with a
     * <code>readUnlock</code>.
     *
     * @see #readUnlock
     */
    public synchronized final void readLock() {
	try {
	    while (currWriter != null) {
		if (currWriter == Thread.currentThread()) {
		    // writer has full read access.... may try to acquire
		    // lock in notification
		    return;
		}
		wait();
	    }
	    numReaders += 1;
	} catch (InterruptedException e) {
	    throw new Error("Interrupted attempt to aquire read lock");
	}
    }

    /**
     * Does a read unlock.  This signals that one
     * of the readers is done.  If there are no more readers
     * then writing can begin again.  This should be balanced
     * with a readLock, and should occur in a finally statement
     * so that the balance is guaranteed.  The following is an
     * example.
     * <pre><code>
     * &nbsp;   readLock();
     * &nbsp;   try {
     * &nbsp;       // do something
     * &nbsp;   } finally {
     * &nbsp;       readUnlock();
     * &nbsp;   }
     * </code></pre>
     *
     * @see #readLock
     */
    public synchronized final void readUnlock() {
	if (currWriter == Thread.currentThread()) {
	    // writer has full read access.... may try to acquire
	    // lock in notification
	    return;
	}
	if (numReaders <= 0) {
	    throw new StateInvariantError(BAD_LOCK_STATE);
	}
	numReaders -= 1;
	notify();
    }

    // --- serialization ---------------------------------------------

    private void readObject(ObjectInputStream s)
      throws ClassNotFoundException, IOException 
    {
	s.defaultReadObject();
	listenerList = new EventListenerList();

        // Restore bidi structure
        //REMIND(bcb) This creates an initial bidi element to account for
        //the \n that exists by default in the content.  
        bidiRoot = new BidiRootElement();
        try {
            writeLock();
            Element[] p = new Element[1];
            p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
            bidiRoot.replace(0,0,p);
        } finally {
            writeUnlock();
        }        
	// At this point bidi root is only partially correct. To fully
	// restore it we need access to getDefaultRootElement. But, this
	// is created by the subclass and at this point will be null. We
	// thus use registerValidation.
	s.registerValidation(new ObjectInputValidation() {
	    public void validateObject() {
		try {
		    writeLock();
		    DefaultDocumentEvent e = new DefaultDocumentEvent
			           (0, getLength(),
				    DocumentEvent.EventType.INSERT);
		    updateBidi( e );
		}
		finally {
		    writeUnlock();
		}
	    }
	}, 0);
    }

    // ----- member variables ------------------------------------------

    private transient int numReaders;
    private transient Thread currWriter;
    /**
     * The number of writers, all obtained from <code>currWriter</code>.
     */
    private transient int numWriters;
    /**
     * True will notifying listeners.
     */
    private transient boolean notifyingListeners;

    private static Boolean defaultI18NProperty;

    /**
     * Storage for document-wide properties.
     */
    private Dictionary<Object,Object> documentProperties = null;

    /**
     * The event listener list for the document.
     */
    protected EventListenerList listenerList = new EventListenerList();

    /**
     * Where the text is actually stored, and a set of marks
     * that track change as the document is edited are managed.
     */
    private Content data;

    /**
     * Factory for the attributes.  This is the strategy for
     * attribute compression and control of the lifetime of
     * a set of attributes as a collection.  This may be shared
     * with other documents.
     */
    private AttributeContext context;

    /**
     * The root of the bidirectional structure for this document.  Its children
     * represent character runs with the same Unicode bidi level.
     */
    private transient BranchElement bidiRoot;
    
    /**
     * Filter for inserting/removing of text.
     */
    private DocumentFilter documentFilter;

    /**
     * Used by DocumentFilter to do actual insert/remove.
     */
    private transient DocumentFilter.FilterBypass filterBypass;

    private static final String BAD_LOCK_STATE = "document lock failure";

    /**
     * Error message to indicate a bad location.
     */
    protected static final String BAD_LOCATION = "document location failure";

    /**
     * Name of elements used to represent paragraphs
     */
    public static final String ParagraphElementName = "paragraph";

    /**
     * Name of elements used to represent content
     */
    public static final String ContentElementName = "content";

    /**
     * Name of elements used to hold sections (lines/paragraphs).
     */
    public static final String SectionElementName = "section";

    /**
     * Name of elements used to hold a unidirectional run
     */
    public static final String BidiElementName = "bidi level";

    /**
     * Name of the attribute used to specify element
     * names.
     */
    public static final String ElementNameAttribute = "$ename";

    /**
     * Document property that indicates whether internationalization
     * functions such as text reordering or reshaping should be
     * performed. This property should not be publicly exposed,
     * since it is used for implementation convenience only.  As a 
     * side effect, copies of this property may be in its subclasses
     * that live in different packages (e.g. HTMLDocument as of now),
     * so those copies should also be taken care of when this property
     * needs to be modified.
     */
    static final String I18NProperty = "i18n";

    /**
     * Document property that indicates if a character has been inserted
     * into the document that is more than one byte long.  GlyphView uses
     * this to determine if it should use BreakIterator.
     */
    static final Object MultiByteProperty = "multiByte";

    /**
     * Document property that indicates asynchronous loading is
     * desired, with the thread priority given as the value.
     */
    static final String AsyncLoadPriority = "load priority";

    /**
     * Interface to describe a sequence of character content that
     * can be edited.  Implementations may or may not support a 
     * history mechanism which will be reflected by whether or not
     * mutations return an UndoableEdit implementation.  
     * @see AbstractDocument
     */
    public interface Content {

	/**
	 * Creates a position within the content that will
	 * track change as the content is mutated.
         *
         * @param offset the offset in the content >= 0
         * @return a Position
         * @exception BadLocationException for an invalid offset
	 */
	public Position createPosition(int offset) throws BadLocationException;

	/**
	 * Current length of the sequence of character content.
         *
         * @return the length >= 0
	 */
        public int length();

	/**
	 * Inserts a string of characters into the sequence.
	 * 
	 * @param where   offset into the sequence to make the insertion >= 0
	 * @param str     string to insert
	 * @return  if the implementation supports a history mechanism, 
	 *    a reference to an <code>Edit</code> implementation will be returned, 
	 *    otherwise returns <code>null</code>
	 * @exception BadLocationException  thrown if the area covered by
	 *   the arguments is not contained in the character sequence
	 */
        public UndoableEdit insertString(int where, String str) throws BadLocationException;

	/**
	 * Removes some portion of the sequence.  
	 *
	 * @param where   The offset into the sequence to make the
         *   insertion >= 0.
	 * @param nitems  The number of items in the sequence to remove >= 0.
	 * @return  If the implementation supports a history mechansim, 
	 *    a reference to an Edit implementation will be returned, 
	 *    otherwise null.
	 * @exception BadLocationException  Thrown if the area covered by
	 *   the arguments is not contained in the character sequence.
	 */
        public UndoableEdit remove(int where, int nitems) throws BadLocationException;

	/**
	 * Fetches a string of characters contained in the sequence.
	 * 
	 * @param where   Offset into the sequence to fetch >= 0.
	 * @param len     number of characters to copy >= 0.
         * @return the string
	 * @exception BadLocationException  Thrown if the area covered by
	 *   the arguments is not contained in the character sequence.
	 */
        public String getString(int where, int len) throws BadLocationException;

        /**
         * Gets a sequence of characters and copies them into a Segment.
         *
         * @param where the starting offset >= 0
         * @param len the number of characters >= 0
         * @param txt the target location to copy into
	 * @exception BadLocationException  Thrown if the area covered by
	 *   the arguments is not contained in the character sequence.
         */
        public void getChars(int where, int len, Segment txt) throws BadLocationException;
    }

    /**
     * An interface that can be used to allow MutableAttributeSet 
     * implementations to use pluggable attribute compression
     * techniques.  Each mutation of the attribute set can be
     * used to exchange a previous AttributeSet instance with
     * another, preserving the possibility of the AttributeSet
     * remaining immutable.  An implementation is provided by
     * the StyleContext class.
     *
     * The Element implementations provided by this class use
     * this interface to provide their MutableAttributeSet
     * implementations, so that different AttributeSet compression
     * techniques can be employed.  The method 
     * <code>getAttributeContext</code> should be implemented to
     * return the object responsible for implementing the desired
     * compression technique.
     * 
     * @see StyleContext
     */
    public interface AttributeContext {

	/**
	 * Adds an attribute to the given set, and returns
	 * the new representative set.
	 *
         * @param old the old attribute set
	 * @param name the non-null attribute name
	 * @param value the attribute value
         * @return the updated attribute set
	 * @see MutableAttributeSet#addAttribute
	 */
        public AttributeSet addAttribute(AttributeSet old, Object name, Object value);

	/**
	 * Adds a set of attributes to the element.
	 *
         * @param old the old attribute set
	 * @param attr the attributes to add
         * @return the updated attribute set
	 * @see MutableAttributeSet#addAttribute
	 */
        public AttributeSet addAttributes(AttributeSet old, AttributeSet attr);

	/**
	 * Removes an attribute from the set.
	 *
         * @param old the old attribute set
	 * @param name the non-null attribute name
         * @return the updated attribute set
	 * @see MutableAttributeSet#removeAttribute
	 */
        public AttributeSet removeAttribute(AttributeSet old, Object name);

	/**
	 * Removes a set of attributes for the element.
	 *
         * @param old the old attribute set
	 * @param names the attribute names
         * @return the updated attribute set
	 * @see MutableAttributeSet#removeAttributes
	 */
        public AttributeSet removeAttributes(AttributeSet old, Enumeration<?> names);

	/**
	 * Removes a set of attributes for the element.
	 *
         * @param old the old attribute set
	 * @param attrs the attributes
         * @return the updated attribute set
	 * @see MutableAttributeSet#removeAttributes
	 */
        public AttributeSet removeAttributes(AttributeSet old, AttributeSet attrs);

	/**
	 * Fetches an empty AttributeSet.
         *
         * @return the attribute set
	 */
	public AttributeSet getEmptySet();

	/**
         * Reclaims an attribute set.
	 * This is a way for a MutableAttributeSet to mark that it no 
	 * longer need a particular immutable set.  This is only necessary
	 * in 1.1 where there are no weak references.  A 1.1 implementation
	 * would call this in its finalize method.
         *
         * @param a the attribute set to reclaim
	 */
	public void reclaim(AttributeSet a);
    }

    /**
     * Implements the abstract part of an element.  By default elements
     * support attributes by having a field that represents the immutable
     * part of the current attribute set for the element.  The element itself
     * implements MutableAttributeSet which can be used to modify the set
     * by fetching a new immutable set.  The immutable sets are provided
     * by the AttributeContext associated with the document.
     * <p>
     * <strong>Warning:</strong>
     * Serialized objects of this class will not be compatible with
     * future Swing releases. The current serialization support is
     * appropriate for short term storage or RMI between applications running
     * the same version of Swing.  As of 1.4, support for long term storage
     * of all JavaBeans<sup><font size="-2">TM</font></sup>
     * has been added to the <code>java.beans</code> package.
     * Please see {@link java.beans.XMLEncoder}.
     */
    public abstract class AbstractElement implements Element, MutableAttributeSet, Serializable, TreeNode {

        /**
         * Creates a new AbstractElement.
         *
         * @param parent the parent element
         * @param a the attributes for the element
	 * @since 1.4
         */
        public AbstractElement(Element parent, AttributeSet a) {
	    this.parent = parent;
	    attributes = getAttributeContext().getEmptySet();
	    if (a != null) {
		addAttributes(a);
	    }
	}

	private final void indent(PrintWriter out, int n) {
	    for (int i = 0; i < n; i++) {
		out.print("  ");
	    }
	}

	/**
	 * Dumps a debugging representation of the element hierarchy.
         *
         * @param psOut the output stream
         * @param indentAmount the indentation level >= 0
	 */
	public void dump(PrintStream psOut, int indentAmount) {
            PrintWriter out;
            try {
                out = new PrintWriter(new OutputStreamWriter(psOut,"JavaEsc"),
                                      true);
            } catch (UnsupportedEncodingException e){
                out = new PrintWriter(psOut,true);
            }
	    indent(out, indentAmount);
	    if (getName() == null) {
		out.print("<??");
	    } else {
		out.print("<" + getName());
	    }
	    if (getAttributeCount() > 0) {
		out.println("");
		// dump the attributes
		Enumeration names = attributes.getAttributeNames();
		while (names.hasMoreElements()) {
		    Object name = names.nextElement();
		    indent(out, indentAmount + 1);
		    out.println(name + "=" + getAttribute(name));
		}
		indent(out, indentAmount);
	    }
	    out.println(">");

	    if (isLeaf()) {
		indent(out, indentAmount+1);
		out.print("[" + getStartOffset() + "," + getEndOffset() + "]");
		Content c = getContent();
		try {
		    String contentStr = c.getString(getStartOffset(), 
                                                    getEndOffset() - getStartOffset())/*.trim()*/;
		    if (contentStr.length() > 40) {
			contentStr = contentStr.substring(0, 40) + "...";
		    }
		    out.println("["+contentStr+"]");		
	        } catch (BadLocationException e) {
			;
		}

	    } else {
		int n = getElementCount();
		for (int i = 0; i < n; i++) {
		    AbstractElement e = (AbstractElement) getElement(i);
		    e.dump(psOut, indentAmount+1);
		}
	    }
	}

	// --- AttributeSet ----------------------------
	// delegated to the immutable field "attributes"

	/**
         * Gets the number of attributes that are defined.
         *
         * @return the number of attributes >= 0
	 * @see AttributeSet#getAttributeCount
	 */
        public int getAttributeCount() {
	    return attributes.getAttributeCount();
	}

	/**
         * Checks whether a given attribute is defined.
         *
         * @param attrName the non-null attribute name
         * @return true if the attribute is defined
	 * @see AttributeSet#isDefined
	 */
        public boolean isDefined(Object attrName) {
	    return attributes.isDefined(attrName);
	}

	/**
         * Checks whether two attribute sets are equal.
         *
         * @param attr the attribute set to check against
         * @return true if the same
	 * @see AttributeSet#isEqual
	 */
        public boolean isEqual(AttributeSet attr) {
	    return attributes.isEqual(attr);
	}

	/**
         * Copies a set of attributes.
         *
         * @return the copy
	 * @see AttributeSet#copyAttributes
	 */
        public AttributeSet copyAttributes() {
	    return attributes.copyAttributes();
	}

	/**
         * Gets the value of an attribute.
         *
         * @param attrName the non-null attribute name
         * @return the attribute value
	 * @see AttributeSet#getAttribute
	 */
        public Object getAttribute(Object attrName) {
	    Object value = attributes.getAttribute(attrName);
	    if (value == null) {
		// The delegate nor it's resolvers had a match,
		// so we'll try to resolve through the parent
		// element.
		AttributeSet a = (parent != null) ? parent.getAttributes() : null;
		if (a != null) {
		    value = a.getAttribute(attrName);
		}
	    }
	    return value;
	}

	/**
         * Gets the names of all attributes.
         *
         * @return the attribute names as an enumeration
	 * @see AttributeSet#getAttributeNames
	 */
        public Enumeration<?> getAttributeNames() {
	    return attributes.getAttributeNames();
	}

	/**
         * Checks whether a given attribute name/value is defined.
         *
         * @param name the non-null attribute name
         * @param value the attribute value
         * @return true if the name/value is defined
	 * @see AttributeSet#containsAttribute
	 */
        public boolean containsAttribute(Object name, Object value) {
	    return attributes.containsAttribute(name, value);
	}


	/**
         * Checks whether the element contains all the attributes.
         *
         * @param attrs the attributes to check
         * @return true if the element contains all the attributes
	 * @see AttributeSet#containsAttributes
	 */
        public boolean containsAttributes(AttributeSet attrs) {
	    return attributes.containsAttributes(attrs);
	}

	/**
         * Gets the resolving parent.
	 * If not overridden, the resolving parent defaults to 
	 * the parent element.
         *
         * @return the attributes from the parent, <code>null</code> if none
	 * @see AttributeSet#getResolveParent
	 */
        public AttributeSet getResolveParent() {
	    AttributeSet a = attributes.getResolveParent();
	    if ((a == null) && (parent != null)) {
		a = parent.getAttributes();
	    }
	    return a;
	}

	// --- MutableAttributeSet ----------------------------------
	// should fetch a new immutable record for the field
	// "attributes".

	/**
         * Adds an attribute to the element.
         *
         * @param name the non-null attribute name
         * @param value the attribute value
	 * @see MutableAttributeSet#addAttribute
	 */
        public void addAttribute(Object name, Object value) {
	    checkForIllegalCast();
	    AttributeContext context = getAttributeContext();
	    attributes = context.addAttribute(attributes, name, value);
	}

	/**
         * Adds a set of attributes to the element.
         *
         * @param attr the attributes to add
	 * @see MutableAttributeSet#addAttribute
	 */
        public void addAttributes(AttributeSet attr) {
	    checkForIllegalCast();
	    AttributeContext context = getAttributeContext();
	    attributes = context.addAttributes(attributes, attr);
	}

	/**
         * Removes an attribute from the set.
         *
         * @param name the non-null attribute name
	 * @see MutableAttributeSet#removeAttribute
	 */
        public void removeAttribute(Object name) {
	    checkForIllegalCast();
	    AttributeContext context = getAttributeContext();
	    attributes = context.removeAttribute(attributes, name);
	}

	/**
         * Removes a set of attributes for the element.
         *
         * @param names the attribute names
	 * @see MutableAttributeSet#removeAttributes
	 */
        public void removeAttributes(Enumeration<?> names) {
	    checkForIllegalCast();
	    AttributeContext context = getAttributeContext();
	    attributes = context.removeAttributes(attributes, names);
	}

	/**
         * Removes a set of attributes for the element.
         *
         * @param attrs the attributes
	 * @see MutableAttributeSet#removeAttributes
	 */
        public void removeAttributes(AttributeSet attrs) {
	    checkForIllegalCast();
	    AttributeContext context = getAttributeContext();
	    if (attrs == this) {
		attributes = context.getEmptySet();
	    } else {
		attributes = context.removeAttributes(attributes, attrs);
	    }
	}

	/**
         * Sets the resolving parent.
         *
         * @param parent the parent, null if none
	 * @see MutableAttributeSet#setResolveParent
	 */
        public void setResolveParent(AttributeSet parent) {
	    checkForIllegalCast();
	    AttributeContext context = getAttributeContext();
	    if (parent != null) {
		attributes = 
		    context.addAttribute(attributes, StyleConstants.ResolveAttribute,
					 parent);
	    } else {
		attributes = 
		    context.removeAttribute(attributes, StyleConstants.ResolveAttribute);
	    }
	}

	private final void checkForIllegalCast() {
	    Thread t = getCurrentWriter();
	    if ((t == null) || (t != Thread.currentThread())) {
		throw new StateInvariantError("Illegal cast to MutableAttributeSet");
	    }
	}

        // --- Element methods -------------------------------------

        /**
         * Retrieves the underlying model.
         *
         * @return the model
         */
	public Document getDocument() {
	    return AbstractDocument.this;
	}

        /**
         * Gets the parent of the element.
         *
         * @return the parent
         */
	public Element getParentElement() {
	    return parent;
	}

        /**
         * Gets the attributes for the element.
         *
         * @return the attribute set
         */
	public AttributeSet getAttributes() {
	    return this;
	}

        /**
         * Gets the name of the element.
         *
         * @return the name, null if none
         */
        public String getName() {
	    if (attributes.isDefined(ElementNameAttribute)) {
		return (String) attributes.getAttribute(ElementNameAttribute);
	    }
	    return null;
	}

        /**
         * Gets the starting offset in the model for the element.
         *
         * @return the offset >= 0
         */
	public abstract int getStartOffset();

        /**
         * Gets the ending offset in the model for the element.
         *
         * @return the offset >= 0
         */
	public abstract int getEndOffset();
    
        /**
         * Gets a child element.
         *
         * @param index the child index, >= 0 && < getElementCount()
         * @return the child element
         */
	public abstract Element getElement(int index);

        /**
         * Gets the number of children for the element.
         *
         * @return the number of children >= 0
         */
	public abstract int getElementCount();

        /**
         * Gets the child element index closest to the given model offset.
         *
         * @param offset the offset >= 0
         * @return the element index >= 0
         */
	public abstract int getElementIndex(int offset);

        /**
         * Checks whether the element is a leaf.
         *
         * @return true if a leaf
         */
	public abstract boolean isLeaf();

        // --- TreeNode methods -------------------------------------

	/**
	 * Returns the child <code>TreeNode</code> at index 
	 * <code>childIndex</code>.
	 */
	public TreeNode getChildAt(int childIndex) {
	    return (TreeNode)getElement(childIndex);
	}

	/**
	 * Returns the number of children <code>TreeNode</code>'s 
         * receiver contains.
         * @return the number of children <code>TreeNodews</code>'s
         * receiver contains
	 */
	public int getChildCount() {
	    return getElementCount();
	}

	/**
	 * Returns the parent <code>TreeNode</code> of the receiver.
         * @return the parent <code>TreeNode</code> of the receiver
	 */
	public TreeNode getParent() {
	    return (TreeNode)getParentElement();
	}

	/**
	 * Returns the index of <code>node</code> in the receivers children.
	 * If the receiver does not contain <code>node</code>, -1 will be
	 * returned.
         * @param node the location of interest
         * @return the index of <code>node</code> in the receiver's
         * children, or -1 if absent
	 */
	public int getIndex(TreeNode node) {
	    for(int counter = getChildCount() - 1; counter >= 0; counter--)
		if(getChildAt(counter) == node)
		    return counter;
	    return -1;
	}

	/**
	 * Returns true if the receiver allows children.
         * @return true if the receiver allows children, otherwise false
	 */
	public abstract boolean getAllowsChildren();


	/**
	 * Returns the children of the receiver as an
         * <code>Enumeration</code>.
         * @return the children of the receiver as an <code>Enumeration</code>
	 */
	public abstract Enumeration children();


	// --- serialization ---------------------------------------------

        private void writeObject(ObjectOutputStream s) throws IOException {
	    s.defaultWriteObject();
	    StyleContext.writeAttributeSet(s, attributes);
	}

        private void readObject(ObjectInputStream s)
            throws ClassNotFoundException, IOException 
        {
	    s.defaultReadObject();
	    MutableAttributeSet attr = new SimpleAttributeSet();
	    StyleContext.readAttributeSet(s, attr);
	    AttributeContext context = getAttributeContext();
	    attributes = context.addAttributes(SimpleAttributeSet.EMPTY, attr);
	}

	// ---- variables -----------------------------------------------------

	private Element parent;
	private transient AttributeSet attributes;

    }

    /**
     * Implements a composite element that contains other elements.
     * <p>
     * <strong>Warning:</strong>
     * Serialized objects of this class will not be compatible with
     * future Swing releases. The current serialization support is
     * appropriate for short term storage or RMI between applications running
     * the same version of Swing.  As of 1.4, support for long term storage
     * of all JavaBeans<sup><font size="-2">TM</font></sup>
     * has been added to the <code>java.beans</code> package.
     * Please see {@link java.beans.XMLEncoder}.
     */
    public class BranchElement extends AbstractElement {

	/**
	 * Constructs a composite element that initially contains
	 * no children.
	 *
	 * @param parent  The parent element
         * @param a the attributes for the element
	 * @since 1.4
	 */
	public BranchElement(Element parent, AttributeSet a) {
	    super(parent, a);
	    children = new AbstractElement[1];
	    nchildren = 0;
	    lastIndex = -1;
	}

	/**
	 * Gets the child element that contains
	 * the given model position.
         *
         * @param pos the position >= 0
         * @return the element, null if none
	 */
	public Element positionToElement(int pos) {
	    int index = getElementIndex(pos);
	    Element child = children[index];
	    int p0 = child.getStartOffset();
	    int p1 = child.getEndOffset();
	    if ((pos >= p0) && (pos < p1)) {
		return child;
	    }
	    return null;
	}

        /**
         * Replaces content with a new set of elements.
         *
         * @param offset the starting offset >= 0
         * @param length the length to replace >= 0
         * @param elems the new elements
         */
        public void replace(int offset, int length, Element[] elems) {
	    int delta = elems.length - length;
	    int src = offset + length;
	    int nmove = nchildren - src;
	    int dest = src + delta;
	    if ((nchildren + delta) >= children.length) {
		// need to grow the array
		int newLength = Math.max(2*children.length, nchildren + delta);
		AbstractElement[] newChildren = new AbstractElement[newLength];
		System.arraycopy(children, 0, newChildren, 0, offset);
		System.arraycopy(elems, 0, newChildren, offset, elems.length);
		System.arraycopy(children, src, newChildren, dest, nmove);
		children = newChildren;
	    } else {
		// patch the existing array
		System.arraycopy(children, src, children, dest, nmove);
		System.arraycopy(elems, 0, children, offset, elems.length);
	    }
	    nchildren = nchildren + delta;
	}

        /**
         * Converts the element to a string.
         *
         * @return the string
         */
	public String toString() {
	    return "BranchElement(" + getName() + ") " + getStartOffset() + "," +
		getEndOffset() + "\n";
	}

	// --- Element methods -----------------------------------

        /**
         * Gets the element name.
         *
         * @return the element name
         */
	public String getName() {
	    String nm = super.getName();
	    if (nm == null) {
		nm = ParagraphElementName;
	    }
	    return nm;
	}

        /**
         * Gets the starting offset in the model for the element.
         *
         * @return the offset >= 0
         */
        public int getStartOffset() {
	    return children[0].getStartOffset();
	}

        /**
         * Gets the ending offset in the model for the element.
         * @throws NullPointerException if this element has no children
         *
         * @return the offset >= 0
         */
        public int getEndOffset() {
	    Element child = 
		(nchildren > 0) ? children[nchildren - 1] : children[0];
	    return child.getEndOffset();
	}
    
        /**
         * Gets a child element.
         *
         * @param index the child index, >= 0 && < getElementCount()
         * @return the child element, null if none
         */
	public Element getElement(int index) {
	    if (index < nchildren) {
		return children[index];
	    }
	    return null;
	}

        /**
         * Gets the number of children for the element.
         *
         * @return the number of children >= 0
         */
	public int getElementCount()  {
	    return nchildren;
	}

        /**
         * Gets the child element index closest to the given model offset.
         *
         * @param offset the offset >= 0
         * @return the element index >= 0
         */
	public int getElementIndex(int offset) {
	    int index;
	    int lower = 0; 
	    int upper = nchildren - 1;
	    int mid = 0;
	    int p0 = getStartOffset();
	    int p1;

	    if (nchildren == 0) {
		return 0;
	    }
	    if (offset >= getEndOffset()) {
		return nchildren - 1;
	    }

	    // see if the last index can be used.
	    if ((lastIndex >= lower) && (lastIndex <= upper)) {
		Element lastHit = children[lastIndex];
		p0 = lastHit.getStartOffset();
		p1 = lastHit.getEndOffset();
		if ((offset >= p0) && (offset < p1)) {
		    return lastIndex;
		}

		// last index wasn't a hit, but it does give useful info about
		// where a hit (if any) would be.
		if (offset < p0) {
		    upper = lastIndex;
		} else  {
		    lower = lastIndex;
		}  
	    }

	    while (lower <= upper) {
		mid = lower + ((upper - lower) / 2);
		Element elem = children[mid];
		p0 = elem.getStartOffset();
		p1 = elem.getEndOffset();
		if ((offset >= p0) && (offset < p1)) {
		    // found the location
		    index = mid;
		    lastIndex = index;
		    return index;
		} else if (offset < p0) {        
		    upper = mid - 1;
		} else {
		    lower = mid + 1;
		}
	    }

	    // didn't find it, but we indicate the index of where it would belong
	    if (offset < p0) {
		index = mid;
	    } else {
		index = mid + 1;
	    }
	    lastIndex = index;
	    return index;   
	}

        /**
         * Checks whether the element is a leaf.
         *
         * @return true if a leaf
         */
	public boolean isLeaf() {
	    return false;
	}


	// ------ TreeNode ----------------------------------------------

	/**
	 * Returns true if the receiver allows children.
         * @return true if the receiver allows children, otherwise false
	 */
	public boolean getAllowsChildren() {
	    return true;
	}


	/**
	 * Returns the children of the receiver as an
         * <code>Enumeration</code>.
         * @return the children of the receiver
	 */
	public Enumeration children() {
	    if(nchildren == 0)
		return null;

	    Vector tempVector = new Vector(nchildren);

	    for(int counter = 0; counter < nchildren; counter++)
		tempVector.addElement(children[counter]);
	    return tempVector.elements();
	}

	// ------ members ----------------------------------------------

	private AbstractElement[] children;
	private int nchildren;
	private int lastIndex;
    }
    
    /**
     * Implements an element that directly represents content of
     * some kind.
     * <p>
     * <strong>Warning:</strong>
     * Serialized objects of this class will not be compatible with
     * future Swing releases. The current serialization support is
     * appropriate for short term storage or RMI between applications running
     * the same version of Swing.  As of 1.4, support for long term storage
     * of all JavaBeans<sup><font size="-2">TM</font></sup>
     * has been added to the <code>java.beans</code> package.
     * Please see {@link java.beans.XMLEncoder}.
     *
     * @see     Element
     */
    public class LeafElement extends AbstractElement {

	/**
	 * Constructs an element that represents content within the
	 * document (has no children).
	 *
	 * @param parent  The parent element
	 * @param a       The element attributes
	 * @param offs0   The start offset >= 0
	 * @param offs1   The end offset >= offs0
	 * @since 1.4
	 */
	public LeafElement(Element parent, AttributeSet a, int offs0, int offs1) {
	    super(parent, a);
	    try {
		p0 = createPosition(offs0);
		p1 = createPosition(offs1);
	    } catch (BadLocationException e) {
		p0 = null;
		p1 = null;
		throw new StateInvariantError("Can't create Position references");
	    }
	}

        /**
         * Converts the element to a string.
         *
         * @return the string
         */
	public String toString() {
	    return "LeafElement(" + getName() + ") " + p0 + "," + p1 + "\n";
	}

	// --- Element methods ---------------------------------------------

        /**
         * Gets the starting offset in the model for the element.
         *
         * @return the offset >= 0
         */
	public int getStartOffset() {
	    return p0.getOffset();
	}

        /**
         * Gets the ending offset in the model for the element.
         *
         * @return the offset >= 0
         */
	public int getEndOffset() {
	    return p1.getOffset();
	}

        /**
         * Gets the element name.
         *
         * @return the name
         */
	public String getName() {
	    String nm = super.getName();
	    if (nm == null) {
		nm = ContentElementName;
	    }
	    return nm;
	}

        /**
         * Gets the child element index closest to the given model offset.
         *
         * @param pos the offset >= 0
         * @return the element index >= 0
         */
	public int getElementIndex(int pos) {
	    return -1;
	}

        /**
         * Gets a child element.
         *
         * @param index the child index, >= 0 && < getElementCount()
         * @return the child element
         */
	public Element getElement(int index) {
	    return null;
	}

        /**
         * Returns the number of child elements.
         *
         * @return the number of children >= 0
         */
	public int getElementCount()  {
	    return 0;
	}

        /**
         * Checks whether the element is a leaf.
         *
         * @return true if a leaf
         */
	public boolean isLeaf() {
	    return true;
	}

	// ------ TreeNode ----------------------------------------------

	/**
	 * Returns true if the receiver allows children.
         * @return true if the receiver allows children, otherwise false
	 */
	public boolean getAllowsChildren() {
	    return false;
	}


	/**
	 * Returns the children of the receiver as an
         * <code>Enumeration</code>.
         * @return the children of the receiver
	 */
	public Enumeration children() {
	    return null;
	}

	// --- serialization ---------------------------------------------

        private void writeObject(ObjectOutputStream s) throws IOException {
	    s.defaultWriteObject();
	    s.writeInt(p0.getOffset());
	    s.writeInt(p1.getOffset());
	}

        private void readObject(ObjectInputStream s)
            throws ClassNotFoundException, IOException 
        {
	    s.defaultReadObject();

	    // set the range with positions that track change
	    int off0 = s.readInt();
	    int off1 = s.readInt();
	    try {
		p0 = createPosition(off0);
		p1 = createPosition(off1);
	    } catch (BadLocationException e) {
		p0 = null;
		p1 = null;
		throw new IOException("Can't restore Position references");
	    }
	}

	// ---- members -----------------------------------------------------

	private transient Position p0;
	private transient Position p1;
    }

    /**
     * Represents the root element of the bidirectional element structure.
     * The root element is the only element in the bidi element structure
     * which contains children.  
     */
    class BidiRootElement extends BranchElement {

	BidiRootElement() {
            super( null, null );
	}

        /**
         * Gets the name of the element.
         * @return the name
         */
        public String getName() {
	    return "bidi root";
	}
    }

    /**
     * Represents an element of the bidirectional element structure.
     */
    class BidiElement extends LeafElement {

        /**
         * Creates a new BidiElement.
         */
	BidiElement(Element parent, int start, int end, int level) {
	    super(parent, new SimpleAttributeSet(), start, end);
            addAttribute(StyleConstants.BidiLevel, new Integer(level));
            //System.out.println("BidiElement: start = " + start
            //                   + " end = " + end + " level = " + level );
	}

        /**
         * Gets the name of the element.
         * @return the name
         */
        public String getName() {
	    return BidiElementName;
	}

        int getLevel() {
            Integer o = (Integer) getAttribute(StyleConstants.BidiLevel);
            if (o != null) {
                return o.intValue();
            }
            return 0;  // Level 0 is base level (non-embedded) left-to-right
        }

        boolean isLeftToRight() {
            return ((getLevel() % 2) == 0);
        }            
    }

    /**
     * Stores document changes as the document is being
     * modified.  Can subsequently be used for change notification
     * when done with the document modification transaction.
     * This is used by the AbstractDocument class and its extensions
     * for broadcasting change information to the document listeners.
     */
    public class DefaultDocumentEvent extends CompoundEdit implements DocumentEvent {

	/**
	 * Constructs a change record.
	 *
	 * @param offs the offset into the document of the change >= 0
	 * @param len  the length of the change >= 0
	 * @param type the type of event (DocumentEvent.EventType)
	 * @since 1.4
	 */
        public DefaultDocumentEvent(int offs, int len, DocumentEvent.EventType type) {
	    super();
	    offset = offs;
	    length = len;
	    this.type = type;
	}

	/**
	 * Returns a string description of the change event.
	 *
	 * @return a string
	 */
        public String toString() {
	    return edits.toString();
	}
	
	// --- CompoundEdit methods --------------------------

	/**
	 * Adds a document edit.  If the number of edits crosses
	 * a threshold, this switches on a hashtable lookup for
	 * ElementChange implementations since access of these
	 * needs to be relatively quick.
	 *
	 * @param anEdit a document edit record
	 * @return true if the edit was added
	 */ 
        public boolean addEdit(UndoableEdit anEdit) {
	    // if the number of changes gets too great, start using
	    // a hashtable for to locate the change for a given element.
	    if ((changeLookup == null) && (edits.size() > 10)) {
		changeLookup = new Hashtable();
		int n = edits.size();
		for (int i = 0; i < n; i++) {
		    Object o = edits.elementAt(i);
		    if (o instanceof DocumentEvent.ElementChange) {
			DocumentEvent.ElementChange ec = (DocumentEvent.ElementChange) o;
			changeLookup.put(ec.getElement(), ec);
		    }
		}
	    }

	    // if we have a hashtable... add the entry if it's 
	    // an ElementChange.
	    if ((changeLookup != null) && (anEdit instanceof DocumentEvent.ElementChange)) {
		DocumentEvent.ElementChange ec = (DocumentEvent.ElementChange) anEdit;
		changeLookup.put(ec.getElement(), ec);
	    }
	    return super.addEdit(anEdit);
	}

	/**
	 * Redoes a change.
	 *
	 * @exception CannotRedoException if the change cannot be redone
	 */
        public void redo() throws CannotRedoException {
	    writeLock();
	    try {
		// change the state
		super.redo();
		// fire a DocumentEvent to notify the view(s)
                UndoRedoDocumentEvent ev = new UndoRedoDocumentEvent(this, false);
		if (type == DocumentEvent.EventType.INSERT) {
		    fireInsertUpdate(ev);
		} else if (type == DocumentEvent.EventType.REMOVE) {
		    fireRemoveUpdate(ev);
		} else {
		    fireChangedUpdate(ev);
		}
	    } finally {
		writeUnlock();
	    }
	}

	/**
	 * Undoes a change.
	 *
	 * @exception CannotUndoException if the change cannot be undone
	 */
        public void undo() throws CannotUndoException {
	    writeLock();
	    try {
		// change the state
		super.undo();
		// fire a DocumentEvent to notify the view(s)
                UndoRedoDocumentEvent ev = new UndoRedoDocumentEvent(this, true);
		if (type == DocumentEvent.EventType.REMOVE) {
		    fireInsertUpdate(ev);
		} else if (type == DocumentEvent.EventType.INSERT) {
		    fireRemoveUpdate(ev);
		} else {
		    fireChangedUpdate(ev);
		}
	    } finally {
		writeUnlock();
	    }
	}

	/**
	 * DefaultDocument events are significant.  If you wish to aggregate
	 * DefaultDocumentEvents to present them as a single edit to the user
	 * place them into a CompoundEdit.
         *
         * @return whether the event is significant for edit undo purposes
	 */
	public boolean isSignificant() {
	    return true;
	}


	/**
	 * Provides a localized, human readable description of this edit
	 * suitable for use in, say, a change log.
         *
         * @return the description
	 */
	public String getPresentationName() {
	    DocumentEvent.EventType type = getType();
	    if(type == DocumentEvent.EventType.INSERT)
		return UIManager.getString("AbstractDocument.additionText");
	    if(type == DocumentEvent.EventType.REMOVE)
		return UIManager.getString("AbstractDocument.deletionText");
	    return UIManager.getString("AbstractDocument.styleChangeText");
	}

	/**
	 * Provides a localized, human readable description of the undoable
	 * form of this edit, e.g. for use as an Undo menu item. Typically
	 * derived from getDescription();
         *
         * @return the description
	 */
	public String getUndoPresentationName() {
	    return UIManager.getString("AbstractDocument.undoText") + " " +
                getPresentationName();
	}

	/**
	 * Provides a localized, human readable description of the redoable
	 * form of this edit, e.g. for use as a Redo menu item. Typically
	 * derived from getPresentationName();
         *
         * @return the description
	 */
	public String getRedoPresentationName() {
	    return UIManager.getString("AbstractDocument.redoText") + " " +
                getPresentationName();
	}

	// --- DocumentEvent methods --------------------------

	/**
	 * Returns the type of event.
         *
         * @return the event type as a DocumentEvent.EventType
	 * @see DocumentEvent#getType
	 */
	public DocumentEvent.EventType getType() {
	    return type;
	}

	/**
	 * Returns the offset within the document of the start of the change.
	 *
	 * @return the offset >= 0
	 * @see DocumentEvent#getOffset
	 */
        public int getOffset() {
	    return offset;
	}

	/**
	 * Returns the length of the change.
	 *
	 * @return the length >= 0
	 * @see DocumentEvent#getLength
	 */
        public int getLength() {
	    return length;
	}
	
	/**
	 * Gets the document that sourced the change event.
	 *
	 * @return the document
	 * @see DocumentEvent#getDocument
	 */
        public Document getDocument() {
	    return AbstractDocument.this;
	}

	/**
	 * Gets the changes for an element.
	 *
	 * @param elem the element
	 * @return the changes
	 */
        public DocumentEvent.ElementChange getChange(Element elem) {
	    if (changeLookup != null) {
		return (DocumentEvent.ElementChange) changeLookup.get(elem);
	    }
	    int n = edits.size();
	    for (int i = 0; i < n; i++) {
		Object o = edits.elementAt(i);
		if (o instanceof DocumentEvent.ElementChange) {
		    DocumentEvent.ElementChange c = (DocumentEvent.ElementChange) o;
		    if (elem.equals(c.getElement())) {
			return c;
		    }
		}
	    }
	    return null;
	}

	// --- member variables ------------------------------------

        private int offset;
        private int length;
        private Hashtable changeLookup;
	private DocumentEvent.EventType type;

    }

    /**
     * This event used when firing document changes while Undo/Redo
     * operations. It just wraps DefaultDocumentEvent and delegates
     * all calls to it except getType() which depends on operation
     * (Undo or Redo).
     */
    class UndoRedoDocumentEvent implements DocumentEvent {
        private DefaultDocumentEvent src = null;
        private boolean isUndo;
        private EventType type = null;

        public UndoRedoDocumentEvent(DefaultDocumentEvent src, boolean isUndo) {
            this.src = src;
            this.isUndo = isUndo;
            if(isUndo) {
                if(src.getType().equals(EventType.INSERT)) {
                    type = EventType.REMOVE;
                } else if(src.getType().equals(EventType.REMOVE)) {
                    type = EventType.INSERT;
                } else {
                    type = src.getType();
                }
            } else {
                type = src.getType();
            }
        }

        public DefaultDocumentEvent getSource() {
            return src;
        }

        // DocumentEvent methods delegated to DefaultDocumentEvent source
        // except getType() which depends on operation (Undo or Redo).
        public int getOffset() {
            return src.getOffset();
        }

        public int getLength() {
            return src.getLength();
        }

        public Document getDocument() {
            return src.getDocument();
        }

        public DocumentEvent.EventType getType() {
            return type;
        }

        public DocumentEvent.ElementChange getChange(Element elem) {
            return src.getChange(elem);
        }
    }

    /**
     * An implementation of ElementChange that can be added to the document
     * event.
     */
    public static class ElementEdit extends AbstractUndoableEdit implements DocumentEvent.ElementChange {

	/**
	 * Constructs an edit record.  This does not modify the element
	 * so it can safely be used to <em>catch up</em> a view to the
	 * current model state for views that just attached to a model.
	 *
	 * @param e the element
	 * @param index the index into the model >= 0
	 * @param removed a set of elements that were removed
	 * @param added a set of elements that were added
	 */
        public ElementEdit(Element e, int index, Element[] removed, Element[] added) {
	    super();
	    this.e = e;
	    this.index = index;
	    this.removed = removed;
	    this.added = added;
	}
	    
	/**
	 * Returns the underlying element.
	 *
	 * @return the element
	 */
        public Element getElement() {
	    return e;
	} 

	/**
	 * Returns the index into the list of elements.
	 *
	 * @return the index >= 0
	 */
        public int getIndex() {
	    return index;
	}

	/**
	 * Gets a list of children that were removed.
	 *
	 * @return the list
	 */
        public Element[] getChildrenRemoved() {
	    return removed;
	}

	/**
	 * Gets a list of children that were added.
	 *
	 * @return the list
	 */
        public Element[] getChildrenAdded() {
	    return added;
	}

	/**
	 * Redoes a change.
	 *
	 * @exception CannotRedoException if the change cannot be redone
	 */
        public void redo() throws CannotRedoException {
	    super.redo();

	    // Since this event will be reused, switch around added/removed.
	    Element[] tmp = removed;
	    removed = added;
	    added = tmp;

	    // PENDING(prinz) need MutableElement interface, canRedo() should check
	    ((AbstractDocument.BranchElement)e).replace(index, removed.length, added);
	}

	/**
	 * Undoes a change.
	 *
	 * @exception CannotUndoException if the change cannot be undone
	 */
        public void undo() throws CannotUndoException {
	    super.undo();
	    // PENDING(prinz) need MutableElement interface, canUndo() should check
	    ((AbstractDocument.BranchElement)e).replace(index, added.length, removed);

	    // Since this event will be reused, switch around added/removed.
	    Element[] tmp = removed;
	    removed = added;
	    added = tmp;
	}

        private Element e;
	private int index;
	private Element[] removed;
	private Element[] added;
    }


    private class DefaultFilterBypass extends DocumentFilter.FilterBypass {
        public Document getDocument() {
            return AbstractDocument.this;
        }

        public void remove(int offset, int length) throws
            BadLocationException {
            handleRemove(offset, length);
        }

        public void insertString(int offset, String string,
                                 AttributeSet attr) throws
                                        BadLocationException {
            handleInsertString(offset, string, attr);
        }

        public void replace(int offset, int length, String text,
                            AttributeSet attrs) throws BadLocationException {
            handleRemove(offset, length);
            handleInsertString(offset, text, attrs);
        }
    }
}






	

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar