Skip to main content
aboutsummaryrefslogblamecommitdiffstats
blob: c1484c23c9afd5c21582cef9b95f0909cdc30878 (plain) (tree)
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
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
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
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547






















                                                                       
                                 

                                         


























                                                
                                     























                                                                                                     
                                                                          

































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                                                                



































                                                                                                                       































































                                                                                                      
                                                                                                  





















































































































































































































































































































































                                                                                                                                                        
 



                                                                        







                                                                                                 


                                                           
                                                    
                                               
                                                








                                                                      
                                                                                            
         



























                                                                                                                                                       








































































                                                                                     
                                                                                

                                 

                                                              





                                        



                                                         








                                                                  





















                                                                                        





                                                                                                                         







































































































































































































































































































































































































































































































































































                                                                                                                                                              




                                        





































































































































































































                                                                                                                                        

                                                                               


                                                        
                                                   
                                                
                                                                            
                                                                    



                                                            




























                                                                                                           






























































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                                                                   









                                                                                                                   

















































































































































































































































































































                                                                                                          
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html

Contributors:
    IBM Corporation - Initial implementation
**********************************************************************/

package org.eclipse.jface.text;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.LineBackgroundEvent;
import org.eclipse.swt.custom.LineBackgroundListener;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.ScrollBar;

import org.eclipse.jface.text.Assert;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;



/**
 * SWT based implementation of <code>ITextViewer</code>. Once the viewer and its SWT control
 * have been created the viewer can only indirectly be disposed by disposing its SWT control.<p>
 * Clients are supposed to instantiate a text viewer and subsequently to communicate with it 
 * exclusively using the <code>ITextViewer</code> interface or any of the implemented extension
 * interfaces. <p>
 * A text viewer serves as text operation target. It only partially supports the external control of
 * the enable state of its text operations. A text viewer is also a widget token owner. Anything that
 * wants to display an overlay window on top of a text viewer should implement the 
 * <code>IWidgetTokenKeeper</code> interface and participate in the widget token negotiation between
 * the text viewer and all its potential widget token keepers.<p>
 * Clients should no subclass this class as it is rather likely that subclasses will be broken by
 * future releases.
 * 
 * @see ITextViewer
 */  
public class TextViewer extends Viewer implements 
		ITextViewer, ITextViewerExtension, ITextViewerExtension2, 
		ITextOperationTarget, ITextOperationTargetExtension,
		IWidgetTokenOwner {
	
	/** Internal flag to indicate the debug state. */
	public static boolean TRACE_ERRORS= false;
	
	/**
	 * Represents a replace command that brings the text viewer's text widget
	 * back in sync with text viewer's document after the document has been changed.
	 */
	protected class WidgetCommand {
		
		public DocumentEvent event;
		public int start, length;
		public String text, preservedText;
				
		/**
		 * Translates a document event into the presentation coordinates of this text viewer.
		 *
		 * @param e the event to be translated
		 */
		public void setEvent(DocumentEvent e) {
			
			event= e;
			
			start= e.getOffset();
			length= e.getLength();
			text= e.getText();
			
			if (length != 0) {
				try {
					preservedText= e.getDocument().get(e.getOffset(), e.getLength());
				} catch (BadLocationException x) {
					preservedText= null;
					if (TRACE_ERRORS)
						System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.WidgetCommand.setEvent")); //$NON-NLS-1$
				}
			} else
				preservedText= null;
		}
	};
		
	/**
	 * Connects a text double click strategy to this viewer's text widget. 
	 * Calls the double click strategy when the mouse has been double clicked 
	 * inside the text editor.
	 */	
	class TextDoubleClickStrategyConnector extends MouseAdapter {
		
		/** Internal flag to remember that a double clicked occurred. */
		private boolean fDoubleClicked= false;
		
		public TextDoubleClickStrategyConnector() {
		}
				
		/*
		 * @see MouseListener#mouseDoubleClick(MouseEvent)
		 */
		public void mouseDoubleClick(MouseEvent e) {
			fDoubleClicked= true;
		}
			
		/*
		 * @see MouseListener#mouseUp(MouseEvent)
		 */
		public void mouseUp(MouseEvent e) {
			if (fDoubleClicked) {
				fDoubleClicked= false;
				ITextDoubleClickStrategy s= (ITextDoubleClickStrategy) selectContentTypePlugin(getSelectedRange().x, fDoubleClickStrategies);
				if (s != null)
					s.doubleClicked(TextViewer.this);
			}
		}
	};
	
	/**
	 * Monitors the area of the viewer's document that is visible in the viewer. 
	 * If the area might have changed, it informs the text viewer about this
	 * potential change and its origin. The origin is internally used for optimization
	 * purposes.
	 */
	class ViewportGuard extends MouseAdapter 
		implements ControlListener, KeyListener, MouseMoveListener, SelectionListener {
		
		/*
		 * @see ControlListener#controlResized(ControlEvent)
		 */
		public void controlResized(ControlEvent e) {
			updateViewportListeners(RESIZE);
		}
		
		/*
		 * @see ControlListener#controlMoved(ControlEvent)
		 */
		public void controlMoved(ControlEvent e) {
		}
		
		/*
		 * @see KeyListener#keyReleased
		 */
		public void keyReleased(KeyEvent e) {
			updateViewportListeners(KEY);
		}

		/*
		 * @see KeyListener#keyPressed
		 */
		public void keyPressed(KeyEvent e) {
			updateViewportListeners(KEY);
		}

		/*
		 * @see MouseListener#mouseUp
		 */
		public void mouseUp(MouseEvent e) {
			if (fTextWidget != null)
				fTextWidget.removeMouseMoveListener(this);
			updateViewportListeners(MOUSE_END);
		}

		/*
		 * @see MouseListener#mouseDown
		 */
		public void mouseDown(MouseEvent e) {
			if (fTextWidget != null)
				fTextWidget.addMouseMoveListener(this);
		}

		/*
		 * @see MouseMoveListener#mouseMove
		 */
		public void mouseMove(MouseEvent e) {
			updateViewportListeners(MOUSE);
		}

		/*
		 * @see SelectionListener#widgetSelected
		 */
		public void widgetSelected(SelectionEvent e) {
			updateViewportListeners(SCROLLER);
		}

		/*
		 * @see SelectionListener#widgetDefaultSelected
		 */
		public void widgetDefaultSelected(SelectionEvent e) {}
	};
		
	/**
	 * This position updater is used to keep the selection during text shift operations.
	 */
	static class ShiftPositionUpdater extends DefaultPositionUpdater {
		
		/**
		 * Creates the position updater for the given category.
		 *
		 * @param category the category this updater takes care of
		 */
		protected ShiftPositionUpdater(String category) {
			super(category);
		}
		
		/**
		 * If an insertion happens at the selection's start offset,
		 * the position is extended rather than shifted.
		 */
		protected void adaptToInsert() {
			
			int myStart= fPosition.offset;
			int myEnd=   fPosition.offset + fPosition.length -1;
			myEnd= Math.max(myStart, myEnd);
			
			int yoursStart= fOffset;
			int yoursEnd=   fOffset + fReplaceLength -1;
			yoursEnd= Math.max(yoursStart, yoursEnd);
			
			if (myEnd < yoursStart)
				return;
			
			if (myStart <= yoursStart) {
				fPosition.length += fReplaceLength;
				return;
			}
			
			if (myStart > yoursStart)
				fPosition.offset += fReplaceLength;		
		}
	};
	
	/**
	 * Internal document listener.
	 */
	class DocumentListener implements IDocumentListener {
		
		/*
		 * @see IDocumentListener#documentAboutToBeChanged
		 */
		public void documentAboutToBeChanged(DocumentEvent e) {
			if (e.getDocument() == getVisibleDocument())
				fWidgetCommand.setEvent(e);
		}
		
		/*
		 * @see IDocumentListener#documentChanged
		 */
		public void documentChanged(final DocumentEvent e) {
			if (fWidgetCommand.event == e)
				updateTextListeners(fWidgetCommand);
		}
	};
	
	
	/**
	 * Internal verify listener.
	 */
	class TextVerifyListener implements VerifyListener {
		
		/**
		 * Indicates whether verify events are forwarded or ignored.
		 * @since 2.0
		 */
		private boolean fForward= true;
		
		/**
		 * Tells the listener to forward received events.
		 * 
		 * @param forward <code>true</code> if forwarding should be enabled.
		 * @since 2.0
		 */
		public void forward(boolean forward) {
			fForward= forward;
		}
		
		/*
		 * @see VerifyListener#verifyText(VerifyEvent)
		 */
		public void verifyText(VerifyEvent e) {
			if (fForward)
				handleVerifyEvent(e);
		}	
	};
	
	/**
	 * The viewer's manager reponsible for registered verify key listeners.
	 * Uses batches rather than robust iterators because of performance issues.
	 * 
	 * @since 2.0
	 */
	class VerifyKeyListenersManager implements VerifyKeyListener {
		
		/**
		 * Represents a batched addListener/removeListener command.
		 */
		class Batch {
			/** The index at which to insert the listener. */
			int index;
			/** The listener to be inserted. */
			VerifyKeyListener listener;
			
			/**
			 * Creates a new batch containing the given listener for the given index.
			 * 
			 * @param l the listener to be added
			 * @param i the index at which to insert the listener
			 */
			public Batch(VerifyKeyListener l, int i) {
				listener= l;
				index= i;
			}
		};
		
		/** List of registed verify key listeners. */
		private List fListeners= new ArrayList();
		/** List of pending batches. */
		private List fBatched= new ArrayList();
		/** The currently active iterator. */
		private Iterator fIterator;
		
		/*
		 * @see VerifyKeyListener#verifyKey(VerifyEvent)
		 */
		public void verifyKey(VerifyEvent event) {
			if (fListeners.isEmpty())
				return;
				
			fIterator= fListeners.iterator();
			while (fIterator.hasNext() && event.doit) {
				VerifyKeyListener listener= (VerifyKeyListener) fIterator.next();
				listener.verifyKey(event);
			}
			fIterator= null;
			
			processBatchedRequests();
		}
		
		/**
		 * Processes the pending batched requests.
		 */
		private void processBatchedRequests() {
			if (!fBatched.isEmpty()) {
				Iterator e= fBatched.iterator();
				while (e.hasNext()) {
					Batch batch= (Batch) e.next();
					insertListener(batch.listener, batch.index);
				}
				fBatched.clear();
			}
		}
		
		/**
		 * Returns the number of registered verify key listeners.
		 * 
		 * @return the number of registered verify key listeners
		 */
		public int numberOfListeners() {
			return fListeners.size();
		}
		
		/**
		 * Inserts the given listener at the given index or moves it
		 * to that index.
		 * 
		 * @param listener the listener to be inserted
		 * @param index the index of the listener or -1 for remove
		 */
		public void insertListener(VerifyKeyListener listener, int index) {
			
			if (index == -1) {
				removeListener(listener);
			} else if (listener != null) {
				
				if (fIterator != null) {
					
					fBatched.add(new Batch(listener, index));
				
				} else {
					
					int idx= -1;
					
					// find index based on identity
					int size= fListeners.size();
					for (int i= 0; i < size; i++) {
						if (listener == fListeners.get(i)) {
							idx= i;
							break;
						}
					}
					
					// move or add it
					if (idx != index) {
						
						if (idx != -1)
							fListeners.remove(idx);
							
						if (index > fListeners.size())
							fListeners.add(listener);
						else
							fListeners.add(index, listener);
					}
					
					if (size == 0)  // checking old size, i.e. current size == size + 1
						install();
				}
			}
		}
		
		/**
		 * Removes the given listener.
		 * 
		 * @param listener the listener to be removed
		 */
		public void removeListener(VerifyKeyListener listener) {
			if (listener == null)
				return;
			
			if (fIterator != null) {
				
				fBatched.add(new Batch(listener, -1));
			
			} else {
				
				int size= fListeners.size();
				for (int i= 0; i < size; i++) {
					if (listener == fListeners.get(i)) {
						fListeners.remove(i);
						if (size == 1)  // checking old size, i.e. current size == size - 1
							uninstall();
						return;
					}
				}
			}
		}
		
		/**
		 * Installs this manager.
		 */
		private void install() {
			StyledText textWidget= getTextWidget();
			if (textWidget != null && !textWidget.isDisposed())
				textWidget.addVerifyKeyListener(this);
		}
		
		/**
		 * Uninstalls this manager.
		 */
		private void uninstall() {
			StyledText textWidget= getTextWidget();
			if (textWidget != null && !textWidget.isDisposed())
				textWidget.removeVerifyKeyListener(this);
		}
	};
	
	
	/**
	 * Reification of a range in which a find replace operation is performed. This range is visually 
	 * highlighted in the viewer as long as the replace operation is in progress.
	 * 
	 * @since 2.0
	 */
	class FindReplaceRange implements LineBackgroundListener, ITextListener, IPositionUpdater {		

		/** Internal name for the position category used to update the range. */
		private final static String RANGE_CATEGORY= "org.eclipse.jface.text.TextViewer.find.range"; //$NON-NLS-1$

		/** The highlight color of this range. */
		private Color fHighlightColor;
		/** The region describing this range's extend. */
		private IRegion fRange;
		/** The position used to lively update this range's extent. */
		private Position fPosition;
		
		/** Creates a new find/replace range with the given extent.
		 * 
		 * @param range the extent of this range 
		 */
		public FindReplaceRange(IRegion range) {
			setRange(range);
		}
		
		/** 
		 * Sets the extent of this range.
		 * 
		 * @param range the extent of this range
		 */
		public void setRange(IRegion range) {
			fPosition= new Position(range.getOffset(), range.getLength());
		}
		
		/**
		 * Returns the extent of this range.
		 * 
		 * @return the extent of this range
		 */
		public IRegion getRange() {
			return new Region(fPosition.getOffset(), fPosition.getLength());
		}
		
		/**
		 * Sets the highlight color of this range. Causes the range to be redrawn.
		 * 
		 * @param color the highlight color
		 */
		public void setHighlightColor(Color color) {
			fHighlightColor= color;
			paint();
		}

		/*
		 * @see LineBackgroundListener#lineGetBackground(LineBackgroundEvent)
		 * @since 2.0
		 */
		public void lineGetBackground(LineBackgroundEvent event) {
			/* Don't use cached line information because of patched redrawing events. */
			
			if (fTextWidget != null) {
				int offset= event.lineOffset + TextViewer.this.getVisibleRegionOffset();
				
				if (fPosition.includes(offset))
					event.lineBackground= fHighlightColor;
			}
		}
		
		/**
		 * Installs this range. The range registers itself as background
		 * line painter and text listener. Also, it creates a category with the
		 * viewer's document to maintain its own extent.
		 */
		public void install() {
			TextViewer.this.addTextListener(this);						
			fTextWidget.addLineBackgroundListener(this);

			IDocument document= TextViewer.this.getDocument();
			try {
				document.addPositionCategory(RANGE_CATEGORY);
				document.addPosition(RANGE_CATEGORY, fPosition);
				document.addPositionUpdater(this);
			} catch (BadPositionCategoryException e) {
				// should not happen
			} catch (BadLocationException e) {
				// should not happen
			}

			paint();
		}
		
		/**
		 * Uninstalls this range.
		 * @see #install()
		 */
		public void uninstall() {
			
			// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19612
			
			IDocument document= TextViewer.this.getDocument();
			if (document != null) {
				document.removePositionUpdater(this);
				document.removePosition(fPosition);
			}

			if (fTextWidget != null && !fTextWidget.isDisposed())
				fTextWidget.removeLineBackgroundListener(this);
			
			TextViewer.this.removeTextListener(this);						

			clear();
		}
		
		/**
		 * Clears the highlighting of this range.
		 */
		private void clear() {
			if (fTextWidget != null && !fTextWidget.isDisposed())
				fTextWidget.redraw();
		}
		
		/**
		 * Paints the highlighting of this range.
		 */
		private void paint() {
			int offset= fPosition.getOffset() - TextViewer.this.getVisibleRegionOffset();
			int length= fPosition.getLength();

			int count= fTextWidget.getCharCount();
			if (offset + length >= count) {
				length= count - offset; // clip

				Point upperLeft= fTextWidget.getLocationAtOffset(offset);
				Point lowerRight= fTextWidget.getLocationAtOffset(offset + length);
				int width= fTextWidget.getClientArea().width;
				int height= fTextWidget.getLineHeight() + lowerRight.y - upperLeft.y;
				fTextWidget.redraw(upperLeft.x, upperLeft.y, width, height, false);
			}			
			
			fTextWidget.redrawRange(offset, length, true);
		}

		/*
		 * @see ITextListener#textChanged(TextEvent)
		 * @since 2.0
		 */
		public void textChanged(TextEvent event) {
			if (event.getViewerRedrawState())
				paint();
		}

		/*
		 * @see IPositionUpdater#update(DocumentEvent)
		 * @since 2.0
		 */
		public void update(DocumentEvent event) {
			int offset= event.getOffset();
			int length= event.getLength();
			int delta= event.getText().length() - length;

			if (offset < fPosition.getOffset())
				fPosition.setOffset(fPosition.getOffset() + delta);
			else if (offset < fPosition.getOffset() + fPosition.getLength())
				fPosition.setLength(fPosition.getLength() + delta);
		}
	};
	
	/**
	 * This viewer's find/replace target.
	 */
	class FindReplaceTarget implements IFindReplaceTarget, IFindReplaceTargetExtension {

		/** The range for this target. */
		private FindReplaceRange fRange;
		/** The highlight color of the range of this target. */
		private Color fScopeHighlightColor;
		/** The document partitioner remembered in case of a "Replace All". */
		private IDocumentPartitioner fRememberedPartitioner;
		
		/*
		 * @see IFindReplaceTarget#getSelectionText()
		 */
		public String getSelectionText() {
			Point s= TextViewer.this.getSelectedRange();
			if (s.x > -1 && s.y > -1) {
				try {
					IDocument document= TextViewer.this.getDocument();
					return document.get(s.x, s.y);
				} catch (BadLocationException x) {
				}
			}
			return null;
		}
		
		/*
		 * @see IFindReplaceTarget#replaceSelection(String)
		 */
		public void replaceSelection(String text) {
			Point s= TextViewer.this.getSelectedRange();
			if (s.x > -1 && s.y > -1) {
				try {
					IDocument document= TextViewer.this.getDocument();
					document.replace(s.x, s.y, text);
					if (text != null && text.length() > 0)
						TextViewer.this.setSelectedRange(s.x, text.length());
				} catch (BadLocationException x) {
				}
			}
		}
		
		/*
		 * @see IFindReplaceTarget#isEditable()
		 */
		public boolean isEditable() {
			return TextViewer.this.isEditable();
		}
				
		/*
		 * @see IFindReplaceTarget#getSelection()
		 */
		public Point getSelection() {
			Point point= TextViewer.this.getSelectedRange();
			point.x -= TextViewer.this.getVisibleRegionOffset();
			return point;
		}
		
		/*
		 * @see IFindReplaceTarget#findAndSelect(int, String, boolean, boolean, boolean)
		 */
		public int findAndSelect(int offset, String findString, boolean searchForward, boolean caseSensitive, boolean wholeWord) {
			if (offset != -1)
				offset += TextViewer.this.getVisibleRegionOffset();

			if (fRange != null) {
				IRegion range= fRange.getRange();
				offset= TextViewer.this.findAndSelectInRange(offset, findString, searchForward, caseSensitive, wholeWord, range.getOffset(), range.getLength());
			} else {
				offset= TextViewer.this.findAndSelect(offset, findString, searchForward, caseSensitive, wholeWord);
			}

			if (offset != -1)
				offset -= TextViewer.this.getVisibleRegionOffset();

			return offset;
		}
		
		/*
		 * @see IFindReplaceTarget#canPerformFind()
		 */
		public boolean canPerformFind() {
			return TextViewer.this.canPerformFind();
		}	

		/*
		 * @see IFindReplaceTargetExtension#beginSession()
		 * @since 2.0
		 */
		public void beginSession() {
			fRange= null;
		}

		/*
		 * @see IFindReplaceTargetExtension#endSession()
		 * @since 2.0
		 */
		public void endSession() {
			if (fRange != null) {
				fRange.uninstall();
				fRange= null;
			}
		}

		/*
		 * @see IFindReplaceTargetExtension#getScope()
		 * @since 2.0
		 */
		public IRegion getScope() {			
			return fRange == null ? null : fRange.getRange();
		}

		/*
		 * @see IFindReplaceTargetExtension#getLineSelection()
		 * @since 2.0
		 */
		public Point getLineSelection() {
			Point point= TextViewer.this.getSelectedRange();

			try {
				IDocument document= TextViewer.this.getDocument();

				// beginning of line
				int line= document.getLineOfOffset(point.x);
				int offset= document.getLineOffset(line);

				// end of line
				line= document.getLineOfOffset(point.x + point.y);
				int length= document.getLineOffset(line) + document.getLineLength(line)	- offset;

				return new Point(offset, length);

			} catch (BadLocationException e) {
				// should not happen			
				return null;
			}
		}

		/*
		 * @see IFindReplaceTargetExtension#setSelection(int, int)
		 * @since 2.0
		 */
		public void setSelection(int offset, int length) {
			TextViewer.this.setSelectedRange(offset /*+ TextViewer.this.getVisibleRegionOffset()*/, length);
		}

		/*
		 * @see IFindReplaceTargetExtension#setScope(IRegion)
		 * @since 2.0
		 */
		public void setScope(IRegion scope) {
			if (fRange != null)
				fRange.uninstall();

			if (scope == null) {
				fRange= null;
				return;
			}
			
			fRange= new FindReplaceRange(scope);
			fRange.setHighlightColor(fScopeHighlightColor);
			fRange.install();			
		}

		/*
		 * @see IFindReplaceTargetExtension#setScopeHighlightColor(Color)
		 * @since 2.0
		 */
		public void setScopeHighlightColor(Color color) {
			if (fRange != null)
				fRange.setHighlightColor(color);
			fScopeHighlightColor= color;
		}

		/*
		 * @see IFindReplaceTargetExtension#setReplaceAllMode(boolean)
		 * @since 2.0
		 */
		public void setReplaceAllMode(boolean replaceAll) {
			
			// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18232
			
			if (replaceAll) {
				
				TextViewer.this.setRedraw(false);
				TextViewer.this.startSequentialRewriteMode(false);
				
				if (fUndoManager != null)
					fUndoManager.beginCompoundChange();
				
				IDocument document= TextViewer.this.getDocument();
				fRememberedPartitioner= document.getDocumentPartitioner();
				if (fRememberedPartitioner != null) {
					fRememberedPartitioner.disconnect();
					document.setDocumentPartitioner(null);
				}

			} else {
				
				TextViewer.this.setRedraw(true);
				TextViewer.this.stopSequentialRewriteMode();
				
				if (fUndoManager != null)
					fUndoManager.endCompoundChange();
					
				if (fRememberedPartitioner != null) {
					IDocument document= TextViewer.this.getDocument();
					fRememberedPartitioner.connect(document);
					document.setDocumentPartitioner(fRememberedPartitioner);
				}
			}
		}
	};
	
	
	/**
	 * The viewer's rewrite target.
	 * @since 2.0
	 */
	class RewriteTarget implements IRewriteTarget {
		
		/*
		 * @see org.eclipse.jface.text.IRewriteTarget#beginCompoundChange()
		 */
		public void beginCompoundChange() {
			if (fUndoManager != null)
				fUndoManager.beginCompoundChange();
		}
		
		/*
		 * @see org.eclipse.jface.text.IRewriteTarget#endCompoundChange()
		 */
		public void endCompoundChange() {
			if (fUndoManager != null)
				fUndoManager.endCompoundChange();
		}
		
		/*
		 * @see org.eclipse.jface.text.IRewriteTarget#getDocument()
		 */
		public IDocument getDocument() {
			return TextViewer.this.getDocument();
		}
		
		/*
		 * @see org.eclipse.jface.text.IRewriteTarget#setRedraw(boolean)
		 */
		public void setRedraw(boolean redraw) {
			TextViewer.this.setRedraw(redraw);
		}
	};
	
	/**
	 * Value object uses as key in the text hover configuration table. It is
	 * modifiable only for efficiency reasons only inside this compilation unit
	 * to allow the reuse of created objects.
	 */
	protected class TextHoverKey {

		private String fContentType;
		private int fStateMask;

		protected TextHoverKey(String contentType, int stateMask) {
			Assert.isNotNull(contentType);
			fContentType= contentType;
			fStateMask= stateMask;
		}
		
		/*
		 * @see java.lang.Object#equals(java.lang.Object)
		 */
		public boolean equals(Object obj) {
			if (obj == null || obj.getClass() != getClass())
				return false;
			TextHoverKey textHoverKey= (TextHoverKey)obj;
			return textHoverKey.fContentType.equals(fContentType) && textHoverKey.fStateMask == fStateMask;
		}

		/*
		 * @see java.lang.Object#hashCode()
		 */
		public int hashCode() {
	 		return fStateMask << 16 | fContentType.hashCode();
		}

		private void setStateMask(int stateMask) {
			fStateMask= stateMask;
		}
	}
		
	/** ID for originators of view port changes */
	protected static final int SCROLLER=		1;
	protected static final int MOUSE=			2;
	protected static final int MOUSE_END=	3;
	protected static final int KEY=				4;
	protected static final int RESIZE=			5;
	protected static final int INTERNAL=		6;
		
	/** Internal name of the position category used selection preservation during shift */
	protected static final String SHIFTING= "__TextViewer_shifting"; //$NON-NLS-1$

	/** The viewer's text widget */
	private StyledText fTextWidget;
	/** The viewer's input document */
	private IDocument fDocument;
	/** The viewer's visible document */
	private IDocument fVisibleDocument;
	/** The viewer's document adapter */
	private IDocumentAdapter fDocumentAdapter;
	/** The child document manager */
	private ChildDocumentManager fChildDocumentManager;
	/** The text viewer's double click strategies connector */
	private TextDoubleClickStrategyConnector fDoubleClickStrategyConnector;
	/** 
	 * The text viewer's hovering controller
	 * @since 2.0
	 */
	private AbstractHoverInformationControlManager fTextHoverManager;
	/** The text viewer's viewport guard */
	private ViewportGuard fViewportGuard;
	/** Caches the graphical coordinate of the first visible line */ 
	private int fTopInset= 0;
	/** The most recent document modification as widget command */
	private WidgetCommand fWidgetCommand= new WidgetCommand();	
	/** The SWT control's scrollbars */
	private ScrollBar fScroller;
	/** Document listener */
	private DocumentListener fDocumentListener= new DocumentListener();
	/** Verify listener */
	private TextVerifyListener fVerifyListener= new TextVerifyListener();
	/** The most recent widget modification as document command */
	private DocumentCommand fDocumentCommand= new DocumentCommand();
	/** The viewer's find/replace target */
	private IFindReplaceTarget fFindReplaceTarget;
	/** 
	 * The viewer widget token keeper
	 * @since 2.0
	 */
	private IWidgetTokenKeeper fWidgetTokenKeeper;
	/** 
	 * The viewer's manager of verify key listeners
	 * @since 2.0
	 */
	private VerifyKeyListenersManager fVerifyKeyListenersManager= new VerifyKeyListenersManager();
	/** 
	 * The mark position.
	 * @since 2.0
	 */
	private Position fMarkPosition;
	/** 
	 * The mark position category.
	 * @since 2.0
	 */
	private final String MARK_POSITION_CATEGORY="__mark_category_" + hashCode(); //$NON-NLS-1$
	/** 
	 * The mark position updater
	 * @since 2.0
	 */
	private final IPositionUpdater fMarkPositionUpdater= new DefaultPositionUpdater(MARK_POSITION_CATEGORY);
	/** 
	 * The flag indicating the redraw behavior
	 * @since 2.0
	 */
	private int fRedrawCounter= 0;
	/** 
	 * The selection when working in non-redraw state
	 * @since 2.0
	 */
	private Point fDocumentSelection;
	/** 
	 * The viewer's rewrite target
	 * @since 2.0
	 */
	private IRewriteTarget fRewriteTarget;
	
	
	/** Should the auto indent strategies ignore the next edit operation */
	protected boolean  fIgnoreAutoIndent= false;
	/** The strings a line is prefixed with on SHIFT_RIGHT and removed from each line on SHIFT_LEFT */
	protected Map fIndentChars;
	/** The string a line is prefixed with on PREFIX and removed from each line on STRIP_PREFIX */
	protected Map fDefaultPrefixChars;
	/** The text viewer's text double click strategies */
	protected Map fDoubleClickStrategies;
	/** The text viewer's undo manager */
	protected IUndoManager fUndoManager;
	/** The text viewer's auto indent strategies */
	protected Map fAutoIndentStrategies;
	/** The text viewer's text hovers */
	protected Map fTextHovers;
	/** 
	 * The creator of the text hover control
	 * @since 2.0
	 */
	protected IInformationControlCreator fHoverControlCreator;
	/** All registered viewport listeners> */
	protected List fViewportListeners;
	/** The last visible vertical position of the top line */
	protected int fLastTopPixel;
	/** All registered text listeners */
	protected List fTextListeners;
	/** All registered text input listeners */
	protected List fTextInputListeners;
	/** The text viewer's event consumer */
	protected IEventConsumer fEventConsumer;
	/** Indicates whether the viewer's text presentation should be replaced are modified. */
	protected boolean fReplaceTextPresentation= false;
	
	
	//---- Construction and disposal ------------------
	
	
	/**
	 * Internal use only
	 */
	protected TextViewer() {
	}
		
	/**
	 * Create a new text viewer with the given SWT style bits.
	 * The viewer is ready to use but does not have any plug-in installed.
	 *
	 * @param parent the parent of the viewer's control
	 * @param styles the SWT style bits for the viewer's control
	 */
	public TextViewer(Composite parent, int styles) {
		createControl(parent, styles);
	}
		
	/**
	 * Factory method to create the text widget to be used as the viewer's text widget.
	 * 
	 * @return the text widget to be used
	 */
	protected StyledText createTextWidget(Composite parent, int styles) {
		return new StyledText(parent, styles);
	}
	
	/**
	 * Factory method to create the document adapter to be used by this viewer.
	 * 
	 * @return the document adapter to be used
	 */
	protected IDocumentAdapter createDocumentAdapter() {
		return new DocumentAdapter();
	}
	
	/**
	 * Creates the viewer's SWT control. The viewer's text widget either is
	 * the control or is a child of the control.
	 *
	 * @param parent the parent of the viewer's control
	 * @param styles the SWT style bits for the viewer's control
	 */
	protected void createControl(Composite parent, int styles) {
					
		fTextWidget= createTextWidget(parent, styles);
		fTextWidget.addDisposeListener(
			new DisposeListener() {
				public void widgetDisposed(DisposeEvent e) {
					setDocument(null);
					handleDispose();
					fTextWidget= null;		
				}
			}
		);
		
		fTextWidget.setFont(parent.getFont());
		fTextWidget.setDoubleClickEnabled(false);
		
		/*
		 * Disable SWT Shift+TAB traversal in this viewer
		 * 1GIYQ9K: ITPUI:WINNT - StyledText swallows Shift+TAB
		 */
		fTextWidget.addTraverseListener(new TraverseListener() {
			public void keyTraversed(TraverseEvent e) {
				if ((SWT.SHIFT == e.stateMask) && ('\t' == e.character))
					e.doit = false;
			}	
		});
		
		// where does the first line start
		fTopInset= -fTextWidget.computeTrim(0, 0, 0, 0).y;
		
		fVerifyListener.forward(true);
		fTextWidget.addVerifyListener(fVerifyListener);
		
		fTextWidget.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent event) {
				selectionChanged(event.x, event.y - event.x);
			}
			public void widgetSelected(SelectionEvent event) {
				selectionChanged(event.x, event.y - event.x);
			}
		});
		
		initializeViewportUpdate();
	}
		
	/*
	 * @see Viewer#getControl
	 */
	public Control getControl() {
		return fTextWidget;
	}
	
	/*
	 * @see ITextViewer#activatePlugin
	 */
	public void activatePlugins() {
		
		if (fDoubleClickStrategies != null && !fDoubleClickStrategies.isEmpty() && fDoubleClickStrategyConnector == null) {
			fDoubleClickStrategyConnector= new TextDoubleClickStrategyConnector();
			fTextWidget.addMouseListener(fDoubleClickStrategyConnector);
		}
		
		if (fTextHovers != null && !fTextHovers.isEmpty() && fHoverControlCreator != null && fTextHoverManager == null) {			
			fTextHoverManager= new TextViewerHoverManager(this, fHoverControlCreator);
			fTextHoverManager.install(this.getTextWidget());
		}
		
		if (fUndoManager != null) {
			fUndoManager.connect(this);
			fUndoManager.reset();
		}
	}
	
	/*
	 * @see ITextViewer#resetPlugins()
	 */
	public void resetPlugins() {
		if (fUndoManager != null)
			fUndoManager.reset();
	}
	
	/**
	 * Frees all resources allocated by this viewer. Internally called when the viewer's
	 * control has been disposed.
	 */
	protected void handleDispose() {
		
		removeViewPortUpdate();
		fViewportGuard= null;
				
		if (fViewportListeners != null) {
			fViewportListeners.clear();
			fViewportListeners= null;
		}
		
		if (fTextListeners != null) {
			fTextListeners.clear();
			fTextListeners= null;
		}
		
		if (fAutoIndentStrategies != null) {
			fAutoIndentStrategies.clear();
			fAutoIndentStrategies= null;
		}
		
		if (fUndoManager != null) {
			fUndoManager.disconnect();
			fUndoManager= null;
		}
		
		if (fDoubleClickStrategies != null) {
			fDoubleClickStrategies.clear();
			fDoubleClickStrategies= null;
		}
		
		if (fTextHovers != null) {
			fTextHovers.clear();
			fTextHovers= null;
		}
		
		fDoubleClickStrategyConnector= null;
		
		if (fTextHoverManager != null) {
			fTextHoverManager.dispose();
			fTextHoverManager= null;
		}
		
		if (fDocumentListener != null)
			fDocumentListener= null;
		
		if (fVisibleDocument instanceof ChildDocument) {
			ChildDocument child = (ChildDocument) fVisibleDocument;
			child.removeDocumentListener(fDocumentListener);
			getChildDocumentManager().freeChildDocument(child);
		}
		
		if (fDocumentAdapter != null) {
			fDocumentAdapter.setDocument(null);
			fDocumentAdapter= null;
		}
		
		fVisibleDocument= null;
		fDocument= null;
		fChildDocumentManager= null;
		fScroller= null;
	}
	
			
	//---- simple getters and setters
			
	/**
	 * Returns viewer's text widget.
	 */
	public StyledText getTextWidget() {
		return fTextWidget;
	}
			
	/*
	 * @see ITextViewer#setAutoIndentStrategy
	 */
	public void setAutoIndentStrategy(IAutoIndentStrategy strategy, String contentType) {
		
		if (strategy != null) {
			if (fAutoIndentStrategies == null)
				fAutoIndentStrategies= new HashMap();
			fAutoIndentStrategies.put(contentType, strategy);
		} else if (fAutoIndentStrategies != null)
			fAutoIndentStrategies.remove(contentType);
	}
	
	/*
	 * @see ITextViewer#setEventConsumer
	 */
	public void setEventConsumer(IEventConsumer consumer) {
		fEventConsumer= consumer;
	}
		
	/*
	 * @see ITextViewer#setIndentPrefixes 
	 */
	public void setIndentPrefixes(String[] indentPrefixes, String contentType) {
					
		int i= -1;
		boolean ok= (indentPrefixes != null);
		while (ok &&  ++i < indentPrefixes.length)
			ok= (indentPrefixes[i] != null);
		
		if (ok) {
			
			if (fIndentChars == null)
				fIndentChars= new HashMap();
			
			fIndentChars.put(contentType, indentPrefixes);
		
		} else if (fIndentChars != null)
			fIndentChars.remove(contentType);
	}
				
	/*
	 * @see ITextViewer#getTopInset
	 */
	public int getTopInset() {
		return fTopInset;
	}
	
	/*
	 * @see ITextViewer#isEditable
	 */
	public boolean isEditable() {
		if (fTextWidget == null)
			return false;
		return fTextWidget.getEditable();
	}
	
	/*
	 * @see ITextViewer#setEditable
	 */
	public void setEditable(boolean editable) {
		if (fTextWidget != null)
			fTextWidget.setEditable(editable);
	}
			
	/*
	 * @see ITextViewer#setDefaultPrefixes
	 * @since 2.0
	 */
	public void setDefaultPrefixes(String[] defaultPrefixes, String contentType) {
				
		if (defaultPrefixes != null && defaultPrefixes.length > 0) {
			if (fDefaultPrefixChars == null)
				fDefaultPrefixChars= new HashMap();
			fDefaultPrefixChars.put(contentType, defaultPrefixes);
		} else if (fDefaultPrefixChars != null)
			fDefaultPrefixChars.remove(contentType);
	}
	
	/*
	 * @see ITextViewer#setUndoManager
	 */
	public void setUndoManager(IUndoManager undoManager) {
		fUndoManager= undoManager;
	}

	/*
	 * @see ITextViewer#setTextHover
	 */
	public void setTextHover(ITextHover hover, String contentType) {
		setTextHover(hover, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
	}

	/*
	 * @see ITextViewerExtension2#setTextHover
	 */
	public void setTextHover(ITextHover hover, String contentType, int stateMask) {
		TextHoverKey key= new TextHoverKey(contentType, stateMask);
		if (hover != null) {
			if (fTextHovers == null)
				fTextHovers= new HashMap();
			fTextHovers.put(key, hover);
		} else if (fTextHovers != null)
			fTextHovers.remove(key);
	}
	
	/**
	 * Returns the text hover for a given offset.
	 * 
	 * @param offset the offset for which to return the text hover
	 * @return the text hover for the given offset
	 */
	protected ITextHover getTextHover(int offset) {
		return getTextHover(offset, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
	}

	/**
	 * Returns the text hover for a given offset.
	 * 
	 * @param offset the offset for which to return the text hover
	 * @param stateMask the SWT event state mask
	 * @return the text hover for the given offset
	 */
	protected ITextHover getTextHover(int offset, int stateMask) {
		if (fTextHovers == null)
			return null;

		try {
			TextHoverKey key= new TextHoverKey(getDocument().getContentType(offset), stateMask);
			Object textHover= fTextHovers.get(key);
			if (textHover == null) {
				// Use default text hover
				key.setStateMask(ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
				textHover= fTextHovers.get(key);
			}
			return (ITextHover)textHover;
		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.selectContentTypePlugin")); //$NON-NLS-1$
		}
		return null;
	}

	/**
	 * Returns the text hovering controller of this viewer.
	 * 
	 * @return the text hovering controller of this viewer
	 * @since 2.0
	 */
	protected AbstractInformationControlManager getTextHoveringController() {
		return fTextHoverManager;
	}
	
	/**
	 * Sets the creator for the hover controls.
	 *  
	 * @param creator the hover control creator
	 * @since 2.0
	 */
	public void setHoverControlCreator(IInformationControlCreator creator) {
		fHoverControlCreator= creator;
	}
	
	/*
	 * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
	 * @since 2.0
	 */
	public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
		if (fTextWidget != null) {
			if (fWidgetTokenKeeper != null) {
				if (fWidgetTokenKeeper == requester)
					return true;
				if (fWidgetTokenKeeper.requestWidgetToken(this)) {
					fWidgetTokenKeeper= requester;
					return true;
				}
			} else {
				fWidgetTokenKeeper= requester;
				return true;
			}
		}
		return false;
	}
	
	/*
	 * @see IWidgetTokenOwner#releaseWidgetToken(IWidgetTokenKeeper)
	 * @since 2.0
	 */
	public void releaseWidgetToken(IWidgetTokenKeeper tokenKeeper) {
		if (fWidgetTokenKeeper == tokenKeeper)
			fWidgetTokenKeeper= null;
	}
	
	
	//---- Selection
	
	/*
	 * @see ITextViewer#getSelectedRange
	 */
	public Point getSelectedRange() {
		
		if (!redraws())
			return new Point(fDocumentSelection.x, fDocumentSelection.y);
			
		if (fTextWidget != null) {
			Point p= fTextWidget.getSelectionRange();
			int offset= getVisibleRegionOffset();			
			return new Point(p.x + offset, p.y);
		}
		
		return new Point(-1, -1);
	}
	
	/*
	 * @see ITextViewer#setSelectedRange
	 */
	public void setSelectedRange(int selectionOffset, int selectionLength) {
		
		if (!redraws()) {
			fDocumentSelection.x= selectionOffset;
			fDocumentSelection.y= selectionLength;
			return;
		}
		
		if (fTextWidget == null)
			return;
			
		IDocument document= getVisibleDocument();
		if (document == null)
			return;
			
		int offset= selectionOffset;
		int length= selectionLength;
		if (selectionLength < 0) {
			offset= selectionOffset + selectionLength;
			length= -selectionLength;
		}
		
		int end= offset + length;
			
		if (document instanceof ChildDocument) {
			Position p= ((ChildDocument) document).getParentDocumentRange();
			if (p.overlapsWith(offset, length)) {
				
				if (offset < p.getOffset())
					offset= p.getOffset();
				offset -= p.getOffset();	
				
				int e= p.getOffset() + p.getLength();
				if (end > e)
					end= e;
				end -= p.getOffset();
				
			} else
				return; 
		}			
		
		length= end - offset;
		
		int[] selectionRange= new int[] { offset, length };
		validateSelectionRange(selectionRange);
		if (selectionRange[0] >= 0 && selectionRange[1] >= 0) {
			
			if (selectionLength < 0)
				fTextWidget.setSelectionRange(selectionRange[0] + selectionRange[1], -selectionRange[1]);
			else
				fTextWidget.setSelectionRange(selectionRange[0], selectionRange[1]);
			
			selectionChanged(selectionRange[0], selectionRange[1]);
		}
	}
	
	/**
	 * Validates and adapts the given selection range if it is not a valid
	 * widget selection. The widget selection is invalid if it starts or ends
	 * inside a multi-character line delimiter. If so, the selection is adapted to
	 * start <b>after</b> the divided line delimiter and to end <b>before</b>
	 * the divided line delimiter.  The parameter passed in is changed in-place
	 * when being adapted. An adaptation to <code>[-1, -1]</code> indicates
	 * that the selection range could not be validated.
	 * Subclasses may reimplement this method.
	 * 
	 * @param selectionRange selectionRange[0] is the offset, selectionRange[1]
	 * 				the length of the selection to validate.
	 * @since 2.0
	 */
	protected void validateSelectionRange(int[] selectionRange) {
		
		IDocument document= getVisibleDocument();
		int documentLength= document.getLength();
		
		int offset= selectionRange[0];
		int length= selectionRange[1];
		
		
		if (offset <0)
			offset= 0;
			
		if (offset > documentLength)
			offset= documentLength;
			
		int delta= (offset + length) - documentLength;
		if (delta > 0)
			length -= delta;
			
		try {
			
			int lineNumber= document.getLineOfOffset(offset);
			IRegion lineInformation= document.getLineInformation(lineNumber);
			
			int lineEnd= lineInformation.getOffset() + lineInformation.getLength();
			delta= offset - lineEnd;
			if (delta > 0) {
				// in the middle of a multi-character line delimiter
				offset= lineEnd;
				String delimiter= document.getLineDelimiter(lineNumber);
				if (delimiter != null)
					offset += delimiter.length();
			}
						
			int end= offset + length;
			lineInformation= document.getLineInformationOfOffset(end);
			lineEnd= lineInformation.getOffset() + lineInformation.getLength();
			delta= end - lineEnd;
			if (delta > 0) {
				// in the middle of a multi-character line delimiter
				length -= delta;
			}
			
		} catch (BadLocationException x) {
			selectionRange[0]= -1;
			selectionRange[1]= -1;
			return;
		}
		
		selectionRange[0]= offset;
		selectionRange[1]= length;
	}

	/*
	 * @see Viewer#setSelection(ISelection)
	 */
	public void setSelection(ISelection selection, boolean reveal) {
		if (selection instanceof ITextSelection) {
			ITextSelection s= (ITextSelection) selection;
			setSelectedRange(s.getOffset(), s.getLength());
			if (reveal)
				revealRange(s.getOffset(), s.getLength());
		}
	}
	
	/*
	 * @see Viewer#getSelection()
	 */
	public ISelection getSelection() {
		Point p= getSelectedRange();
		if (p.x == -1 || p.y == -1)
			return TextSelection.emptySelection();
			
		return new TextSelection(getDocument(), p.x, p.y);
	}
	
	/*
	 * @see ITextViewer#getSelectionProvider
	 */
	public ISelectionProvider getSelectionProvider() {
		return this;
	}
	
	/**
	 * Sends out a text selection changed event to all registered listeners.
	 *
	 * @param offset the offset of the newly selected range in the visible document
	 * @param length the length of the newly selected range in the visible document
	 */
	protected void selectionChanged(int offset, int length) {
		if (redraws()) {
			ISelection selection= new TextSelection(getDocument(), getVisibleRegionOffset() + offset, length);
			SelectionChangedEvent event= new SelectionChangedEvent(this, selection);
			fireSelectionChanged(event);
		}
	}
	
	/**
	 * Sends out a mark selection changed event to all registered listeners.
	 * 
	 * @param offset the offset of the mark selection in the visible document, the offset is <code>-1</code> if the mark was cleared
	 * @param length the length of the mark selection, may be negative if the caret is before the mark.
	 * @since 2.0
	 */
	protected void markChanged(int offset, int length) {
		if (redraws()) {
			if (offset != -1)
				offset += getVisibleRegionOffset();
			ISelection selection= new MarkSelection(getDocument(), offset, length);
			SelectionChangedEvent event= new SelectionChangedEvent(this, selection);
			fireSelectionChanged(event);
		}
	}
	
	
	//---- Text listeners
	
	/*
	 * @see ITextViewer#addTextListener
	 */
	public void addTextListener(ITextListener listener) {
		if (fTextListeners == null)
			fTextListeners= new ArrayList();
	
		if (!fTextListeners.contains(listener))
			fTextListeners.add(listener);
	}
	
	/*
	 * @see ITextViewer#removeTextListener
	 */
	public void removeTextListener(ITextListener listener) {
		if (fTextListeners != null) {
			fTextListeners.remove(listener);
			if (fTextListeners.size() == 0)
				fTextListeners= null;
		}
	}
	
	/**
	 * Informs all registered text listeners about the change specified by the
	 * widget command. This method does not use a robust iterator.
	 *
	 * @param cmd the widget command translated into a text event sent to all text listeners
	 */
	protected void updateTextListeners(WidgetCommand cmd) {
		
		if (fTextListeners != null) {
			
			DocumentEvent event= cmd.event;
			if (event instanceof ChildDocumentEvent)
				event= ((ChildDocumentEvent) event).getParentEvent();
				
			TextEvent e= new TextEvent(cmd.start, cmd.length, cmd.text, cmd.preservedText, event, redraws());
			for (int i= 0; i < fTextListeners.size(); i++) {
				ITextListener l= (ITextListener) fTextListeners.get(i);
				l.textChanged(e);
			}
		}
	}
	
	//---- Text input listeners
	
	/*
	 * @see ITextViewer#addTextInputListener
	 */
	public void addTextInputListener(ITextInputListener listener) {
		if (fTextInputListeners == null)
			fTextInputListeners= new ArrayList();
	
		if (!fTextInputListeners.contains(listener))
			fTextInputListeners.add(listener);
	}
	
	/*
	 * @see ITextViewer#removeTextInputListener
	 */
	public void removeTextInputListener(ITextInputListener listener) {
		if (fTextInputListeners != null) {
			fTextInputListeners.remove(listener);
			if (fTextInputListeners.size() == 0)
				fTextInputListeners= null;
		}
	}
	
	/**
	 * Informs all registered text input listeners about the forthcoming input change,
	 * This method does not use a robust iterator.
	 *
	 * @param oldInput the old input document
	 * @param newInput the new input document
	 */
	protected void fireInputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
		if (fTextInputListeners != null) {
			for (int i= 0; i < fTextInputListeners.size(); i++) {
				ITextInputListener l= (ITextInputListener) fTextInputListeners.get(i);
				l.inputDocumentAboutToBeChanged(oldInput, newInput);
			}
		}
	}
	
	/**
	 * Informs all registered text input listeners about the sucessful input change,
	 * This method does not use a robust iterator.
	 *
	 * @param oldInput the old input document
	 * @param newInput the new input document
	 */
	protected void fireInputDocumentChanged(IDocument oldInput, IDocument newInput) {		
		if (fTextInputListeners != null) {
			for (int i= 0; i < fTextInputListeners.size(); i++) {
				ITextInputListener l= (ITextInputListener) fTextInputListeners.get(i);
				l.inputDocumentChanged(oldInput, newInput);
			}
		}
	}
	
	//---- Document
	
	/*
	 * @see Viewer#getInput
	 */
	public Object getInput() {
		return getDocument();
	}
	
	/*
	 * @see ITextViewer#getDocument
	 */
	public IDocument getDocument() {
		return fDocument;
	}
	
	/*
	 * @see Viewer#setInput
	 */
	public void setInput(Object input) {
		
		IDocument document= null;
		if (input instanceof IDocument)
			document= (IDocument) input;
		
		setDocument(document);
	}
	
	/*
	 * @see ITextViewer#setDocument(IDocument)
	 */
	public void setDocument(IDocument document) {
		
		fReplaceTextPresentation= true;
		fireInputDocumentAboutToBeChanged(fDocument, document);
				
		IDocument oldDocument= fDocument;
		fDocument= document;
		
		setVisibleDocument(fDocument);
		
		inputChanged(fDocument, oldDocument);
		
		fireInputDocumentChanged(oldDocument, fDocument);
		fReplaceTextPresentation= false;
	}
	
	/*
	 * @see ITextViewer#setDocument(IDocument, int int)
	 */
	public void setDocument(IDocument document, int visibleRegionOffset, int visibleRegionLength) {
		
		fReplaceTextPresentation= true;
		fireInputDocumentAboutToBeChanged(fDocument, document);
				
		IDocument oldDocument= fDocument;
		fDocument= document;
		
		try {
			int line= fDocument.getLineOfOffset(visibleRegionOffset);
			int offset= fDocument.getLineOffset(line);
			int length= (visibleRegionOffset - offset) + visibleRegionLength;
			setVisibleDocument(getChildDocumentManager().createChildDocument(fDocument, offset, length));
		} catch (BadLocationException x) {
			throw new IllegalArgumentException(JFaceTextMessages.getString("TextViewer.error.invalid_visible_region_1")); //$NON-NLS-1$
		}
		
		inputChanged(fDocument, oldDocument);
		
		fireInputDocumentChanged(oldDocument, fDocument);
		fReplaceTextPresentation= false;
	}		
	
	//---- Viewports	
	
	/**
	 * Initializes all listeners and structures required to set up viewport listeners.
	 */
	private void initializeViewportUpdate() {

		if (fViewportGuard != null)
			return;

		if (fTextWidget != null) {
			
			fViewportGuard= new ViewportGuard();
			fLastTopPixel= -1;

			fTextWidget.addKeyListener(fViewportGuard);
			fTextWidget.addMouseListener(fViewportGuard);

			fScroller= fTextWidget.getVerticalBar();
			if (fScroller != null)
				fScroller.addSelectionListener(fViewportGuard);
		}
	}
	
	/**
	 * Removes all listeners and structures required to set up viewport listeners.
	 */
	private void removeViewPortUpdate() {
		
		if (fTextWidget != null) {
			
			fTextWidget.removeKeyListener(fViewportGuard);
			fTextWidget.removeMouseListener(fViewportGuard);

			if (fScroller != null && !fScroller.isDisposed()) {
				fScroller.removeSelectionListener(fViewportGuard);
				fScroller= null;
			}

			fViewportGuard= null;
		}
	}
	
	/*
	 * @see ITextViewer#addViewportListener
	 */
	public void addViewportListener(IViewportListener listener) {
		
		if (fViewportListeners == null) {
			fViewportListeners= new ArrayList();
			initializeViewportUpdate();
		}
	
		if (!fViewportListeners.contains(listener))
			fViewportListeners.add(listener);
	}
	
	/*
	 * @see ITextViewer#removeViewportListener
	 */
	public void removeViewportListener(IViewportListener listener) {
		if (fViewportListeners != null)
			fViewportListeners.remove(listener);
	}
		
	/**
	 * Checks whether the viewport changed and if so informs all registered 
	 * listeners about the change.
	 *
	 * @param origin describes under which circumstances this method has been called.
	 *
	 * @see IViewportListener
	 */
	protected void updateViewportListeners(int origin) {
		
		if (redraws()) {
			int topPixel= fTextWidget.getTopPixel();
			if (topPixel >= 0 && topPixel != fLastTopPixel) {
				if (fViewportListeners != null) {
					for (int i= 0; i < fViewportListeners.size(); i++) {
						IViewportListener l= (IViewportListener) fViewportListeners.get(i);
						l.viewportChanged(topPixel);
					}
				}
				fLastTopPixel= topPixel;
			}
		}
	}
	
	//---- scrolling and revealing
	
	/*
	 * @see ITextViewer#getTopIndex
	 */
	public int getTopIndex() {
		
		if (fTextWidget != null) {
			
			int top= fTextWidget.getTopIndex();
			
			int offset= getVisibleRegionOffset();
			if (offset > 0) {
				try {
					top += getDocument().getLineOfOffset(offset);
				} catch (BadLocationException x) {
					if (TRACE_ERRORS)
						System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.getTopIndex")); //$NON-NLS-1$
					return -1;
				}
			}
			
			return top;
		}
					
		return -1;
	}
		
	/*
	 * @see ITextViewer#setTopIndex
	 */
	public void setTopIndex(int index) {
		
		if (fTextWidget != null) {
			
			int offset= getVisibleRegionOffset();
			if (offset > 0) {
				try {
					index -= getDocument().getLineOfOffset(offset);
				} catch (BadLocationException x) {
					if (TRACE_ERRORS)
						System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.setTopIndex_1")); //$NON-NLS-1$
					return;
				}
			}
			
			if (index >= 0) {
				
				int lines= getVisibleLinesInViewport();
				if (lines > -1 ) {					
					IDocument d= getVisibleDocument();
					int last= d.getNumberOfLines() - lines;
					if (last > 0 && index  > last)
						index= last;
					
					fTextWidget.setTopIndex(index);
					updateViewportListeners(INTERNAL);
				
				} else
					fTextWidget.setTopIndex(index);
			}
		}
	}
	
	/**
	 * Returns the viewport height in lines. The actual visible lines can be fewer if the
	 * document is shorter than the viewport.
	 *
	 * @return the viewport height in lines
	 */
	protected int getVisibleLinesInViewport() {
		if (fTextWidget != null) {
			Rectangle clArea= fTextWidget.getClientArea();
			if (!clArea.isEmpty())
				return clArea.height / fTextWidget.getLineHeight();
		}
		return -1;
	}
	
	/*
	 * @see ITextViewer#getBottomIndex
	 */
	public int getBottomIndex() {
		
		if (fTextWidget == null)
			return -1;
		
		IRegion r= getVisibleRegion();
		
		try {
			
			IDocument d= getDocument();
			int startLine= d.getLineOfOffset(r.getOffset());
			int endLine= d.getLineOfOffset(r.getOffset()  + r.getLength() - 1);
			int lines= getVisibleLinesInViewport();
			
			if (startLine + lines < endLine)
				return getTopIndex() + lines - 1;
				
			return endLine;
			
		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.getBottomIndex")); //$NON-NLS-1$
		}
		
		return -1;
	}
	
	/*
	 * @see ITextViewer#getTopIndexStartOffset
	 */
	public int getTopIndexStartOffset() {
		
		if (fTextWidget != null) {	
			int top= fTextWidget.getTopIndex();
			try {
				top= getVisibleDocument().getLineOffset(top);
				return top + getVisibleRegionOffset();
			} catch (BadLocationException ex) {
				if (TRACE_ERRORS)
					System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.getTopIndexStartOffset")); //$NON-NLS-1$
			}
		}
		
		return -1;
	}
	
	/*
	 * @see ITextViewer#getBottomIndexEndOffset
	 */
	public int getBottomIndexEndOffset() {
		try {
			
			IRegion line= getDocument().getLineInformation(getBottomIndex());
			int bottomEndOffset= line.getOffset() + line.getLength() - 1;
			
			IRegion region= getVisibleRegion();
			int visibleRegionEndOffset=  region.getOffset() + region.getLength() - 1;
			return visibleRegionEndOffset < bottomEndOffset ? visibleRegionEndOffset : bottomEndOffset;
				
		} catch (BadLocationException ex) {
			if (TRACE_ERRORS)
				System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.getBottomIndexEndOffset")); //$NON-NLS-1$
			return getDocument().getLength() - 1;
		}
	}
	
	/*
	 * @see ITextViewer#revealRange
	 */
	public void revealRange(int start, int length) {
		
		if (fTextWidget == null || !redraws())
			return;
			
		if (length < 0) {
			start += length;
			length= -length;
		}
		
		int end= start + length;

		IDocument document= getVisibleDocument();
		if (document == null)
			return;
			
		Position p= (document instanceof ChildDocument)
			? ((ChildDocument) document).getParentDocumentRange()
			: new Position(0, document.getLength());
			
		if (p.overlapsWith(start, length)) {
				
			if (start < p.getOffset())
				start= p.getOffset();
			start -= p.getOffset();	
				
			int e= p.getOffset() + p.getLength();				
			if (end > e)
				end= e;
			end -= p.getOffset();
				
		} else {
			// http://dev.eclipse.org/bugs/show_bug.cgi?id=15159
			start= start < p.getOffset() ? 0 : p.getLength();
			end= start;
		}
		
		internalRevealRange(start, end);
	}
	
	/**
	 * Reveals the given range of the visible document.
	 *
	 * @param start the start offset of the range
	 * @param end the end offset of the range
	 */
	protected void internalRevealRange(int start, int end) {			
		
		try {
			
			IDocument doc= getVisibleDocument();
			
			int startLine= doc.getLineOfOffset(start);
			int endLine= doc.getLineOfOffset(end);
			
			int top= fTextWidget.getTopIndex();
			if (top > -1) {
				
				// scroll vertically
				
				int lines= getVisibleLinesInViewport();
				int bottom= top + lines;
				
				// two lines at the top and the bottom should always be left
				// if window is smaller than 5 lines, always center position is chosen
				int bufferZone= 2; 
				
				if (startLine >= top + bufferZone 
						&& startLine <= bottom - bufferZone
						&& endLine >= top + bufferZone 
						&& endLine <= bottom - bufferZone) {
						
					// do not scroll at all as it is already visible
					
				} else {
					
					int delta= Math.max(0, lines - (endLine - startLine));
					fTextWidget.setTopIndex(startLine - delta/3);
					updateViewportListeners(INTERNAL);
				}
				
				// scroll horizontally
				
				if (endLine < startLine) {
					endLine += startLine;
					startLine= endLine - startLine;
					endLine -= startLine;
				}
				
				int startPixel= -1;
				int endPixel= -1;
				
				if (endLine > startLine) {
					// reveal the beginning of the range in the start line
					IRegion line= doc.getLineInformation(startLine);
					startPixel= getWidthInPixels(line.getOffset(), start - line.getOffset());
					endPixel= getWidthInPixels(line.getOffset(), line.getLength());
				} else {
					int lineStart= doc.getLineOffset(startLine);
					startPixel= getWidthInPixels(lineStart, start - lineStart);
					endPixel= getWidthInPixels(lineStart, end - lineStart);
				}
				
				int visibleStart= fTextWidget.getHorizontalPixel();
				int visibleEnd= visibleStart + fTextWidget.getClientArea().width;
				
				// scroll only if not yet visible
				if (startPixel < visibleStart || visibleEnd < endPixel) {
					
					// set buffer zone to 10 pixels
					bufferZone= 10;
					
					int newOffset= visibleStart;
					if (startPixel < visibleStart)
						newOffset= startPixel;
					else if (endPixel - startPixel  + bufferZone < visibleEnd - visibleStart)
						newOffset= visibleStart + (endPixel - visibleEnd + bufferZone);
					else
						newOffset= startPixel;
						
					fTextWidget.setHorizontalIndex(newOffset / getAverageCharWidth());
				}
				
			}
		} catch (BadLocationException e) {
			throw new IllegalArgumentException(JFaceTextMessages.getString("TextViewer.error.invalid_range")); //$NON-NLS-1$
		}
	}
	
	/**
	 * Returns the width of the text when being drawed into this viewer's widget.
	 * 
	 * @param the string to messure
	 * @return the width of the presentation of the given string
	 * @deprecated use <code>getWidthInPixels(int, int)</code> instead
	 */
	final protected int getWidthInPixels(String text) {
		GC gc= new GC(fTextWidget);
		gc.setFont(fTextWidget.getFont());
		Point extent= gc.textExtent(text);
		gc.dispose();
		return extent.x;
	}
	
	/**
	 * Returns the width of the representation of a text range in the
	 * visible region of the viewer's document as drawn in this viewer's
	 * widget.
	 * 
	 * @param offset the offset of the text range in the visible region
	 * @param length the length of the text range in the visible region
	 * @return the width of the presentation of the specified text range
	 * @since 2.0
	 */
	final protected int getWidthInPixels(int offset, int length) {		
		
		Point left= fTextWidget.getLocationAtOffset(offset);
		Point right= new Point(left.x, left.y);
		
		int end= offset + length;
		for (int i= offset +1; i <= end; i++) {
			
			Point p= fTextWidget.getLocationAtOffset(i);
			
			if (left.x > p.x)
				left.x= p.x;
								
			if (right.x  < p.x)
				right.x= p.x;				
		}
		
		return  right.x - left.x;
	}
	
	/**
	 * Returns the average character width of this viewer's widget.
	 * 
	 * @return the average character width of this viewer's widget
	 */
	final protected int getAverageCharWidth() {
		GC gc= new GC(fTextWidget);
		gc.setFont(fTextWidget.getFont());
		int increment= gc.getFontMetrics().getAverageCharWidth();
		gc.dispose();
		return increment;
	}
	
	/*
	 * @see Viewer#refresh
	 */
	public void refresh() {
		setDocument(getDocument());
	}
	
	//---- visible range support
	
	/**
	 * Returns the child document manager
	 *
	 * @return the child document manager
	 */
	private ChildDocumentManager getChildDocumentManager() {
		if (fChildDocumentManager == null)
			fChildDocumentManager= new ChildDocumentManager();
		return fChildDocumentManager;
	}
	
	/*
	 * @see org.eclipse.jface.text.ITextViewer#invalidateTextPresentation()
	 */
	public final void invalidateTextPresentation() {
		if (fVisibleDocument != null) {
			fWidgetCommand.event= null;
			fWidgetCommand.start= 0;
			fWidgetCommand.length= fVisibleDocument.getLength();
			fWidgetCommand.text= fVisibleDocument.get();
			updateTextListeners(fWidgetCommand);
		}
	}
	
	public final void invalidateTextPresentation(int offset, int length) {
		if (fVisibleDocument != null) {
			
			IRegion visibleRegion= getVisibleRegion();
			
			int delta= visibleRegion.getOffset() - offset;
			if (delta > 0) {
				offset= visibleRegion.getOffset();
				length -= delta;
			}
			offset -= visibleRegion.getOffset();	
			
			delta= (offset + length) - (visibleRegion.getOffset() + visibleRegion.getLength());
			if (delta > 0)
				length -= delta;
				
			fWidgetCommand.event= null;
			fWidgetCommand.start= offset;
			fWidgetCommand.length= length;
			
			try {
				fWidgetCommand.text= fVisibleDocument.get(offset, length);
				updateTextListeners(fWidgetCommand);
			} catch (BadLocationException x) {
				// can not happen because of previous checking
			}
		}
	}
	
	/**
	 * Initializes the text widget with the visual document and
	 * invalidates the overall presentation.
	 */
	private void initializeWidgetContents() {
		
		if (fTextWidget != null && fVisibleDocument != null) {
		
			// set widget content
			if (fDocumentAdapter == null)
				fDocumentAdapter= createDocumentAdapter();
				
			fDocumentAdapter.setDocument(fVisibleDocument);
			fTextWidget.setContent(fDocumentAdapter);
								
			// invalidate presentation				
			invalidateTextPresentation();
		}
	}
	
	/**
	 * Sets this viewer's visible document. The visible document represents the 
	 * visible region of the viewer's input document.
	 *
	 * @param document the visible document
	 */
	private void setVisibleDocument(IDocument document) {
		
		if (fVisibleDocument != null && fDocumentListener != null)
			fVisibleDocument.removeDocumentListener(fDocumentListener);
		
		fVisibleDocument= document;
		
		initializeWidgetContents();
		resetPlugins();
		
		if (fVisibleDocument != null && fDocumentListener != null)
			fVisibleDocument.addDocumentListener(fDocumentListener);
	}
	
	/**
	 * Returns the viewer's visible document.
	 *
	 * @return the viewer's visible document
	 */
	protected IDocument getVisibleDocument() {
		return fVisibleDocument;
	}
	
	/**
	 * Returns the offset of the visible region.
	 *
	 * @return the offset of the visible region
	 */
	protected int getVisibleRegionOffset() {
		
		IDocument document= getVisibleDocument();
		if (document instanceof ChildDocument) {
			ChildDocument cdoc= (ChildDocument) document;
			return cdoc.getParentDocumentRange().getOffset();
		}
		
		return 0;
	}
	
	/*
	 * @see ITextViewer#getVisibleRegion
	 */
	public IRegion getVisibleRegion() {
		
		IDocument document= getVisibleDocument();
		if (document instanceof ChildDocument) {
			Position p= ((ChildDocument) document).getParentDocumentRange();
			return new Region(p.getOffset(), p.getLength());
		}		
		
		return new Region(0, document == null ? 0 : document.getLength());
	}
		
	/*
	 * @see ITextViewer#setVisibleRegion
	 */
	public void setVisibleRegion(int start, int length) {
		
		IRegion region= getVisibleRegion();
		if (start == region.getOffset() && length == region.getLength()) {
			// nothing to change
			return;
		}
		
		ChildDocument child= null;
		IDocument parent= getVisibleDocument();
		
		if (parent instanceof ChildDocument) {
			child= (ChildDocument) parent;
			parent= child.getParentDocument();
		}
		
		try {
			
			int line= parent.getLineOfOffset(start);
			int offset= parent.getLineOffset(line);
			length += (start - offset);
			
			if (child != null) {
				child.setParentDocumentRange(offset, length);
			} else {
				child= getChildDocumentManager().createChildDocument(parent, offset, length);
			}
			
			setVisibleDocument(child);
							
		} catch (BadLocationException x) {
			throw new IllegalArgumentException(JFaceTextMessages.getString("TextViewer.error.invalid_visible_region_2")); //$NON-NLS-1$
		}
	}
				
	/*
	 * @see ITextViewer#resetVisibleRegion
	 */
	public void resetVisibleRegion() {
		IDocument document= getVisibleDocument();
		if (document instanceof ChildDocument) {			
			ChildDocument child = (ChildDocument) document;
			setVisibleDocument(child.getParentDocument());
			getChildDocumentManager().freeChildDocument(child);
		}
	}
	
	/*
	 * @see ITextViewer#overlapsWithVisibleRegion
	 */
	public boolean overlapsWithVisibleRegion(int start, int length) {
		IDocument document= getVisibleDocument();
		if (document instanceof ChildDocument) {
			ChildDocument cdoc= (ChildDocument) document;
			return cdoc.getParentDocumentRange().overlapsWith(start, length);
		} else if (document != null) {
			int size= document.getLength();
			return (start >= 0 && length >= 0 && start + length <= size);
		}
		return false;
	}
		
	
	
	//--------------------------------------
	
	/*
	 * @see ITextViewer#setTextDoubleClickStrategy
	 */
	public void setTextDoubleClickStrategy(ITextDoubleClickStrategy strategy, String contentType) {		
		
		if (strategy != null) {
			if (fDoubleClickStrategies == null)
				fDoubleClickStrategies= new HashMap();
			fDoubleClickStrategies.put(contentType, strategy);
		} else if (fDoubleClickStrategies != null)
			fDoubleClickStrategies.remove(contentType);
	}
	
	/**
	 * Selects from the given map the one which is registered under
	 * the content type of the partition in which the given offset is located.
	 *
	 * @param plugins the map from which to choose
	 * @param offset the offset for which to find the plugin
	 * @return the plugin registered under the offset's content type 
	 */
	protected Object selectContentTypePlugin(int offset, Map plugins) {
		try {
			return selectContentTypePlugin(getDocument().getContentType(offset), plugins);
		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.selectContentTypePlugin")); //$NON-NLS-1$
		}
		return null;
	}
	
	/**
	 * Selects from the given <code>plugins</code> this one which is registered for
	 * the given content <code>type</code>.
	 */
	private Object selectContentTypePlugin(String type, Map plugins) {
		
		if (plugins == null)
			return null;
		
		return plugins.get(type);
	}
	
	/**
	 * Hook called on receipt of a <code>VerifyEvent</code>. The event has
	 * been translated into a <code>DocumentCommand</code> which can now be
	 * manipulated by interested parties. By default, the hook forwards the command
	 * to the installed <code>IAutoIndentStrategy</code>.
	 *
	 * @param command the document command representing the verify event
	 */
	protected void customizeDocumentCommand(DocumentCommand command) {
		if (!fIgnoreAutoIndent) {
			IAutoIndentStrategy s= (IAutoIndentStrategy) selectContentTypePlugin(command.offset, fAutoIndentStrategies);
			if (s != null)
				s.customizeDocumentCommand(getDocument(), command);
		}
		fIgnoreAutoIndent= false;
	}
	
	/**
	 * @see VerifyListener#verifyText
	 */
	protected void handleVerifyEvent(VerifyEvent e) {
				
		if (fEventConsumer != null) {
			fEventConsumer.processEvent(e);
			if (!e.doit)
				return;
		}
		
		int offset= getVisibleRegionOffset();
		fDocumentCommand.setEvent(e, offset);
		customizeDocumentCommand(fDocumentCommand);
		if (!fDocumentCommand.fillEvent(e, offset)) {
			try {
				fVerifyListener.forward(false);
				getDocument().replace(fDocumentCommand.offset, fDocumentCommand.length, fDocumentCommand.text);
				if (fTextWidget != null) {
					int caretOffset= fDocumentCommand.offset + (fDocumentCommand.text == null ? 0 : fDocumentCommand.text.length()) - offset;
					fTextWidget.setCaretOffset(caretOffset);
				}
			} catch (BadLocationException x) {
				if (TRACE_ERRORS)
					System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.verifyText")); //$NON-NLS-1$
			} finally {
				fVerifyListener.forward(true);
			}
		}	
	}
	
	//---- text manipulation

	/**
	 * Returns whether the marked region of this viewer is empty.
	 * 
	 * @return <code>true</code> if the marked region of this viewer is empty, otherwise <code>false</code>
	 */
	private boolean isMarkedRegionEmpty() {

		if (fTextWidget == null)
			return true;

		IRegion region= getVisibleRegion();
		int offset= region.getOffset();
		int length= region.getLength();

		return
			fMarkPosition == null ||
			fMarkPosition.isDeleted() ||
			fMarkPosition.offset < offset ||
			fMarkPosition.offset > offset + length;
	}

	/*
	 * @see ITextViewer#canDoOperation
	 */
	public boolean canDoOperation(int operation) {
		
		if (fTextWidget == null || !redraws())
			return false;

		switch (operation) {
			case CUT:
				return isEditable() &&(fTextWidget.getSelectionCount() > 0 || !isMarkedRegionEmpty());
			case COPY:				
				return fTextWidget.getSelectionCount() > 0 || !isMarkedRegionEmpty();
			case DELETE:
			case PASTE:
				return isEditable();
			case SELECT_ALL:
				return true;
			case SHIFT_RIGHT:
			case SHIFT_LEFT:
				return isEditable() && fIndentChars != null && areMultipleLinesSelected();
			case PREFIX:
			case STRIP_PREFIX:
				return isEditable() && fDefaultPrefixChars != null;
			case UNDO:
				return fUndoManager != null && fUndoManager.undoable();
			case REDO:
				return fUndoManager != null && fUndoManager.redoable();
			case PRINT:
				return isPrintable();
		}
		
		return false;
	}
	
	/*
	 * @see ITextViewer#doOperation
	 */
	public void doOperation(int operation) {
		
		if (fTextWidget == null || !redraws())
			return;

		switch (operation) {

			case UNDO:
				if (fUndoManager != null) {
					fIgnoreAutoIndent= true;
					fUndoManager.undo();
				}
				break;
			case REDO:
				if (fUndoManager != null) {
					fIgnoreAutoIndent= true;
					fUndoManager.redo();
				}
				break;
			case CUT:
				if (fTextWidget.getSelectionCount() == 0)
					copyMarkedRegion(true);
				else
					fTextWidget.cut();
				break;
			case COPY:
				if (fTextWidget.getSelectionCount() == 0)
					copyMarkedRegion(false);
				else
					fTextWidget.copy();
				break;
			case PASTE:
				fIgnoreAutoIndent= true;
				fTextWidget.paste();
				break;
			case DELETE:
				deleteText();
				break;
			case SELECT_ALL:
				setSelectedRange(getVisibleRegionOffset(), getVisibleDocument().getLength());
				break;
			case SHIFT_RIGHT:
				shift(false, true, false);
				break;
			case SHIFT_LEFT:
				shift(false, false, false);
				break;
			case PREFIX:
				shift(true, true, true);
				break;
			case STRIP_PREFIX:
				shift(true, false, true);
				break;
			case PRINT:
				print();
				break;
		}
	}
	
	/*
	 * @see ITextOperationTargetExtension#enableOperation(int, boolean)
	 * @since 2.0
	 */
	public void enableOperation(int operation, boolean enable) {
		/* 
		 * No-op by default.
		 * Will be changed to regularily disable the known operations.
		 */
	}
	
	/**
	 * Copies/cuts the marked region.
	 * 
	 * @param delete <code>true</code> if the region should be deleted rather than copied.
	 * @since 2.0
	 */
	private void copyMarkedRegion(boolean delete) {
		
		if (fTextWidget == null)
			return;

		IRegion region= getVisibleRegion();
		int offset= region.getOffset();
		int length= region.getLength();

		if (fMarkPosition == null || fMarkPosition.isDeleted() ||
			fMarkPosition.offset < offset || fMarkPosition.offset > offset + length)
			return;
					
		int markOffset= fMarkPosition.offset - offset;
		
		Point selection= fTextWidget.getSelection();		
		if (selection.x <= markOffset)
			fTextWidget.setSelection(selection.x, markOffset);
		else
			fTextWidget.setSelection(markOffset, selection.x);

		if (delete) {
			fTextWidget.cut();			
		} else {
			fTextWidget.copy();
			fTextWidget.setSelection(selection.x); // restore old cursor position
		}
	}
	
	/**
	 * Deletes the current selection. If the selection has the length 0
	 * the selection is automatically extended to the right - either by 1
	 * or by the length of line delimiter if at the end of a line.
	 * 
	 * @deprecated use <code>StyledText.invokeAction</code> instead
	 */
	protected void deleteText() {
		fTextWidget.invokeAction(ST.DELETE_NEXT);
	}
		
	/**
	 * A block is selected if the character preceding the start of the 
	 * selection is a new line character.
	 *
	 * @return <code>true</code> if a block is selected
	 */
	protected boolean isBlockSelected() {
		
		Point s= getSelectedRange();
		if (s.y == 0)
			return false;
		
		try {
			
			IDocument document= getDocument();
			int line= document.getLineOfOffset(s.x);
			int start= document.getLineOffset(line);
			return (s.x == start);
			
		} catch (BadLocationException x) {
		}
		
		return false;
	}
	
	/**
	 * Returns <code>true</code> if one line is completely selected or if multiple lines are selected.
	 * Being completely selected means that all characters except the new line characters are 
	 * selected.
	 * 
	 * @return <code>true</code> if one or multiple lines are selected
	 * @since 2.0
	 */
	protected boolean areMultipleLinesSelected() {
		Point s= getSelectedRange();
		if (s.y == 0)
			return false;
			
		try {
			
			IDocument document= getDocument();
			int startLine= document.getLineOfOffset(s.x);
			int endLine= document.getLineOfOffset(s.x + s.y);
			IRegion line= document.getLineInformation(startLine);
			return startLine != endLine || (s.x == line.getOffset() && s.y == line.getLength());
		
		} catch (BadLocationException x) {
		}
		
		return false;
	}
	
	/**
	 * Returns the index of the first line whose start offset is in the given text range.
	 *
	 * @param region the text range in characters where to find the line
	 * @return the first line whose start index is in the given range, -1 if there is no such line
	 */
	private int getFirstCompleteLineOfRegion(IRegion region) {
		
		try {
			
			IDocument d= getDocument();
			
			int startLine= d.getLineOfOffset(region.getOffset());
			
			int offset= d.getLineOffset(startLine);
			if (offset >= region.getOffset())
				return startLine;
				
			offset= d.getLineOffset(startLine + 1);
			return (offset > region.getOffset() + region.getLength() ? -1 : startLine + 1);
		
		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.getFirstCompleteLineOfRegion")); //$NON-NLS-1$
		}
		
		return -1;
	}
	
	
	/**
	 * Creates a region describing the text block (something that starts at
	 * the beginning of a line) completely containing the current selection.
	 * 
	 * @param selection the selection to use
	 * @return the region describing the text block comprising the given selection
	 * @since 2.0
	 */
	private IRegion getTextBlockFromSelection(Point selection) {
				
		try {
			IDocument document= getDocument();
			IRegion line= document.getLineInformationOfOffset(selection.x);
			int length= selection.y == 0 ? line.getLength() : selection.y + (selection.x - line.getOffset());
			return new Region(line.getOffset(), length);
			
		} catch (BadLocationException x) {
		}
		
		return null;		
	}

	/**
	 * Shifts a text block to the right or left using the specified set of prefix characters.
	 * The prefixes must start at the beginnig of the line.
	 *
	 * @param useDefaultPrefixes says whether the configured default or indent prefixes should be used
	 * @param right says whether to shift to the right or the left
	 * 
	 * @deprecated use shift(boolean, boolean, boolean) instead
	 */
	protected void shift(boolean useDefaultPrefixes, boolean right) {
		shift(useDefaultPrefixes, right, false);
	}
		
	/**
	 * Shifts a text block to the right or left using the specified set of prefix characters.
	 * If white space should be ignored the prefix characters must not be at the beginning of
	 * the line when shifting to the left. There may be whitespace in front of the prefixes.
	 *
	 * @param useDefaultPrefixes says whether the configured default or indent prefixes should be used
	 * @param right says whether to shift to the right or the left
	 * @param ignoreWhitespace says whether whitepsace in front of prefixes is allowed
	 * @since 2.0
	 */
	protected void shift(boolean useDefaultPrefixes, boolean right, boolean ignoreWhitespace) {
		
		if (fUndoManager != null)
			fUndoManager.beginCompoundChange();
			
		setRedraw(false);
		startSequentialRewriteMode(true);

		IDocument d= getDocument();
		IDocumentPartitioner partitioner= null;
		
		try {
			
			Point selection= getSelectedRange();
			IRegion block= getTextBlockFromSelection(selection);
			ITypedRegion[] regions= d.computePartitioning(block.getOffset(), block.getLength());

			int lineCount= 0;			
			int[] lines= new int[regions.length * 2]; // [startline, endline, startline, endline, ...]
			for (int i= 0, j= 0; i < regions.length; i++, j+= 2) {
				// start line of region
				lines[j]= getFirstCompleteLineOfRegion(regions[i]);
				// end line of region
				int offset= regions[i].getOffset() + regions[i].getLength() - 1;
				lines[j + 1]= (lines[j] == -1 ? -1 : d.getLineOfOffset(offset));
				lineCount += lines[j + 1] - lines[j] + 1;
			}
			
			if (lineCount >= 20) {
				partitioner= d.getDocumentPartitioner();
				if (partitioner != null) {
					partitioner.disconnect();
					d.setDocumentPartitioner(null);
				}
			}
			
			// Remember the selection range.
			IPositionUpdater positionUpdater= new ShiftPositionUpdater(SHIFTING);
			Position rememberedSelection= new Position(selection.x, selection.y);
			d.addPositionCategory(SHIFTING);
			d.addPositionUpdater(positionUpdater);
			try {
				d.addPosition(SHIFTING, rememberedSelection);
			} catch (BadPositionCategoryException ex) {
				// should not happen
			}
									
			// Perform the shift operation.
			Map map= (useDefaultPrefixes ? fDefaultPrefixChars : fIndentChars);
			for (int i= 0, j= 0; i < regions.length; i++, j += 2) {
				String[] prefixes= (String[]) selectContentTypePlugin(regions[i].getType(), map);
				if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0) {
					if (right)
						shiftRight(lines[j], lines[j + 1], prefixes[0]);
					else
						shiftLeft(lines[j], lines[j + 1], prefixes, ignoreWhitespace);
				}
			}
			
			// Restore the selection.
			setSelectedRange(rememberedSelection.getOffset(), rememberedSelection.getLength());
						
			try {
				d.removePositionUpdater(positionUpdater);
				d.removePositionCategory(SHIFTING);			
			} catch (BadPositionCategoryException ex) {
				// should not happen
			}
						
		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.shift_1")); //$NON-NLS-1$
		
		} finally {

			if (partitioner != null) {
				partitioner.connect(d);
				d.setDocumentPartitioner(partitioner);
			}
			
			stopSequentialRewriteMode();
			setRedraw(true);
			
			if (fUndoManager != null)
				fUndoManager.endCompoundChange();
		}
	}
	
	/**
	 * Shifts the specified lines to the right inserting the given prefix
	 * at the beginning of each line
	 *
	 * @param prefix the prefix to be inserted
	 * @param startLine the first line to shift
	 * @param endLine the last line to shift
	 * @since 2.0
	 */
	private void shiftRight(int startLine, int endLine, String prefix) {
		
		try {
						
			IDocument d= getDocument();
			while (startLine <= endLine) {
				d.replace(d.getLineOffset(startLine++), 0, prefix);
			}

		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println("TextViewer.shiftRight: BadLocationException"); //$NON-NLS-1$
		}
	}
	
	/**
	 * Shifts the specified lines to the right or to the left. On shifting to the right
	 * it insert <code>prefixes[0]</code> at the beginning of each line. On shifting to the
	 * left it tests whether each of the specified lines starts with one of the specified 
	 * prefixes and if so, removes the prefix.
	 *
	 * @param prefixes the prefixes to be used for shifting
	 * @param right if <code>true</code> shift to the right otherwise to the left
	 * @param startLine the first line to shift
	 * @param endLine the last line to shift
	 * @since 2.0
	 */
	private void shiftLeft(int startLine, int endLine, String[] prefixes, boolean ignoreWhitespace) {
		
		IDocument d= getDocument();
		
		try {
						
			IRegion[] occurrences= new IRegion[endLine - startLine + 1];
			
			// find all the first occurrences of prefix in the given lines
			for (int i= 0; i < occurrences.length; i++) {
				
				IRegion line= d.getLineInformation(startLine + i);
				String text= d.get(line.getOffset(), line.getLength());
				
				int index= -1;
				int[] found= TextUtilities.indexOf(prefixes, text, 0);
				if (found[0] != -1) {
					if (ignoreWhitespace) {
						String s= d.get(line.getOffset(), found[0]);
						s= s.trim();
						if (s.length() == 0)
							index= line.getOffset() + found[0];
					} else if (found[0] == 0)
						index= line.getOffset();
				}
				
				if (index > -1) {
					// remember where prefix is in line, so that it can be removed
					int length= prefixes[found[1]].length();
					if (length == 0 && !ignoreWhitespace && line.getLength() > 0) {
						// found a non-empty line which cannot be shifted
						return;
					} else 
						occurrences[i]= new Region(index, length);
				} else {
					// found a line which cannot be shifted
					return;
				}
			}
			
			// ok - change the document
			int decrement= 0;
			for (int i= 0; i < occurrences.length; i++) {
				IRegion r= occurrences[i];
				d.replace(r.getOffset() - decrement, r.getLength(), ""); //$NON-NLS-1$
				decrement += r.getLength();
			}
			
		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println("TextViewer.shiftLeft: BadLocationException"); //$NON-NLS-1$
		}
	}
	
	/**
	 * Returns whether the shown text can be printed.
	 *
	 * @return the viewer's printable mode
	 */
	protected boolean isPrintable() {
		/*
		 * 1GK7Q10: ITPUI:WIN98 - internal error after invoking print at editor view
		 * Changed from returning true to testing the length of the printer queue
		 */
		PrinterData[] printerList= Printer.getPrinterList();
		return (printerList != null && printerList.length > 0);
	}
	
	/**
	 * Brings up a print dialog and calls <code>printContents(Printer)</code> which 
	 * performs the actual print.
	 *
	 * Subclasses may override.
	 */
	protected void print() {
		
		final PrintDialog dialog= new PrintDialog(fTextWidget.getShell(), SWT.PRIMARY_MODAL);
		final PrinterData data= dialog.open();
		
		if (data != null) {
			
			final Printer printer= new Printer(data);
			final Runnable styledTextPrinter= fTextWidget.print(printer);
	
			Thread printingThread= new Thread("Printing") { //$NON-NLS-1$
				public void run() {
					styledTextPrinter.run();
					printer.dispose();
				}
			};
			printingThread.start();
		}
    }
	
		
	//------ find support
	
	/**
	 * @see IFindReplaceTarget#canPerformFind
	 */
	protected boolean canPerformFind() {
		IDocument d= getVisibleDocument();
		return (fTextWidget != null && d != null && d.getLength() > 0);
	}
	
	/**
	 * @see IFindReplaceTarget#findAndSelect(int, String, boolean, boolean, boolean)
	 */
	protected int findAndSelect(int startPosition, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord) {
		if (fTextWidget == null)
			return -1;
			
		try {
			int offset= (startPosition == -1 ? startPosition : startPosition - getVisibleRegionOffset());
			int pos= getVisibleDocument().search(offset, findString, forwardSearch, caseSensitive, wholeWord);
			if (pos > -1) {
				int length= findString.length();
				if (redraws()) {
					fTextWidget.setSelectionRange(pos, length);
					internalRevealRange(pos, pos + length);
					selectionChanged(pos, length);
				} else {
					setSelectedRange(pos + getVisibleRegionOffset(), length);
				}
			}
			return pos + getVisibleRegionOffset();
		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.findAndSelect")); //$NON-NLS-1$
		}
		
		return -1;
	}
	
	/**
	 * @see IFindReplaceTarget#findAndSelect(int, String, boolean, boolean, boolean)
	 * @since 2.0
	 */
	private int findAndSelectInRange(int startPosition, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, int rangeOffset, int rangeLength) {
		if (fTextWidget == null)
			return -1;
			
		try {
			int offset;
			if (forwardSearch && (startPosition == -1 || startPosition < rangeOffset)) {
				offset= rangeOffset;
			} else if (!forwardSearch && (startPosition == -1 || startPosition > rangeOffset + rangeLength)) {
				offset= rangeOffset + rangeLength;
			} else {
				offset= startPosition;
			}
			offset -= getVisibleRegionOffset();
			
			int pos= getVisibleDocument().search(offset, findString, forwardSearch, caseSensitive, wholeWord);

			int length =  findString.length();
			if (pos != -1 && (pos + getVisibleRegionOffset() < rangeOffset || pos + getVisibleRegionOffset() + length > rangeOffset + rangeLength))
				pos= -1;

			if (pos > -1) {
				if (redraws()) {
					fTextWidget.setSelectionRange(pos, length);
					internalRevealRange(pos, pos + length);
					selectionChanged(pos, length);
				} else {
					setSelectedRange(pos + getVisibleRegionOffset(), length);
				}
			}
			return pos + getVisibleRegionOffset();
		} catch (BadLocationException x) {
			if (TRACE_ERRORS)
				System.out.println(JFaceTextMessages.getString("TextViewer.error.bad_location.findAndSelect")); //$NON-NLS-1$
		}
		
		return -1;
	}	
	
	//---------- text presentation support
	
	/*
	 * @see ITextViewer#setTextColor
	 */
	public void setTextColor(Color color) {
		if (color != null)
			setTextColor(color, 0, getDocument().getLength(), true);
	}
	
	/*
	 * @see ITextViewer#setTextColor 	 
	 */
	public void setTextColor(Color color, int start, int length, boolean controlRedraw) {	
		
		if (fTextWidget != null) {
									
			if (controlRedraw)
				fTextWidget.setRedraw(false); 
			
			StyleRange s= new StyleRange();
			s.foreground= color;
			s.start= start;
			s.length= length;
			
			fTextWidget.setStyleRange(s);
			
			if (controlRedraw)
				fTextWidget.setRedraw(true);
		}
	}
	
	/**
	 * Adds the given presentation to the viewer's style information.
	 *
	 * @param presentation the presentation to be added
	 */
	private void addPresentation(TextPresentation presentation) {
		
		StyleRange range= presentation.getDefaultStyleRange();
		if (range != null) {
			
			fTextWidget.setStyleRange(range);
			Iterator e= presentation.getNonDefaultStyleRangeIterator();
			while (e.hasNext()) {
				range= (StyleRange) e.next();
				fTextWidget.setStyleRange(range);
			}
		
		} else {
			
			IRegion coverage= presentation.getCoverage();
			if (coverage != null) {
				Iterator e= presentation.getAllStyleRangeIterator();
				StyleRange[] ranges= new StyleRange[presentation.getDenumerableRanges()];
				for (int i= 0; i < ranges.length; i++)
					ranges[i]= (StyleRange) e.next();
					
				fTextWidget.replaceStyleRanges(coverage.getOffset(), coverage.getLength(), ranges);
			}
		}
	}
	
	/**
	 * Returns the visible region if it is not equal to the whole document.
	 * Otherwise returns <code>null</code>.
	 *
	 * @return the viewer's visible region if smaller than input document, otherwise <code>null</code>
	 */
	protected IRegion internalGetVisibleRegion() {
		
		IDocument document= getVisibleDocument();
		if (document instanceof ChildDocument) {
			Position p= ((ChildDocument) document).getParentDocumentRange();
			return new Region(p.getOffset(), p.getLength());
		}		
		
		return null;
	}
	
	/*
	 * @see ITextViewer#changeTextPresentation
	 */
	public void changeTextPresentation(TextPresentation presentation, boolean controlRedraw) {
				
		if (presentation == null)
			return;
			
		presentation.setResultWindow(internalGetVisibleRegion());
		if (presentation.isEmpty() || fTextWidget == null)
			return;
					
		if (controlRedraw)
			fTextWidget.setRedraw(false);
		
		if (fReplaceTextPresentation)
			TextPresentation.applyTextPresentation(presentation, fTextWidget);
		else
			addPresentation(presentation);
		
		if (controlRedraw)
			fTextWidget.setRedraw(true);
	}

	/*
	 * @see ITextViewer#getFindReplaceTarget()
	 */
	public IFindReplaceTarget getFindReplaceTarget() {
		if (fFindReplaceTarget == null)
			fFindReplaceTarget= new FindReplaceTarget();
		return fFindReplaceTarget;
	}

	/*
	 * @see ITextViewer#getTextOperationTarget()
	 */
	public ITextOperationTarget getTextOperationTarget() {
		return this;
	}

	/*
	 * @see ITextViewerExtension#appendVerifyKeyListener(VerifyKeyListener)
	 * @since 2.0
	 */
	public void appendVerifyKeyListener(VerifyKeyListener listener) {
		int index= fVerifyKeyListenersManager.numberOfListeners();
		fVerifyKeyListenersManager.insertListener(listener, index);
	}
	
	/*
	 * @see ITextViewerExtension#prependVerifyKeyListener(VerifyKeyListener)
	 * @since 2.0
	 */
	public void prependVerifyKeyListener(VerifyKeyListener listener) {
		fVerifyKeyListenersManager.insertListener(listener, 0);
		
	}
	
	/*
	 * @see ITextViewerExtension#removeVerifyKeyListener(VerifyKeyListener)
	 * @since 2.0
	 */
	public void removeVerifyKeyListener(VerifyKeyListener listener) {
		fVerifyKeyListenersManager.removeListener(listener);
	}

	/*
	 * @see ITextViewerExtension#getMark()
	 * @since 2.0
	 */
	public int getMark() {
		return fMarkPosition == null || fMarkPosition.isDeleted()
			? -1
			: fMarkPosition.getOffset();
	}

	/*
	 * @see ITextViewerExtension#setMark(int)
	 * @since 2.0
	 */
	public void setMark(int offset) {

		// clear
		if (offset == -1) {
			if (fMarkPosition != null && !fMarkPosition.isDeleted()) {

				IDocument document= getDocument();
				if (document != null)
					document.removePosition(fMarkPosition);
			}			

			fMarkPosition= null;

			markChanged(-1, 0);

		// set
		} else {
			if (fMarkPosition == null) {

				IDocument document= getDocument();
				if (document == null)
					return;			

				if (offset < 0 || offset > document.getLength())
					return;

				try {	
					Position position= new Position(offset);			
					document.addPosition(MARK_POSITION_CATEGORY, position);
					fMarkPosition= position;

				} catch (BadLocationException e) {
					return;
				} catch (BadPositionCategoryException e) {
					return;
				}
		
			} else {

				IDocument document= getDocument();
				if (document == null) {
					fMarkPosition= null;
					return;			
				}				
				
				if (offset < 0 || offset > document.getLength())
					return;

				fMarkPosition.setOffset(offset);
				fMarkPosition.undelete();
			}

			markChanged(fMarkPosition.offset - getVisibleRegionOffset(), 0);
		}		
	}

	/*
	 * @see Viewer#inputChanged(Object, Object)
	 * @since 2.0
	 */
	protected void inputChanged(Object newInput, Object oldInput) {

		IDocument oldDocument= (IDocument) oldInput;
		if (oldDocument != null) {
			if (fMarkPosition != null && !fMarkPosition.isDeleted())
				oldDocument.removePosition(fMarkPosition);

			try {
				oldDocument.removePositionUpdater(fMarkPositionUpdater);
				oldDocument.removePositionCategory(MARK_POSITION_CATEGORY);
	
			} catch (BadPositionCategoryException e) {
			}
		}

		fMarkPosition= null;

		super.inputChanged(newInput, oldInput);

		IDocument newDocument= (IDocument) newInput;
		if (newDocument != null) {
			newDocument.addPositionCategory(MARK_POSITION_CATEGORY);
			newDocument.addPositionUpdater(fMarkPositionUpdater);			
		}
	}
	
	/**
	 * Informs all text listeners about the change of the viewer's redraw state.
	 * @since 2.0
	 */
	private void fireRedrawChanged() {
		fWidgetCommand.start= 0;
		fWidgetCommand.length= 0;
		fWidgetCommand.text= null;
		fWidgetCommand.event= null;
		updateTextListeners(fWidgetCommand);
	}
	
	/**
	 * Enables the redrawing of this text viewer. Subclasses may extend.
	 * @since 2.0
	 */
	protected void enabledRedrawing() {
		if (fDocumentAdapter instanceof IDocumentAdapterExtension) {
			IDocumentAdapterExtension extension= (IDocumentAdapterExtension) fDocumentAdapter;
			StyledText textWidget= getTextWidget();
			if (textWidget != null && !textWidget.isDisposed()) {
				int topPixel= textWidget.getTopPixel();	
				extension.resumeForwardingDocumentChanges();
				if (topPixel > -1) {
					try {
						textWidget.setTopPixel(topPixel);
					} catch (IllegalArgumentException x) {
						// changes don't allow for the previous top pixel
					}
				}
			}
		}
		
		setSelectedRange(fDocumentSelection.x, fDocumentSelection.y);
		revealRange(fDocumentSelection.x, fDocumentSelection.y);
		
		if (fTextWidget != null && !fTextWidget.isDisposed())
			fTextWidget.setRedraw(true);
			
		fireRedrawChanged();
	}
	
	/**
	 * Disables the redrawing of this text viewer. Subclasses may extend.
	 * @since 2.0
	 */
	protected void disableRedrawing() {
		
		fDocumentSelection= getSelectedRange();
		
		if (fDocumentAdapter instanceof IDocumentAdapterExtension) {
			IDocumentAdapterExtension extension= (IDocumentAdapterExtension) fDocumentAdapter;
			extension.stopForwardingDocumentChanges();
		}
		
		if (fTextWidget != null && !fTextWidget.isDisposed())
			fTextWidget.setRedraw(false);
			
		fireRedrawChanged();
	}
	
	/*
	 * @see ITextViewerExtension#setRedraw(boolean)
	 * @since 2.0
	 */
	public final void setRedraw(boolean redraw) {
		if (!redraw) {
			if (fRedrawCounter == 0)
				disableRedrawing();
			++ fRedrawCounter;
		} else {
			-- fRedrawCounter;
			if (fRedrawCounter == 0)
				enabledRedrawing();
		}
	}
	
	/**
	 * Returns whether this viewer redraws itself.
	 * 
	 * @return <code>true</code> if this viewer redraws itself
	 * @since 2.0
	 */
	protected final boolean redraws() {
		return fRedrawCounter <= 0;
	}
	
	/**
	 * Starts  the sequential rewrite mode of the viewer's document.
	 * @since 2.0
	 */
	protected final void startSequentialRewriteMode(boolean normalized) {
		IDocument document= getDocument();
		if (document instanceof IDocumentExtension) {
			IDocumentExtension extension= (IDocumentExtension) document;
			extension.startSequentialRewrite(normalized);
		}
	}
	
	/**
	 * Sets the sequential rewrite mode of the viewer's document.
	 * @since 2.0
	 */
	protected final void stopSequentialRewriteMode() {
		IDocument document= getDocument();
		if (document instanceof IDocumentExtension) {
			IDocumentExtension extension= (IDocumentExtension) document;
			extension.stopSequentialRewrite();
		}
	}
	
	/*
	 * @see org.eclipse.jface.text.ITextViewerExtension#getRewriteTarget()
	 * @since 2.0
	 */
	public IRewriteTarget getRewriteTarget() {
		if (fRewriteTarget == null)
			fRewriteTarget= new RewriteTarget();
		return fRewriteTarget;
	}
}

Back to the top