summaryrefslogtreecommitdiff
path: root/src/static/js/ace2_inner.js
blob: 4eaf041ddf4e7b21f1a6784823e5a6925dd5d1db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
/**
 * This code is mostly from the old Etherpad. Please help us to comment this code. 
 * This helps other people to understand this code better and helps them to improve it.
 * TL;DR COMMENTS ON THIS FILE ARE HIGHLY APPRECIATED
 */

/**
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var editor, _, $, jQuery, plugins, Ace2Common;

Ace2Common = require('./ace2_common');

plugins = require('ep_etherpad-lite/static/js/pluginfw/client_plugins');
$ = jQuery = require('./rjquery').$;
_ = require("./underscore");

var isNodeText = Ace2Common.isNodeText,
  browser = Ace2Common.browser,
  getAssoc = Ace2Common.getAssoc,
  setAssoc = Ace2Common.setAssoc,
  isTextNode = Ace2Common.isTextNode,
  binarySearchInfinite = Ace2Common.binarySearchInfinite,
  htmlPrettyEscape = Ace2Common.htmlPrettyEscape,
  noop = Ace2Common.noop;
  var hooks = require('./pluginfw/hooks');
  

function Ace2Inner(){
  
  var makeChangesetTracker = require('./changesettracker').makeChangesetTracker;
  var colorutils = require('./colorutils').colorutils;
  var makeContentCollector = require('./contentcollector').makeContentCollector;
  var makeCSSManager = require('./cssmanager').makeCSSManager;
  var domline = require('./domline').domline;
  var AttribPool = require('./AttributePool');
  var Changeset = require('./Changeset');
  var ChangesetUtils = require('./ChangesetUtils');
  var linestylefilter = require('./linestylefilter').linestylefilter;
  var SkipList = require('./skiplist');
  var undoModule = require('./undomodule').undoModule;
  var makeVirtualLineView = require('./virtual_lines').makeVirtualLineView;
  var AttributeManager = require('./AttributeManager');
  
  var DEBUG = false; //$$ build script replaces the string "var DEBUG=true;//$$" with "var DEBUG=false;"
  // changed to false 
  var isSetUp = false;

  var THE_TAB = '    '; //4
  var MAX_LIST_LEVEL = 8;

  var LINE_NUMBER_PADDING_RIGHT = 4;
  var LINE_NUMBER_PADDING_LEFT = 4;
  var MIN_LINEDIV_WIDTH = 20;
  var EDIT_BODY_PADDING_TOP = 8;
  var EDIT_BODY_PADDING_LEFT = 8;

  var caughtErrors = [];

  var thisAuthor = '';

  var disposed = false;
  var editorInfo = parent.editorInfo;

  var iframe = window.frameElement;
  var outerWin = iframe.ace_outerWin;
  iframe.ace_outerWin = null; // prevent IE 6 memory leak
  var sideDiv = iframe.nextSibling;
  var lineMetricsDiv = sideDiv.nextSibling;
  var overlaysdiv = lineMetricsDiv.nextSibling;
  initLineNumbers();

  var outsideKeyDown = noop;
  
  var outsideKeyPress = function(){return true;};
  
  var outsideNotifyDirty = noop;

  // selFocusAtStart -- determines whether the selection extends "backwards", so that the focus
  // point (controlled with the arrow keys) is at the beginning; not supported in IE, though
  // native IE selections have that behavior (which we try not to interfere with).
  // Must be false if selection is collapsed!
  var rep = {
    lines: new SkipList(),
    selStart: null,
    selEnd: null,
    selFocusAtStart: false,
    alltext: "",
    alines: [],
    apool: new AttribPool()
  };
  
  // lines, alltext, alines, and DOM are set up in setup()
  if (undoModule.enabled)
  {
    undoModule.apool = rep.apool;
  }

  var root, doc; // set in setup()
  var isEditable = true;
  var doesWrap = true;
  var hasLineNumbers = true;
  var isStyled = true;
  
  // space around the innermost iframe element
  var iframePadLeft = MIN_LINEDIV_WIDTH + LINE_NUMBER_PADDING_RIGHT + EDIT_BODY_PADDING_LEFT;
  var iframePadTop = EDIT_BODY_PADDING_TOP;
  var iframePadBottom = 0,
      iframePadRight = 0;

  var console = (DEBUG && window.console);
  var documentAttributeManager;
  
  if (!window.console)
  {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    console = {};
    for (var i = 0; i < names.length; ++i)
    console[names[i]] = noop;
    //console.error = function(str) { alert(str); };
  }

  var PROFILER = window.PROFILER;
  if (!PROFILER)
  {
    PROFILER = function()
    {
      return {
        start: noop,
        mark: noop,
        literal: noop,
        end: noop,
        cancel: noop
      };
    };
  }

  // "dmesg" is for displaying messages in the in-page output pane
  // visible when "?djs=1" is appended to the pad URL.  It generally
  // remains a no-op unless djs is enabled, but we make a habit of
  // only calling it in error cases or while debugging.
  var dmesg = noop;
  window.dmesg = noop;

  var scheduler = parent;

  var textFace = 'monospace';
  var textSize = 12;
  

  function textLineHeight()
  {
    return Math.round(textSize * 4 / 3);
  }

  var dynamicCSS = null;

  function initDynamicCSS()
  {
    dynamicCSS = makeCSSManager("dynamicsyntax");
  }

  var changesetTracker = makeChangesetTracker(scheduler, rep.apool, {
    withCallbacks: function(operationName, f)
    {
      inCallStackIfNecessary(operationName, function()
      {
        fastIncorp(1);
        f(
        {
          setDocumentAttributedText: function(atext)
          {
            setDocAText(atext);
          },
          applyChangesetToDocument: function(changeset, preferInsertionAfterCaret)
          {
            var oldEventType = currentCallStack.editEvent.eventType;
            currentCallStack.startNewEvent("nonundoable");

            performDocumentApplyChangeset(changeset, preferInsertionAfterCaret);

            currentCallStack.startNewEvent(oldEventType);
          }
        });
      });
    }
  });

  var authorInfos = {}; // presence of key determines if author is present in doc

  function setAuthorInfo(author, info)
  {
    if ((typeof author) != "string")
    {
      throw new Error("setAuthorInfo: author (" + author + ") is not a string");
    }
    if (!info)
    {
      delete authorInfos[author];
      if (dynamicCSS)
      {
        dynamicCSS.removeSelectorStyle(getAuthorColorClassSelector(getAuthorClassName(author)));
      }
    }
    else
    {
      authorInfos[author] = info;
      if (info.bgcolor)
      {
        if (dynamicCSS)
        {
          var bgcolor = info.bgcolor;
          if ((typeof info.fade) == "number")
          {
            bgcolor = fadeColor(bgcolor, info.fade);
          }
          
          var authorStyle = dynamicCSS.selectorStyle(getAuthorColorClassSelector(
          getAuthorClassName(author)));
          var anchorStyle = dynamicCSS.selectorStyle(getAuthorColorClassSelector(
          getAuthorClassName(author))+' > a')
          
          // author color
          authorStyle.backgroundColor = bgcolor;
          
          // text contrast
          if(colorutils.luminosity(colorutils.css2triple(bgcolor)) < 0.5)
          {
            authorStyle.color = '#ffffff';
          }else{
            authorStyle.color = null;
          }
          
          // anchor text contrast
          if(colorutils.luminosity(colorutils.css2triple(bgcolor)) < 0.55)
          {
            anchorStyle.color = colorutils.triple2css(colorutils.complementary(colorutils.css2triple(bgcolor)));
          }else{
            anchorStyle.color = null;
          }
        }
      }
    }
  }

  function getAuthorClassName(author)
  {
    return "author-" + author.replace(/[^a-y0-9]/g, function(c)
    {
      if (c == ".") return "-";
      return 'z' + c.charCodeAt(0) + 'z';
    });
  }

  function className2Author(className)
  {
    if (className.substring(0, 7) == "author-")
    {
      return className.substring(7).replace(/[a-y0-9]+|-|z.+?z/g, function(cc)
      {
        if (cc == '-') return '.';
        else if (cc.charAt(0) == 'z')
        {
          return String.fromCharCode(Number(cc.slice(1, -1)));
        }
        else
        {
          return cc;
        }
      });
    }
    return null;
  }

  function getAuthorColorClassSelector(oneClassName)
  {
    return ".authorColors ." + oneClassName;
  }

  function setUpTrackingCSS()
  {
    if (dynamicCSS)
    {
      var backgroundHeight = lineMetricsDiv.offsetHeight;
      var lineHeight = textLineHeight();
      var extraBodding = 0;
      var extraTodding = 0;
      if (backgroundHeight < lineHeight)
      {
        extraBodding = Math.ceil((lineHeight - backgroundHeight) / 2);
        extraTodding = lineHeight - backgroundHeight - extraBodding;
      }
      var spanStyle = dynamicCSS.selectorStyle("#innerdocbody span");
      spanStyle.paddingTop = extraTodding + "px";
      spanStyle.paddingBottom = extraBodding + "px";
    }
  }

  function boldColorFromColor(lightColorCSS)
  {
    var color = colorutils.css2triple(lightColorCSS);

    // amp up the saturation to full
    color = colorutils.saturate(color);

    // normalize brightness based on luminosity
    color = colorutils.scaleColor(color, 0, 0.5 / colorutils.luminosity(color));

    return colorutils.triple2css(color);
  }

  function fadeColor(colorCSS, fadeFrac)
  {
    var color = colorutils.css2triple(colorCSS);
    color = colorutils.blend(color, [1, 1, 1], fadeFrac);
    return colorutils.triple2css(color);
  }

  function doAlert(str)
  {
    scheduler.setTimeout(function()
    {
      alert(str);
    }, 0);
  }

  editorInfo.ace_getRep = function()
  {
    return rep;
  };

  editorInfo.ace_getAuthor = function()
  {
    return thisAuthor;
  }

  var currentCallStack = null;

  function inCallStack(type, action)
  {
    if (disposed) return;

    if (currentCallStack)
    {
      console.error("Can't enter callstack " + type + ", already in " + currentCallStack.type);
    }

    var profiling = false;

    function profileRest()
    {
      profiling = true;
      console.profile();
    }

    function newEditEvent(eventType)
    {
      return {
        eventType: eventType,
        backset: null
      };
    }

    function submitOldEvent(evt)
    {
      if (rep.selStart && rep.selEnd)
      {
        var selStartChar = rep.lines.offsetOfIndex(rep.selStart[0]) + rep.selStart[1];
        var selEndChar = rep.lines.offsetOfIndex(rep.selEnd[0]) + rep.selEnd[1];
        evt.selStart = selStartChar;
        evt.selEnd = selEndChar;
        evt.selFocusAtStart = rep.selFocusAtStart;
      }
      if (undoModule.enabled)
      {
        var undoWorked = false;
        try
        {
          if (evt.eventType == "setup" || evt.eventType == "importText" || evt.eventType == "setBaseText")
          {
            undoModule.clearHistory();
          }
          else if (evt.eventType == "nonundoable")
          {
            if (evt.changeset)
            {
              undoModule.reportExternalChange(evt.changeset);
            }
          }
          else
          {
            undoModule.reportEvent(evt);
          }
          undoWorked = true;
        }
        finally
        {
          if (!undoWorked)
          {
            undoModule.enabled = false; // for safety
          }
        }
      }
    }

    function startNewEvent(eventType, dontSubmitOld)
    {
      var oldEvent = currentCallStack.editEvent;
      if (!dontSubmitOld)
      {
        submitOldEvent(oldEvent);
      }
      currentCallStack.editEvent = newEditEvent(eventType);
      return oldEvent;
    }

    currentCallStack = {
      type: type,
      docTextChanged: false,
      selectionAffected: false,
      userChangedSelection: false,
      domClean: false,
      profileRest: profileRest,
      isUserChange: false,
      // is this a "user change" type of call-stack
      repChanged: false,
      editEvent: newEditEvent(type),
      startNewEvent: startNewEvent
    };
    var cleanExit = false;
    var result;
    try
    {
      result = action();

      hooks.callAll('aceEditEvent', {
        callstack: currentCallStack,
        editorInfo: editorInfo,
        rep: rep,
        documentAttributeManager: documentAttributeManager
      });

      //console.log("Just did action for: "+type);
      cleanExit = true;
    }
    catch (e)
    {
      caughtErrors.push(
      {
        error: e,
        time: +new Date()
      });
      dmesg(e.toString());
      throw e;
    }
    finally
    {
      var cs = currentCallStack;
      //console.log("Finished action for: "+type);
      if (cleanExit)
      {
        submitOldEvent(cs.editEvent);
        if (cs.domClean && cs.type != "setup")
        {
          // if (cs.isUserChange)
          // {
          //  if (cs.repChanged) parenModule.notifyChange();
          //  else parenModule.notifyTick();
          // }
          if (cs.selectionAffected)
          {
            updateBrowserSelectionFromRep();
          }
          if ((cs.docTextChanged || cs.userChangedSelection) && cs.type != "applyChangesToBase")
          {
            scrollSelectionIntoView();
          }
          if (cs.docTextChanged && cs.type.indexOf("importText") < 0)
          {
            outsideNotifyDirty();
          }
        }
      }
      else
      {
        // non-clean exit
        if (currentCallStack.type == "idleWorkTimer")
        {
          idleWorkTimer.atLeast(1000);
        }
      }
      currentCallStack = null;
      if (profiling) console.profileEnd();
    }
    return result;
  }
  editorInfo.ace_inCallStack = inCallStack;

  function inCallStackIfNecessary(type, action)
  {
    if (!currentCallStack)
    {
      inCallStack(type, action);
    }
    else
    {
      action();
    }
  }
  editorInfo.ace_inCallStackIfNecessary = inCallStackIfNecessary;

  function recolorLineByKey(key)
  {
    if (rep.lines.containsKey(key))
    {
      var offset = rep.lines.offsetOfKey(key);
      var width = rep.lines.atKey(key).width;
      recolorLinesInRange(offset, offset + width);
    }
  }

  function getLineKeyForOffset(charOffset)
  {
    return rep.lines.atOffset(charOffset).key;
  }
    
  
  function dispose()
  {
    disposed = true;
    if (idleWorkTimer) idleWorkTimer.never();
    teardown();
  }

  function checkALines()
  {
    return; // disable for speed


    function error()
    {
      throw new Error("checkALines");
    }
    if (rep.alines.length != rep.lines.length())
    {
      error();
    }
    for (var i = 0; i < rep.alines.length; i++)
    {
      var aline = rep.alines[i];
      var lineText = rep.lines.atIndex(i).text + "\n";
      var lineTextLength = lineText.length;
      var opIter = Changeset.opIterator(aline);
      var alineLength = 0;
      while (opIter.hasNext())
      {
        var o = opIter.next();
        alineLength += o.chars;
        if (opIter.hasNext())
        {
          if (o.lines !== 0) error();
        }
        else
        {
          if (o.lines != 1) error();
        }
      }
      if (alineLength != lineTextLength)
      {
        error();
      }
    }
  }

  function setWraps(newVal)
  {
    doesWrap = newVal;
    var dwClass = "doesWrap";
    setClassPresence(root, "doesWrap", doesWrap);
    scheduler.setTimeout(function()
    {
      inCallStackIfNecessary("setWraps", function()
      {
        fastIncorp(7);
        recreateDOM();
        fixView();
      });
    }, 0);
  }

  function setStyled(newVal)
  {
    var oldVal = isStyled;
    isStyled = !! newVal;

    if (newVal != oldVal)
    {
      if (!newVal)
      {
        // clear styles
        inCallStackIfNecessary("setStyled", function()
        {
          fastIncorp(12);
          var clearStyles = [];
          for (var k in STYLE_ATTRIBS)
          {
            clearStyles.push([k, '']);
          }
          performDocumentApplyAttributesToCharRange(0, rep.alltext.length, clearStyles);
        });
      }
    }
  }

  function setTextFace(face)
  {
    textFace = face;
    root.style.fontFamily = textFace;
    lineMetricsDiv.style.fontFamily = textFace;
    scheduler.setTimeout(function()
    {
      setUpTrackingCSS();
    }, 0);
  }

  function setTextSize(size)
  {
    textSize = size;
    root.style.fontSize = textSize + "px";
    root.style.lineHeight = textLineHeight() + "px";
    sideDiv.style.lineHeight = textLineHeight() + "px";
    lineMetricsDiv.style.fontSize = textSize + "px";
    scheduler.setTimeout(function()
    {
      setUpTrackingCSS();
    }, 0);
  }

  function recreateDOM()
  {
    // precond: normalized
    recolorLinesInRange(0, rep.alltext.length);
  }

  function setEditable(newVal)
  {
    isEditable = newVal;

    // the following may fail, e.g. if iframe is hidden
    if (!isEditable)
    {
      setDesignMode(false);
    }
    else
    {
      setDesignMode(true);
    }
    setClassPresence(root, "static", !isEditable);
  }

  function enforceEditability()
  {
    setEditable(isEditable);
  }

  function importText(text, undoable, dontProcess)
  {
    var lines;
    if (dontProcess)
    {
      if (text.charAt(text.length - 1) != "\n")
      {
        throw new Error("new raw text must end with newline");
      }
      if (/[\r\t\xa0]/.exec(text))
      {
        throw new Error("new raw text must not contain CR, tab, or nbsp");
      }
      lines = text.substring(0, text.length - 1).split('\n');
    }
    else
    {
      lines = _.map(text.split('\n'), textify);
    }
    var newText = "\n";
    if (lines.length > 0)
    {
      newText = lines.join('\n') + '\n';
    }

    inCallStackIfNecessary("importText" + (undoable ? "Undoable" : ""), function()
    {
      setDocText(newText);
    });

    if (dontProcess && rep.alltext != text)
    {
      throw new Error("mismatch error setting raw text in importText");
    }
  }

  function importAText(atext, apoolJsonObj, undoable)
  {
    atext = Changeset.cloneAText(atext);
    if (apoolJsonObj)
    {
      var wireApool = (new AttribPool()).fromJsonable(apoolJsonObj);
      atext.attribs = Changeset.moveOpsToNewPool(atext.attribs, wireApool, rep.apool);
    }
    inCallStackIfNecessary("importText" + (undoable ? "Undoable" : ""), function()
    {
      setDocAText(atext);
    });
  }

  function setDocAText(atext)
  {
    fastIncorp(8);

    var oldLen = rep.lines.totalWidth();
    var numLines = rep.lines.length();
    var upToLastLine = rep.lines.offsetOfIndex(numLines - 1);
    var lastLineLength = rep.lines.atIndex(numLines - 1).text.length;
    var assem = Changeset.smartOpAssembler();
    var o = Changeset.newOp('-');
    o.chars = upToLastLine;
    o.lines = numLines - 1;
    assem.append(o);
    o.chars = lastLineLength;
    o.lines = 0;
    assem.append(o);
    Changeset.appendATextToAssembler(atext, assem);
    var newLen = oldLen + assem.getLengthChange();
    var changeset = Changeset.checkRep(
    Changeset.pack(oldLen, newLen, assem.toString(), atext.text.slice(0, -1)));
    performDocumentApplyChangeset(changeset);

    performSelectionChange([0, rep.lines.atIndex(0).lineMarker], [0, rep.lines.atIndex(0).lineMarker]);

    idleWorkTimer.atMost(100);

    if (rep.alltext != atext.text)
    {
      dmesg(htmlPrettyEscape(rep.alltext));
      dmesg(htmlPrettyEscape(atext.text));
      throw new Error("mismatch error setting raw text in setDocAText");
    }
  }

  function setDocText(text)
  {
    setDocAText(Changeset.makeAText(text));
  }

  function getDocText()
  {
    var alltext = rep.alltext;
    var len = alltext.length;
    if (len > 0) len--; // final extra newline
    return alltext.substring(0, len);
  }

  function exportText()
  {
    if (currentCallStack && !currentCallStack.domClean)
    {
      inCallStackIfNecessary("exportText", function()
      {
        fastIncorp(2);
      });
    }
    return getDocText();
  }

  function editorChangedSize()
  {
    fixView();
  }

  function setOnKeyPress(handler)
  {
    outsideKeyPress = handler;
  }

  function setOnKeyDown(handler)
  {
    outsideKeyDown = handler;
  }

  function setNotifyDirty(handler)
  {
    outsideNotifyDirty = handler;
  }

  function getFormattedCode()
  {
    if (currentCallStack && !currentCallStack.domClean)
    {
      inCallStackIfNecessary("getFormattedCode", incorporateUserChanges);
    }
    var buf = [];
    if (rep.lines.length() > 0)
    {
      // should be the case, even for empty file
      var entry = rep.lines.atIndex(0);
      while (entry)
      {
        var domInfo = entry.domInfo;
        buf.push((domInfo && domInfo.getInnerHTML()) || domline.processSpaces(domline.escapeHTML(entry.text), doesWrap) || '&nbsp;' /*empty line*/ );
        entry = rep.lines.next(entry);
      }
    }
    return '<div class="syntax"><div>' + buf.join('</div>\n<div>') + '</div></div>';
  }

  var CMDS = {
    clearauthorship: function(prompt)
    {
      if ((!(rep.selStart && rep.selEnd)) || isCaret())
      {
        if (prompt)
        {
          prompt();
        }
        else
        {
          performDocumentApplyAttributesToCharRange(0, rep.alltext.length, [
            ['author', '']
          ]);
        }
      }
      else
      {
        setAttributeOnSelection('author', '');
      }
    }
  };

  function execCommand(cmd)
  {
    cmd = cmd.toLowerCase();
    var cmdArgs = Array.prototype.slice.call(arguments, 1);
    if (CMDS[cmd])
    {
      inCallStackIfNecessary(cmd, function()
      {
        fastIncorp(9);
        CMDS[cmd].apply(CMDS, cmdArgs);
      });
    }
  }

  function replaceRange(start, end, text)
  {
    inCallStackIfNecessary('replaceRange', function()
    {
      fastIncorp(9);
      performDocumentReplaceRange(start, end, text);
    });
  }

  editorInfo.ace_focus = focus;
  editorInfo.ace_importText = importText;
  editorInfo.ace_importAText = importAText;
  editorInfo.ace_exportText = exportText;
  editorInfo.ace_editorChangedSize = editorChangedSize;
  editorInfo.ace_setOnKeyPress = setOnKeyPress;
  editorInfo.ace_setOnKeyDown = setOnKeyDown;
  editorInfo.ace_setNotifyDirty = setNotifyDirty;
  editorInfo.ace_dispose = dispose;
  editorInfo.ace_getFormattedCode = getFormattedCode;
  editorInfo.ace_setEditable = setEditable;
  editorInfo.ace_execCommand = execCommand;
  editorInfo.ace_replaceRange = replaceRange;

  editorInfo.ace_callWithAce = function(fn, callStack, normalize)
  {
    var wrapper = function()
    {
      return fn(editorInfo);
    };
    
    if (normalize !== undefined)
    {
      var wrapper1 = wrapper;
      wrapper = function()
      {
        editorInfo.ace_fastIncorp(9);
        wrapper1();
      };
    }

    if (callStack !== undefined)
    {
      return editorInfo.ace_inCallStack(callStack, wrapper);
    }
    else
    {
      return wrapper();
    }
  };

  // This methed exposes a setter for some ace properties
  // @param key the name of the parameter
  // @param value the value to set to
  editorInfo.ace_setProperty = function(key, value)
  {
    
    // Convinience function returning a setter for a class on an element    
    var setClassPresenceNamed = function(element, cls){
      return function(value){
         setClassPresence(element, cls, !! value)
      }
    };
    
    // These properties are exposed
    var setters = {
      wraps: setWraps,
      showsauthorcolors: setClassPresenceNamed(root, "authorColors"),
      showsuserselections: setClassPresenceNamed(root, "userSelections"),
      showslinenumbers : function(value){
        hasLineNumbers = !! value;
        // disable line numbers on mobile devices
        if (browser.mobile) hasLineNumbers = false;
        setClassPresence(sideDiv, "sidedivhidden", !hasLineNumbers);
        fixView();
      },
      grayedout: setClassPresenceNamed(outerWin.document.body, "grayedout"),
      dmesg: function(){ dmesg = window.dmesg = value; },
      userauthor: function(value){ 
        thisAuthor = String(value);
        documentAttributeManager.author = thisAuthor;
      },
      styled: setStyled,
      textface: setTextFace,
      textsize: setTextSize,
      rtlistrue: setClassPresenceNamed(root, "rtl")
    };
    
    var setter = setters[key.toLowerCase()];
    
    // check if setter is present 
    if(setter !== undefined){
      setter(value)
    }
  };

  editorInfo.ace_setBaseText = function(txt)
  {
    changesetTracker.setBaseText(txt);
  };
  editorInfo.ace_setBaseAttributedText = function(atxt, apoolJsonObj)
  {
    setUpTrackingCSS();
    changesetTracker.setBaseAttributedText(atxt, apoolJsonObj);
  };
  editorInfo.ace_applyChangesToBase = function(c, optAuthor, apoolJsonObj)
  {
    changesetTracker.applyChangesToBase(c, optAuthor, apoolJsonObj);
  };
  editorInfo.ace_prepareUserChangeset = function()
  {
    return changesetTracker.prepareUserChangeset();
  };
  editorInfo.ace_applyPreparedChangesetToBase = function()
  {
    changesetTracker.applyPreparedChangesetToBase();
  };
  editorInfo.ace_setUserChangeNotificationCallback = function(f)
  {
    changesetTracker.setUserChangeNotificationCallback(f);
  };
  editorInfo.ace_setAuthorInfo = function(author, info)
  {
    setAuthorInfo(author, info);
  };
  editorInfo.ace_setAuthorSelectionRange = function(author, start, end)
  {
    changesetTracker.setAuthorSelectionRange(author, start, end);
  };

  editorInfo.ace_getUnhandledErrors = function()
  {
    return caughtErrors.slice();
  };

  editorInfo.ace_getDebugProperty = function(prop)
  {
    if (prop == "debugger")
    {
      // obfuscate "eval" so as not to scare yuicompressor
      window['ev' + 'al']("debugger");
    }
    else if (prop == "rep")
    {
      return rep;
    }
    else if (prop == "window")
    {
      return window;
    }
    else if (prop == "document")
    {
      return document;
    }
    return undefined;
  };

  function now()
  {
    return (new Date()).getTime();
  }

  function newTimeLimit(ms)
  {
    //console.debug("new time limit");
    var startTime = now();
    var lastElapsed = 0;
    var exceededAlready = false;
    var printedTrace = false;
    var isTimeUp = function()
      {
        if (exceededAlready)
        {
          if ((!printedTrace))
          { // && now() - startTime - ms > 300) {
            //console.trace();
            printedTrace = true;
          }
          return true;
        }
        var elapsed = now() - startTime;
        if (elapsed > ms)
        {
          exceededAlready = true;
          //console.debug("time limit hit, before was %d/%d", lastElapsed, ms);
          //console.trace();
          return true;
        }
        else
        {
          lastElapsed = elapsed;
          return false;
        }
      };
        
    isTimeUp.elapsed = function()
    {
      return now() - startTime;
    };
    return isTimeUp;
  }


  function makeIdleAction(func)
  {
    var scheduledTimeout = null;
    var scheduledTime = 0;

    function unschedule()
    {
      if (scheduledTimeout)
      {
        scheduler.clearTimeout(scheduledTimeout);
        scheduledTimeout = null;
      }
    }

    function reschedule(time)
    {
      unschedule();
      scheduledTime = time;
      var delay = time - now();
      if (delay < 0) delay = 0;
      scheduledTimeout = scheduler.setTimeout(callback, delay);
    }

    function callback()
    {
      scheduledTimeout = null;
      // func may reschedule the action
      func();
    }
    return {
      atMost: function(ms)
      {
        var latestTime = now() + ms;
        if ((!scheduledTimeout) || scheduledTime > latestTime)
        {
          reschedule(latestTime);
        }
      },
      // atLeast(ms) will schedule the action if not scheduled yet.
      // In other words, "infinity" is replaced by ms, even though
      // it is technically larger.
      atLeast: function(ms)
      {
        var earliestTime = now() + ms;
        if ((!scheduledTimeout) || scheduledTime < earliestTime)
        {
          reschedule(earliestTime);
        }
      },
      never: function()
      {
        unschedule();
      }
    };
  }

  function fastIncorp(n)
  {
    // normalize but don't do any lexing or anything
    incorporateUserChanges(newTimeLimit(0));
  }
  editorInfo.ace_fastIncorp = fastIncorp;

  function incorpIfQuick()
  {
    var me = incorpIfQuick;
    var failures = (me.failures || 0);
    if (failures < 5)
    {
      var isTimeUp = newTimeLimit(40);
      var madeChanges = incorporateUserChanges(isTimeUp);
      if (isTimeUp())
      {
        me.failures = failures + 1;
      }
      return true;
    }
    else
    {
      var skipCount = (me.skipCount || 0);
      skipCount++;
      if (skipCount == 20)
      {
        skipCount = 0;
        me.failures = 0;
      }
      me.skipCount = skipCount;
    }
    return false;
  }

  var idleWorkTimer = makeIdleAction(function()
  {

    //if (! top.BEFORE) top.BEFORE = [];
    //top.BEFORE.push(magicdom.root.dom.innerHTML);
    //if (! isEditable) return; // and don't reschedule
    if (window.parent.parent.inInternationalComposition)
    {
      // don't do idle input incorporation during international input composition
      idleWorkTimer.atLeast(500);
      return;
    }

    inCallStackIfNecessary("idleWorkTimer", function()
    {

      var isTimeUp = newTimeLimit(250);

      //console.time("idlework");
      var finishedImportantWork = false;
      var finishedWork = false;

      try
      {

        // isTimeUp() is a soft constraint for incorporateUserChanges,
        // which always renormalizes the DOM, no matter how long it takes,
        // but doesn't necessarily lex and highlight it
        incorporateUserChanges(isTimeUp);

        if (isTimeUp()) return;

        updateLineNumbers(); // update line numbers if any time left
        if (isTimeUp()) return;

        var visibleRange = getVisibleCharRange();
        var docRange = [0, rep.lines.totalWidth()];
        //console.log("%o %o", docRange, visibleRange);
        finishedImportantWork = true;
        finishedWork = true;
      }
      finally
      {
        //console.timeEnd("idlework");
        if (finishedWork)
        {
          idleWorkTimer.atMost(1000);
        }
        else if (finishedImportantWork)
        {
          // if we've finished highlighting the view area,
          // more highlighting could be counter-productive,
          // e.g. if the user just opened a triple-quote and will soon close it.
          idleWorkTimer.atMost(500);
        }
        else
        {
          var timeToWait = Math.round(isTimeUp.elapsed() / 2);
          if (timeToWait < 100) timeToWait = 100;
          idleWorkTimer.atMost(timeToWait);
        }
      }
    });

    //if (! top.AFTER) top.AFTER = [];
    //top.AFTER.push(magicdom.root.dom.innerHTML);
  });

  var _nextId = 1;

  function uniqueId(n)
  {
    // not actually guaranteed to be unique, e.g. if user copy-pastes
    // nodes with ids
    var nid = n.id;
    if (nid) return nid;
    return (n.id = "magicdomid" + (_nextId++));
  }


  function recolorLinesInRange(startChar, endChar, isTimeUp, optModFunc)
  {
    if (endChar <= startChar) return;
    if (startChar < 0 || startChar >= rep.lines.totalWidth()) return;
    var lineEntry = rep.lines.atOffset(startChar); // rounds down to line boundary
    var lineStart = rep.lines.offsetOfEntry(lineEntry);
    var lineIndex = rep.lines.indexOfEntry(lineEntry);
    var selectionNeedsResetting = false;
    var firstLine = null;
    var lastLine = null;
    isTimeUp = (isTimeUp || noop);

    // tokenFunc function; accesses current value of lineEntry and curDocChar,
    // also mutates curDocChar
    var curDocChar;
    var tokenFunc = function(tokenText, tokenClass)
      {
        lineEntry.domInfo.appendSpan(tokenText, tokenClass);
        };
    if (optModFunc)
    {
      var f = tokenFunc;
      tokenFunc = function(tokenText, tokenClass)
      {
        optModFunc(tokenText, tokenClass, f, curDocChar);
        curDocChar += tokenText.length;
      };
    }

    while (lineEntry && lineStart < endChar && !isTimeUp())
    {
      //var timer = newTimeLimit(200);
      var lineEnd = lineStart + lineEntry.width;

      curDocChar = lineStart;
      lineEntry.domInfo.clearSpans();
      getSpansForLine(lineEntry, tokenFunc, lineStart);
      lineEntry.domInfo.finishUpdate();

      markNodeClean(lineEntry.lineNode);

      if (rep.selStart && rep.selStart[0] == lineIndex || rep.selEnd && rep.selEnd[0] == lineIndex)
      {
        selectionNeedsResetting = true;
      }

      //if (timer()) console.dirxml(lineEntry.lineNode.dom);
      if (firstLine === null) firstLine = lineIndex;
      lastLine = lineIndex;
      lineStart = lineEnd;
      lineEntry = rep.lines.next(lineEntry);
      lineIndex++;
    }
    if (selectionNeedsResetting)
    {
      currentCallStack.selectionAffected = true;
    }
    //console.debug("Recolored line range %d-%d", firstLine, lastLine);
  }

  // like getSpansForRange, but for a line, and the func takes (text,class)
  // instead of (width,class); excludes the trailing '\n' from
  // consideration by func


  function getSpansForLine(lineEntry, textAndClassFunc, lineEntryOffsetHint)
  {
    var lineEntryOffset = lineEntryOffsetHint;
    if ((typeof lineEntryOffset) != "number")
    {
      lineEntryOffset = rep.lines.offsetOfEntry(lineEntry);
    }
    var text = lineEntry.text;
    var width = lineEntry.width; // text.length+1
    if (text.length === 0)
    {
      // allow getLineStyleFilter to set line-div styles
      var func = linestylefilter.getLineStyleFilter(
      0, '', textAndClassFunc, rep.apool);
      func('', '');
    }
    else
    {
      var offsetIntoLine = 0;
      var filteredFunc = linestylefilter.getFilterStack(text, textAndClassFunc, browser);
      var lineNum = rep.lines.indexOfEntry(lineEntry);
      var aline = rep.alines[lineNum];
      filteredFunc = linestylefilter.getLineStyleFilter(
      text.length, aline, filteredFunc, rep.apool);
      filteredFunc(text, '');
    }
  }

  var observedChanges;

  function clearObservedChanges()
  {
    observedChanges = {
      cleanNodesNearChanges: {}
    };
  }
  clearObservedChanges();

  function getCleanNodeByKey(key)
  {
    var p = PROFILER("getCleanNodeByKey", false);
    p.extra = 0;
    var n = doc.getElementById(key);
    // copying and pasting can lead to duplicate ids
    while (n && isNodeDirty(n))
    {
      p.extra++;
      n.id = "";
      n = doc.getElementById(key);
    }
    p.literal(p.extra, "extra");
    p.end();
    return n;
  }

  function observeChangesAroundNode(node)
  {
    // Around this top-level DOM node, look for changes to the document
    // (from how it looks in our representation) and record them in a way
    // that can be used to "normalize" the document (apply the changes to our
    // representation, and put the DOM in a canonical form).
    //top.console.log("observeChangesAroundNode(%o)", node);
    var cleanNode;
    var hasAdjacentDirtyness;
    if (!isNodeDirty(node))
    {
      cleanNode = node;
      var prevSib = cleanNode.previousSibling;
      var nextSib = cleanNode.nextSibling;
      hasAdjacentDirtyness = ((prevSib && isNodeDirty(prevSib)) || (nextSib && isNodeDirty(nextSib)));
    }
    else
    {
      // node is dirty, look for clean node above
      var upNode = node.previousSibling;
      while (upNode && isNodeDirty(upNode))
      {
        upNode = upNode.previousSibling;
      }
      if (upNode)
      {
        cleanNode = upNode;
      }
      else
      {
        var downNode = node.nextSibling;
        while (downNode && isNodeDirty(downNode))
        {
          downNode = downNode.nextSibling;
        }
        if (downNode)
        {
          cleanNode = downNode;
        }
      }
      if (!cleanNode)
      {
        // Couldn't find any adjacent clean nodes!
        // Since top and bottom of doc is dirty, the dirty area will be detected.
        return;
      }
      hasAdjacentDirtyness = true;
    }

    if (hasAdjacentDirtyness)
    {
      // previous or next line is dirty
      observedChanges.cleanNodesNearChanges['$' + uniqueId(cleanNode)] = true;
    }
    else
    {
      // next and prev lines are clean (if they exist)
      var lineKey = uniqueId(cleanNode);
      var prevSib = cleanNode.previousSibling;
      var nextSib = cleanNode.nextSibling;
      var actualPrevKey = ((prevSib && uniqueId(prevSib)) || null);
      var actualNextKey = ((nextSib && uniqueId(nextSib)) || null);
      var repPrevEntry = rep.lines.prev(rep.lines.atKey(lineKey));
      var repNextEntry = rep.lines.next(rep.lines.atKey(lineKey));
      var repPrevKey = ((repPrevEntry && repPrevEntry.key) || null);
      var repNextKey = ((repNextEntry && repNextEntry.key) || null);
      if (actualPrevKey != repPrevKey || actualNextKey != repNextKey)
      {
        observedChanges.cleanNodesNearChanges['$' + uniqueId(cleanNode)] = true;
      }
    }
  }

  function observeChangesAroundSelection()
  {
    if (currentCallStack.observedSelection) return;
    currentCallStack.observedSelection = true;

    var p = PROFILER("getSelection", false);
    var selection = getSelection();
    p.end();
    
    function topLevel(n)
    {
      if ((!n) || n == root) return null;
      while (n.parentNode != root)
      {
        n = n.parentNode;
      }
      return n;
    }
    
    if (selection)
    {
      var node1 = topLevel(selection.startPoint.node);
      var node2 = topLevel(selection.endPoint.node);
      if (node1) observeChangesAroundNode(node1);
      if (node2 && node1 != node2)
      {
        observeChangesAroundNode(node2);
      }
    }
  }

  function observeSuspiciousNodes()
  {
    // inspired by Firefox bug #473255, where pasting formatted text
    // causes the cursor to jump away, making the new HTML never found.
    if (root.getElementsByTagName)
    {
      var nds = root.getElementsByTagName("style");
      for (var i = 0; i < nds.length; i++)
      {
        var n = nds[i];
        while (n.parentNode && n.parentNode != root)
        {
          n = n.parentNode;
        }
        if (n.parentNode == root)
        {
          observeChangesAroundNode(n);
        }
      }
    }
  }

  function incorporateUserChanges(isTimeUp)
  {

    if (currentCallStack.domClean) return false;

    currentCallStack.isUserChange = true;

    isTimeUp = (isTimeUp ||
    function()
    {
      return false;
    });

    if (DEBUG && window.DONT_INCORP || window.DEBUG_DONT_INCORP) return false;

    var p = PROFILER("incorp", false);

    //if (doc.body.innerHTML.indexOf("AppJet") >= 0)
    //dmesg(htmlPrettyEscape(doc.body.innerHTML));
    //if (top.RECORD) top.RECORD.push(doc.body.innerHTML);
    // returns true if dom changes were made
    if (!root.firstChild)
    {
      root.innerHTML = "<div><!-- --></div>";
    }

    p.mark("obs");
    observeChangesAroundSelection();
    observeSuspiciousNodes();
    p.mark("dirty");
    var dirtyRanges = getDirtyRanges();
    //console.log("dirtyRanges: "+toSource(dirtyRanges));
    var dirtyRangesCheckOut = true;
    var j = 0;
    var a, b;
    while (j < dirtyRanges.length)
    {
      a = dirtyRanges[j][0];
      b = dirtyRanges[j][1];
      if (!((a === 0 || getCleanNodeByKey(rep.lines.atIndex(a - 1).key)) && (b == rep.lines.length() || getCleanNodeByKey(rep.lines.atIndex(b).key))))
      {
        dirtyRangesCheckOut = false;
        break;
      }
      j++;
    }
    if (!dirtyRangesCheckOut)
    {
      var numBodyNodes = root.childNodes.length;
      for (var k = 0; k < numBodyNodes; k++)
      {
        var bodyNode = root.childNodes.item(k);
        if ((bodyNode.tagName) && ((!bodyNode.id) || (!rep.lines.containsKey(bodyNode.id))))
        {
          observeChangesAroundNode(bodyNode);
        }
      }
      dirtyRanges = getDirtyRanges();
    }

    clearObservedChanges();

    p.mark("getsel");
    var selection = getSelection();

    //console.log(magicdom.root.dom.innerHTML);
    //console.log("got selection: %o", selection);
    var selStart, selEnd; // each one, if truthy, has [line,char] needed to set selection
    var i = 0;
    var splicesToDo = [];
    var netNumLinesChangeSoFar = 0;
    var toDeleteAtEnd = [];
    p.mark("ranges");
    p.literal(dirtyRanges.length, "numdirt");
    var domInsertsNeeded = []; // each entry is [nodeToInsertAfter, [info1, info2, ...]]
    while (i < dirtyRanges.length)
    {
      var range = dirtyRanges[i];
      a = range[0];
      b = range[1];
      var firstDirtyNode = (((a === 0) && root.firstChild) || getCleanNodeByKey(rep.lines.atIndex(a - 1).key).nextSibling);
      firstDirtyNode = (firstDirtyNode && isNodeDirty(firstDirtyNode) && firstDirtyNode);
      var lastDirtyNode = (((b == rep.lines.length()) && root.lastChild) || getCleanNodeByKey(rep.lines.atIndex(b).key).previousSibling);
      lastDirtyNode = (lastDirtyNode && isNodeDirty(lastDirtyNode) && lastDirtyNode);
      if (firstDirtyNode && lastDirtyNode)
      {
        var cc = makeContentCollector(isStyled, browser, rep.apool, null, className2Author);
        cc.notifySelection(selection);
        var dirtyNodes = [];
        for (var n = firstDirtyNode; n && !(n.previousSibling && n.previousSibling == lastDirtyNode);
        n = n.nextSibling)
        {
          if (browser.msie)
          {
            // try to undo IE's pesky and overzealous linkification
            try
            {
              n.createTextRange().execCommand("unlink", false, null);
            }
            catch (e)
            {}
          }
          cc.collectContent(n);
          dirtyNodes.push(n);
        }
        cc.notifyNextNode(lastDirtyNode.nextSibling);
        var lines = cc.getLines();
        if ((lines.length <= 1 || lines[lines.length - 1] !== "") && lastDirtyNode.nextSibling)
        {
          // dirty region doesn't currently end a line, even taking the following node
          // (or lack of node) into account, so include the following clean node.
          // It could be SPAN or a DIV; basically this is any case where the contentCollector
          // decides it isn't done.
          // Note that this clean node might need to be there for the next dirty range.
          //console.log("inclusive of "+lastDirtyNode.next().dom.tagName);
          b++;
          var cleanLine = lastDirtyNode.nextSibling;
          cc.collectContent(cleanLine);
          toDeleteAtEnd.push(cleanLine);
          cc.notifyNextNode(cleanLine.nextSibling);
        }

        var ccData = cc.finish();
        var ss = ccData.selStart;
        var se = ccData.selEnd;
        lines = ccData.lines;
        var lineAttribs = ccData.lineAttribs;
        var linesWrapped = ccData.linesWrapped;

        if (linesWrapped > 0)
        {
          doAlert("Editor warning: " + linesWrapped + " long line" + (linesWrapped == 1 ? " was" : "s were") + " hard-wrapped into " + ccData.numLinesAfter + " lines.");
        }

        if (ss[0] >= 0) selStart = [ss[0] + a + netNumLinesChangeSoFar, ss[1]];
        if (se[0] >= 0) selEnd = [se[0] + a + netNumLinesChangeSoFar, se[1]];

        var entries = [];
        var nodeToAddAfter = lastDirtyNode;
        var lineNodeInfos = new Array(lines.length);
        for (var k = 0; k < lines.length; k++)
        {
          var lineString = lines[k];
          var newEntry = createDomLineEntry(lineString);
          entries.push(newEntry);
          lineNodeInfos[k] = newEntry.domInfo;
        }
        //var fragment = magicdom.wrapDom(document.createDocumentFragment());
        domInsertsNeeded.push([nodeToAddAfter, lineNodeInfos]);
        _.each(dirtyNodes,function(n){
          toDeleteAtEnd.push(n);
        });
        var spliceHints = {};
        if (selStart) spliceHints.selStart = selStart;
        if (selEnd) spliceHints.selEnd = selEnd;
        splicesToDo.push([a + netNumLinesChangeSoFar, b - a, entries, lineAttribs, spliceHints]);
        netNumLinesChangeSoFar += (lines.length - (b - a));
      }
      else if (b > a)
      {
        splicesToDo.push([a + netNumLinesChangeSoFar, b - a, [],
          []
        ]);
      }
      i++;
    }

    var domChanges = (splicesToDo.length > 0);

    // update the representation
    p.mark("splice");
    _.each(splicesToDo, function(splice)
    {
      doIncorpLineSplice(splice[0], splice[1], splice[2], splice[3], splice[4]);
    });

    //p.mark("relex");
    //rep.lexer.lexCharRange(getVisibleCharRange(), function() { return false; });
    //var isTimeUp = newTimeLimit(100);
    // do DOM inserts
    p.mark("insert");
    _.each(domInsertsNeeded,function(ins)
    {
      insertDomLines(ins[0], ins[1], isTimeUp);
    });

    p.mark("del");
    // delete old dom nodes
    _.each(toDeleteAtEnd,function(n)
    {
      //var id = n.uniqueId();
      // parent of n may not be "root" in IE due to non-tree-shaped DOM (wtf)
      n.parentNode.removeChild(n);

      //dmesg(htmlPrettyEscape(htmlForRemovedChild(n)));
      //console.log("removed: "+id);
    });

    p.mark("findsel");
    // if the nodes that define the selection weren't encountered during
    // content collection, figure out where those nodes are now.
    if (selection && !selStart)
    {
      //if (domChanges) dmesg("selection not collected");
      selStart = getLineAndCharForPoint(selection.startPoint);
    }
    if (selection && !selEnd)
    {
      selEnd = getLineAndCharForPoint(selection.endPoint);
    }

    // selection from content collection can, in various ways, extend past final
    // BR in firefox DOM, so cap the line
    var numLines = rep.lines.length();
    if (selStart && selStart[0] >= numLines)
    {
      selStart[0] = numLines - 1;
      selStart[1] = rep.lines.atIndex(selStart[0]).text.length;
    }
    if (selEnd && selEnd[0] >= numLines)
    {
      selEnd[0] = numLines - 1;
      selEnd[1] = rep.lines.atIndex(selEnd[0]).text.length;
    }

    p.mark("repsel");
    // update rep if we have a new selection
    // NOTE: IE loses the selection when you click stuff in e.g. the
    // editbar, so removing the selection when it's lost is not a good
    // idea. 
    if (selection) repSelectionChange(selStart, selEnd, selection && selection.focusAtStart);
    // update browser selection
    p.mark("browsel");
    if (selection && (domChanges || isCaret()))
    {
      // if no DOM changes (not this case), want to treat range selection delicately,
      // e.g. in IE not lose which end of the selection is the focus/anchor;
      // on the other hand, we may have just noticed a press of PageUp/PageDown
      currentCallStack.selectionAffected = true;
    }

    currentCallStack.domClean = true;

    p.mark("fixview");

    fixView();

    p.end("END");

    return domChanges;
  }

  function htmlForRemovedChild(n)
  {
    var div = doc.createElement("DIV");
    div.appendChild(n);
    return div.innerHTML;
  }

  var STYLE_ATTRIBS = {
    bold: true,
    italic: true,
    underline: true,
    strikethrough: true,
    list: true
  };
  var OTHER_INCORPED_ATTRIBS = {
    insertorder: true,
    author: true
  };

  function isStyleAttribute(aname)
  {
    return !!STYLE_ATTRIBS[aname];
  }

  function isIncorpedAttribute(aname)
  {
    return ( !! STYLE_ATTRIBS[aname]) || ( !! OTHER_INCORPED_ATTRIBS[aname]);
  }

  function insertDomLines(nodeToAddAfter, infoStructs, isTimeUp)
  {
    isTimeUp = (isTimeUp ||
    function()
    {
      return false;
    });

    var lastEntry;
    var lineStartOffset;
    if (infoStructs.length < 1) return;
    var startEntry = rep.lines.atKey(uniqueId(infoStructs[0].node));
    var endEntry = rep.lines.atKey(uniqueId(infoStructs[infoStructs.length - 1].node));
    var charStart = rep.lines.offsetOfEntry(startEntry);
    var charEnd = rep.lines.offsetOfEntry(endEntry) + endEntry.width;

    //rep.lexer.lexCharRange([charStart, charEnd], isTimeUp);
    _.each(infoStructs, function(info)
    {
      var p2 = PROFILER("insertLine", false);
      var node = info.node;
      var key = uniqueId(node);
      var entry;
      p2.mark("findEntry");
      if (lastEntry)
      {
        // optimization to avoid recalculation
        var next = rep.lines.next(lastEntry);
        if (next && next.key == key)
        {
          entry = next;
          lineStartOffset += lastEntry.width;
        }
      }
      if (!entry)
      {
        p2.literal(1, "nonopt");
        entry = rep.lines.atKey(key);
        lineStartOffset = rep.lines.offsetOfKey(key);
      }
      else p2.literal(0, "nonopt");
      lastEntry = entry;
      p2.mark("spans");
      getSpansForLine(entry, function(tokenText, tokenClass)
      {
        info.appendSpan(tokenText, tokenClass);
      }, lineStartOffset, isTimeUp());
      //else if (entry.text.length > 0) {
      //info.appendSpan(entry.text, 'dirty');
      //}
      p2.mark("addLine");
      info.prepareForAdd();
      entry.lineMarker = info.lineMarker;
      if (!nodeToAddAfter)
      {
        root.insertBefore(node, root.firstChild);
      }
      else
      {
        root.insertBefore(node, nodeToAddAfter.nextSibling);
      }
      nodeToAddAfter = node;
      info.notifyAdded();
      p2.mark("markClean");
      markNodeClean(node);
      p2.end();
    });
  }

  function isCaret()
  {
    return (rep.selStart && rep.selEnd && rep.selStart[0] == rep.selEnd[0] && rep.selStart[1] == rep.selEnd[1]);
  }
  editorInfo.ace_isCaret = isCaret;

  // prereq: isCaret()


  function caretLine()
  {
    return rep.selStart[0];
  }

  function caretColumn()
  {
    return rep.selStart[1];
  }

  function caretDocChar()
  {
    return rep.lines.offsetOfIndex(caretLine()) + caretColumn();
  }

  function handleReturnIndentation()
  {
    // on return, indent to level of previous line
    if (isCaret() && caretColumn() === 0 && caretLine() > 0)
    {
      var lineNum = caretLine();
      var thisLine = rep.lines.atIndex(lineNum);
      var prevLine = rep.lines.prev(thisLine);
      var prevLineText = prevLine.text;
      var theIndent = /^ *(?:)/.exec(prevLineText)[0];
      if (/[\[\(\{]\s*$/.exec(prevLineText)) theIndent += THE_TAB;
      var cs = Changeset.builder(rep.lines.totalWidth()).keep(
      rep.lines.offsetOfIndex(lineNum), lineNum).insert(
      theIndent, [
        ['author', thisAuthor]
      ], rep.apool).toString();
      performDocumentApplyChangeset(cs);
      performSelectionChange([lineNum, theIndent.length], [lineNum, theIndent.length]);
    }
  }

  function getPointForLineAndChar(lineAndChar)
  {
    var line = lineAndChar[0];
    var charsLeft = lineAndChar[1];
    //console.log("line: %d, key: %s, node: %o", line, rep.lines.atIndex(line).key,
    //getCleanNodeByKey(rep.lines.atIndex(line).key));
    var lineEntry = rep.lines.atIndex(line);
    charsLeft -= lineEntry.lineMarker;
    if (charsLeft < 0)
    {
      charsLeft = 0;
    }
    var lineNode = lineEntry.lineNode;
    var n = lineNode;
    var after = false;
    if (charsLeft === 0)
    {
      var index = 0;
      if (browser.msie && line == (rep.lines.length() - 1) && lineNode.childNodes.length === 0)
      {
        // best to stay at end of last empty div in IE
        index = 1;
      }
      return {
        node: lineNode,
        index: index,
        maxIndex: 1
      };
    }
    while (!(n == lineNode && after))
    {
      if (after)
      {
        if (n.nextSibling)
        {
          n = n.nextSibling;
          after = false;
        }
        else n = n.parentNode;
      }
      else
      {
        if (isNodeText(n))
        {
          var len = n.nodeValue.length;
          if (charsLeft <= len)
          {
            return {
              node: n,
              index: charsLeft,
              maxIndex: len
            };
          }
          charsLeft -= len;
          after = true;
        }
        else
        {
          if (n.firstChild) n = n.firstChild;
          else after = true;
        }
      }
    }
    return {
      node: lineNode,
      index: 1,
      maxIndex: 1
    };
  }

  function nodeText(n)
  {
    return n.innerText || n.textContent || n.nodeValue || '';
  }

  function getLineAndCharForPoint(point)
  {
    // Turn DOM node selection into [line,char] selection.
    // This method has to work when the DOM is not pristine,
    // assuming the point is not in a dirty node.
    if (point.node == root)
    {
      if (point.index === 0)
      {
        return [0, 0];
      }
      else
      {
        var N = rep.lines.length();
        var ln = rep.lines.atIndex(N - 1);
        return [N - 1, ln.text.length];
      }
    }
    else
    {
      var n = point.node;
      var col = 0;
      // if this part fails, it probably means the selection node
      // was dirty, and we didn't see it when collecting dirty nodes.
      if (isNodeText(n))
      {
        col = point.index;
      }
      else if (point.index > 0)
      {
        col = nodeText(n).length;
      }
      var parNode, prevSib;
      while ((parNode = n.parentNode) != root)
      {
        if ((prevSib = n.previousSibling))
        {
          n = prevSib;
          col += nodeText(n).length;
        }
        else
        {
          n = parNode;
        }
      }
      if (n.id === "") console.debug("BAD");
      if (n.firstChild && isBlockElement(n.firstChild))
      {
        col += 1; // lineMarker
      }
      var lineEntry = rep.lines.atKey(n.id);
      var lineNum = rep.lines.indexOfEntry(lineEntry);
      return [lineNum, col];
    }
  }
  editorInfo.ace_getLineAndCharForPoint = getLineAndCharForPoint;

  function createDomLineEntry(lineString)
  {
    var info = doCreateDomLine(lineString.length > 0);
    var newNode = info.node;
    return {
      key: uniqueId(newNode),
      text: lineString,
      lineNode: newNode,
      domInfo: info,
      lineMarker: 0
    };
  }

  function canApplyChangesetToDocument(changes)
  {
    return Changeset.oldLen(changes) == rep.alltext.length;
  }

  function performDocumentApplyChangeset(changes, insertsAfterSelection)
  {
    doRepApplyChangeset(changes, insertsAfterSelection);

    var requiredSelectionSetting = null;
    if (rep.selStart && rep.selEnd)
    {
      var selStartChar = rep.lines.offsetOfIndex(rep.selStart[0]) + rep.selStart[1];
      var selEndChar = rep.lines.offsetOfIndex(rep.selEnd[0]) + rep.selEnd[1];
      var result = Changeset.characterRangeFollow(changes, selStartChar, selEndChar, insertsAfterSelection);
      requiredSelectionSetting = [result[0], result[1], rep.selFocusAtStart];
    }

    var linesMutatee = {
      splice: function(start, numRemoved, newLinesVA)
      {
        var args = Array.prototype.slice.call(arguments, 2);
        domAndRepSplice(start, numRemoved, _.map(args, function(s){ return s.slice(0, -1); }), null);
      },
      get: function(i)
      {
        return rep.lines.atIndex(i).text + '\n';
      },
      length: function()
      {
        return rep.lines.length();
      },
      slice_notused: function(start, end)
      {
        return _.map(rep.lines.slice(start, end), function(e)
        {
          return e.text + '\n';
        });
      }
    };

    Changeset.mutateTextLines(changes, linesMutatee);

    checkALines();

    if (requiredSelectionSetting)
    {
      performSelectionChange(lineAndColumnFromChar(requiredSelectionSetting[0]), lineAndColumnFromChar(requiredSelectionSetting[1]), requiredSelectionSetting[2]);
    }

    function domAndRepSplice(startLine, deleteCount, newLineStrings, isTimeUp)
    {
      // dgreensp 3/2009: the spliced lines may be in the middle of a dirty region,
      // so if no explicit time limit, don't spend a lot of time highlighting
      isTimeUp = (isTimeUp || newTimeLimit(50));

      var keysToDelete = [];
      if (deleteCount > 0)
      {
        var entryToDelete = rep.lines.atIndex(startLine);
        for (var i = 0; i < deleteCount; i++)
        {
          keysToDelete.push(entryToDelete.key);
          entryToDelete = rep.lines.next(entryToDelete);
        }
      }

      var lineEntries = _.map(newLineStrings, createDomLineEntry);

      doRepLineSplice(startLine, deleteCount, lineEntries);

      var nodeToAddAfter;
      if (startLine > 0)
      {
        nodeToAddAfter = getCleanNodeByKey(rep.lines.atIndex(startLine - 1).key);
      }
      else nodeToAddAfter = null;

      insertDomLines(nodeToAddAfter, _.map(lineEntries, function(entry)
      {
        return entry.domInfo;
      }), isTimeUp);

      _.each(keysToDelete, function(k)
      {
        var n = doc.getElementById(k);
        n.parentNode.removeChild(n);
      });

      if ((rep.selStart && rep.selStart[0] >= startLine && rep.selStart[0] <= startLine + deleteCount) || (rep.selEnd && rep.selEnd[0] >= startLine && rep.selEnd[0] <= startLine + deleteCount))
      {
        currentCallStack.selectionAffected = true;
      }
    }
  }

  function checkChangesetLineInformationAgainstRep(changes)
  {
    return true; // disable for speed
    var opIter = Changeset.opIterator(Changeset.unpack(changes).ops);
    var curOffset = 0;
    var curLine = 0;
    var curCol = 0;
    while (opIter.hasNext())
    {
      var o = opIter.next();
      if (o.opcode == '-' || o.opcode == '=')
      {
        curOffset += o.chars;
        if (o.lines)
        {
          curLine += o.lines;
          curCol = 0;
        }
        else
        {
          curCol += o.chars;
        }
      }
      var calcLine = rep.lines.indexOfOffset(curOffset);
      var calcLineStart = rep.lines.offsetOfIndex(calcLine);
      var calcCol = curOffset - calcLineStart;
      if (calcCol != curCol || calcLine != curLine)
      {
        return false;
      }
    }
    return true;
  }

  function doRepApplyChangeset(changes, insertsAfterSelection)
  {
    Changeset.checkRep(changes);

    if (Changeset.oldLen(changes) != rep.alltext.length) throw new Error("doRepApplyChangeset length mismatch: " + Changeset.oldLen(changes) + "/" + rep.alltext.length);

    if (!checkChangesetLineInformationAgainstRep(changes))
    {
      throw new Error("doRepApplyChangeset line break mismatch");
    }

    (function doRecordUndoInformation(changes)
    {
      var editEvent = currentCallStack.editEvent;
      if (editEvent.eventType == "nonundoable")
      {
        if (!editEvent.changeset)
        {
          editEvent.changeset = changes;
        }
        else
        {
          editEvent.changeset = Changeset.compose(editEvent.changeset, changes, rep.apool);
        }
      }
      else
      {
        var inverseChangeset = Changeset.inverse(changes, {
          get: function(i)
          {
            return rep.lines.atIndex(i).text + '\n';
          },
          length: function()
          {
            return rep.lines.length();
          }
        }, rep.alines, rep.apool);

        if (!editEvent.backset)
        {
          editEvent.backset = inverseChangeset;
        }
        else
        {
          editEvent.backset = Changeset.compose(inverseChangeset, editEvent.backset, rep.apool);
        }
      }
    })(changes);

    //rep.alltext = Changeset.applyToText(changes, rep.alltext);
    Changeset.mutateAttributionLines(changes, rep.alines, rep.apool);

    if (changesetTracker.isTracking())
    {
      changesetTracker.composeUserChangeset(changes);
    }

  }

  /*
    Converts the position of a char (index in String) into a [row, col] tuple
  */
  function lineAndColumnFromChar(x)
  {
    var lineEntry = rep.lines.atOffset(x);
    var lineStart = rep.lines.offsetOfEntry(lineEntry);
    var lineNum = rep.lines.indexOfEntry(lineEntry);
    return [lineNum, x - lineStart];
  }

  function performDocumentReplaceCharRange(startChar, endChar, newText)
  {
    if (startChar == endChar && newText.length === 0)
    {
      return;
    }
    // Requires that the replacement preserve the property that the
    // internal document text ends in a newline.  Given this, we
    // rewrite the splice so that it doesn't touch the very last
    // char of the document.
    if (endChar == rep.alltext.length)
    {
      if (startChar == endChar)
      {
        // an insert at end
        startChar--;
        endChar--;
        newText = '\n' + newText.substring(0, newText.length - 1);
      }
      else if (newText.length === 0)
      {
        // a delete at end
        startChar--;
        endChar--;
      }
      else
      {
        // a replace at end
        endChar--;
        newText = newText.substring(0, newText.length - 1);
      }
    }
    performDocumentReplaceRange(lineAndColumnFromChar(startChar), lineAndColumnFromChar(endChar), newText);
  }

  function performDocumentReplaceRange(start, end, newText)
  {
    if (start === undefined) start = rep.selStart;
    if (end === undefined) end = rep.selEnd;

    //dmesg(String([start.toSource(),end.toSource(),newText.toSource()]));
    // start[0]: <--- start[1] --->CCCCCCCCCCC\n
    //           CCCCCCCCCCCCCCCCCCCC\n
    //           CCCC\n
    // end[0]:   <CCC end[1] CCC>-------\n
    var builder = Changeset.builder(rep.lines.totalWidth());
    ChangesetUtils.buildKeepToStartOfRange(rep, builder, start);
    ChangesetUtils.buildRemoveRange(rep, builder, start, end);
    builder.insert(newText, [
      ['author', thisAuthor]
    ], rep.apool);
    var cs = builder.toString();

    performDocumentApplyChangeset(cs);
  }

  function performDocumentApplyAttributesToCharRange(start, end, attribs)
  {
    end = Math.min(end, rep.alltext.length - 1);
    documentAttributeManager.setAttributesOnRange(lineAndColumnFromChar(start), lineAndColumnFromChar(end), attribs);
  }
  editorInfo.ace_performDocumentApplyAttributesToCharRange = performDocumentApplyAttributesToCharRange;
  
  
  function setAttributeOnSelection(attributeName, attributeValue)
  {
    if (!(rep.selStart && rep.selEnd)) return;

    documentAttributeManager.setAttributesOnRange(rep.selStart, rep.selEnd, [
      [attributeName, attributeValue]
    ]);
  }
  editorInfo.ace_setAttributeOnSelection = setAttributeOnSelection;

  function toggleAttributeOnSelection(attributeName)
  {
    if (!(rep.selStart && rep.selEnd)) return;

    var selectionAllHasIt = true;
    var withIt = Changeset.makeAttribsString('+', [
      [attributeName, 'true']
    ], rep.apool);
    var withItRegex = new RegExp(withIt.replace(/\*/g, '\\*') + "(\\*|$)");

    function hasIt(attribs)
    {
      return withItRegex.test(attribs);
    }

    var selStartLine = rep.selStart[0];
    var selEndLine = rep.selEnd[0];
    for (var n = selStartLine; n <= selEndLine; n++)
    {
      var opIter = Changeset.opIterator(rep.alines[n]);
      var indexIntoLine = 0;
      var selectionStartInLine = 0;
      var selectionEndInLine = rep.lines.atIndex(n).text.length; // exclude newline
      if (n == selStartLine)
      {
        selectionStartInLine = rep.selStart[1];
      }
      if (n == selEndLine)
      {
        selectionEndInLine = rep.selEnd[1];
      }
      while (opIter.hasNext())
      {
        var op = opIter.next();
        var opStartInLine = indexIntoLine;
        var opEndInLine = opStartInLine + op.chars;
        if (!hasIt(op.attribs))
        {
          // does op overlap selection?
          if (!(opEndInLine <= selectionStartInLine || opStartInLine >= selectionEndInLine))
          {
            selectionAllHasIt = false;
            break;
          }
        }
        indexIntoLine = opEndInLine;
      }
      if (!selectionAllHasIt)
      {
        break;
      }
    }

    if (selectionAllHasIt)
    {
      documentAttributeManager.setAttributesOnRange(rep.selStart, rep.selEnd, [
        [attributeName, '']
      ]);
    }
    else
    {
      documentAttributeManager.setAttributesOnRange(rep.selStart, rep.selEnd, [
        [attributeName, 'true']
      ]);
    }
  }
  editorInfo.ace_toggleAttributeOnSelection = toggleAttributeOnSelection;

  function performDocumentReplaceSelection(newText)
  {
    if (!(rep.selStart && rep.selEnd)) return;
    performDocumentReplaceRange(rep.selStart, rep.selEnd, newText);
  }

  // Change the abstract representation of the document to have a different set of lines.
  // Must be called after rep.alltext is set.


  function doRepLineSplice(startLine, deleteCount, newLineEntries)
  {

    _.each(newLineEntries, function(entry)
    {
      entry.width = entry.text.length + 1;
    });

    var startOldChar = rep.lines.offsetOfIndex(startLine);
    var endOldChar = rep.lines.offsetOfIndex(startLine + deleteCount);

    var oldRegionStart = rep.lines.offsetOfIndex(startLine);
    var oldRegionEnd = rep.lines.offsetOfIndex(startLine + deleteCount);
    rep.lines.splice(startLine, deleteCount, newLineEntries);
    currentCallStack.docTextChanged = true;
    currentCallStack.repChanged = true;
    var newRegionEnd = rep.lines.offsetOfIndex(startLine + newLineEntries.length);

    var newText = _.map(newLineEntries, function(e)
    {
      return e.text + '\n';
    }).join('');

    rep.alltext = rep.alltext.substring(0, startOldChar) + newText + rep.alltext.substring(endOldChar, rep.alltext.length);

    //var newTotalLength = rep.alltext.length;
    //rep.lexer.updateBuffer(rep.alltext, oldRegionStart, oldRegionEnd - oldRegionStart,
    //newRegionEnd - oldRegionStart);
  }

  function doIncorpLineSplice(startLine, deleteCount, newLineEntries, lineAttribs, hints)
  {

    var startOldChar = rep.lines.offsetOfIndex(startLine);
    var endOldChar = rep.lines.offsetOfIndex(startLine + deleteCount);

    var oldRegionStart = rep.lines.offsetOfIndex(startLine);

    var selStartHintChar, selEndHintChar;
    if (hints && hints.selStart)
    {
      selStartHintChar = rep.lines.offsetOfIndex(hints.selStart[0]) + hints.selStart[1] - oldRegionStart;
    }
    if (hints && hints.selEnd)
    {
      selEndHintChar = rep.lines.offsetOfIndex(hints.selEnd[0]) + hints.selEnd[1] - oldRegionStart;
    }

    var newText = _.map(newLineEntries, function(e)
    {
      return e.text + '\n';
    }).join('');
    var oldText = rep.alltext.substring(startOldChar, endOldChar);
    var oldAttribs = rep.alines.slice(startLine, startLine + deleteCount).join('');
    var newAttribs = lineAttribs.join('|1+1') + '|1+1'; // not valid in a changeset
    var analysis = analyzeChange(oldText, newText, oldAttribs, newAttribs, selStartHintChar, selEndHintChar);
    var commonStart = analysis[0];
    var commonEnd = analysis[1];
    var shortOldText = oldText.substring(commonStart, oldText.length - commonEnd);
    var shortNewText = newText.substring(commonStart, newText.length - commonEnd);
    var spliceStart = startOldChar + commonStart;
    var spliceEnd = endOldChar - commonEnd;
    var shiftFinalNewlineToBeforeNewText = false;

    // adjust the splice to not involve the final newline of the document;
    // be very defensive
    if (shortOldText.charAt(shortOldText.length - 1) == '\n' && shortNewText.charAt(shortNewText.length - 1) == '\n')
    {
      // replacing text that ends in newline with text that also ends in newline
      // (still, after analysis, somehow)
      shortOldText = shortOldText.slice(0, -1);
      shortNewText = shortNewText.slice(0, -1);
      spliceEnd--;
      commonEnd++;
    }
    if (shortOldText.length === 0 && spliceStart == rep.alltext.length && shortNewText.length > 0)
    {
      // inserting after final newline, bad
      spliceStart--;
      spliceEnd--;
      shortNewText = '\n' + shortNewText.slice(0, -1);
      shiftFinalNewlineToBeforeNewText = true;
    }
    if (spliceEnd == rep.alltext.length && shortOldText.length > 0 && shortNewText.length === 0)
    {
      // deletion at end of rep.alltext
      if (rep.alltext.charAt(spliceStart - 1) == '\n')
      {
        // (if not then what the heck?  it will definitely lead
        // to a rep.alltext without a final newline)
        spliceStart--;
        spliceEnd--;
      }
    }

    if (!(shortOldText.length === 0 && shortNewText.length === 0))
    {
      var oldDocText = rep.alltext;
      var oldLen = oldDocText.length;

      var spliceStartLine = rep.lines.indexOfOffset(spliceStart);
      var spliceStartLineStart = rep.lines.offsetOfIndex(spliceStartLine);

      var startBuilder = function()
      {
        var builder = Changeset.builder(oldLen);
        builder.keep(spliceStartLineStart, spliceStartLine);
        builder.keep(spliceStart - spliceStartLineStart);
        return builder;
      };

      var eachAttribRun = function(attribs, func /*(startInNewText, endInNewText, attribs)*/ )
      {
        var attribsIter = Changeset.opIterator(attribs);
        var textIndex = 0;
        var newTextStart = commonStart;
        var newTextEnd = newText.length - commonEnd - (shiftFinalNewlineToBeforeNewText ? 1 : 0);
        while (attribsIter.hasNext())
        {
          var op = attribsIter.next();
          var nextIndex = textIndex + op.chars;
          if (!(nextIndex <= newTextStart || textIndex >= newTextEnd))
          {
            func(Math.max(newTextStart, textIndex), Math.min(newTextEnd, nextIndex), op.attribs);
          }
          textIndex = nextIndex;
        }
      };

      var justApplyStyles = (shortNewText == shortOldText);
      var theChangeset;

      if (justApplyStyles)
      {
        // create changeset that clears the incorporated styles on
        // the existing text.  we compose this with the
        // changeset the applies the styles found in the DOM.
        // This allows us to incorporate, e.g., Safari's native "unbold".
        var incorpedAttribClearer = cachedStrFunc(function(oldAtts)
        {
          return Changeset.mapAttribNumbers(oldAtts, function(n)
          {
            var k = rep.apool.getAttribKey(n);
            if (isStyleAttribute(k))
            {
              return rep.apool.putAttrib([k, '']);
            }
            return false;
          });
        });

        var builder1 = startBuilder();
        if (shiftFinalNewlineToBeforeNewText)
        {
          builder1.keep(1, 1);
        }
        eachAttribRun(oldAttribs, function(start, end, attribs)
        {
          builder1.keepText(newText.substring(start, end), incorpedAttribClearer(attribs));
        });
        var clearer = builder1.toString();

        var builder2 = startBuilder();
        if (shiftFinalNewlineToBeforeNewText)
        {
          builder2.keep(1, 1);
        }
        eachAttribRun(newAttribs, function(start, end, attribs)
        {
          builder2.keepText(newText.substring(start, end), attribs);
        });
        var styler = builder2.toString();

        theChangeset = Changeset.compose(clearer, styler, rep.apool);
      }
      else
      {
        var builder = startBuilder();

        var spliceEndLine = rep.lines.indexOfOffset(spliceEnd);
        var spliceEndLineStart = rep.lines.offsetOfIndex(spliceEndLine);
        if (spliceEndLineStart > spliceStart)
        {
          builder.remove(spliceEndLineStart - spliceStart, spliceEndLine - spliceStartLine);
          builder.remove(spliceEnd - spliceEndLineStart);
        }
        else
        {
          builder.remove(spliceEnd - spliceStart);
        }

        var isNewTextMultiauthor = false;
        var authorAtt = Changeset.makeAttribsString('+', (thisAuthor ? [
          ['author', thisAuthor]
        ] : []), rep.apool);
        var authorizer = cachedStrFunc(function(oldAtts)
        {
          if (isNewTextMultiauthor)
          {
            // prefer colors from DOM
            return Changeset.composeAttributes(authorAtt, oldAtts, true, rep.apool);
          }
          else
          {
            // use this author's color
            return Changeset.composeAttributes(oldAtts, authorAtt, true, rep.apool);
          }
        });

        var foundDomAuthor = '';
        eachAttribRun(newAttribs, function(start, end, attribs)
        {
          var a = Changeset.attribsAttributeValue(attribs, 'author', rep.apool);
          if (a && a != foundDomAuthor)
          {
            if (!foundDomAuthor)
            {
              foundDomAuthor = a;
            }
            else
            {
              isNewTextMultiauthor = true; // multiple authors in DOM!
            }
          }
        });

        if (shiftFinalNewlineToBeforeNewText)
        {
          builder.insert('\n', authorizer(''));
        }

        eachAttribRun(newAttribs, function(start, end, attribs)
        {
          builder.insert(newText.substring(start, end), authorizer(attribs));
        });
        theChangeset = builder.toString();
      }

      //dmesg(htmlPrettyEscape(theChangeset));
      doRepApplyChangeset(theChangeset);
    }

    // do this no matter what, because we need to get the right
    // line keys into the rep.
    doRepLineSplice(startLine, deleteCount, newLineEntries);

    checkALines();
  }

  function cachedStrFunc(func)
  {
    var cache = {};
    return function(s)
    {
      if (!cache[s])
      {
        cache[s] = func(s);
      }
      return cache[s];
    };
  }

  function analyzeChange(oldText, newText, oldAttribs, newAttribs, optSelStartHint, optSelEndHint)
  {
    function incorpedAttribFilter(anum)
    {
      return isStyleAttribute(rep.apool.getAttribKey(anum));
    }

    function attribRuns(attribs)
    {
      var lengs = [];
      var atts = [];
      var iter = Changeset.opIterator(attribs);
      while (iter.hasNext())
      {
        var op = iter.next();
        lengs.push(op.chars);
        atts.push(op.attribs);
      }
      return [lengs, atts];
    }

    function attribIterator(runs, backward)
    {
      var lengs = runs[0];
      var atts = runs[1];
      var i = (backward ? lengs.length - 1 : 0);
      var j = 0;
      return function next()
      {
        while (j >= lengs[i])
        {
          if (backward) i--;
          else i++;
          j = 0;
        }
        var a = atts[i];
        j++;
        return a;
      };
    }

    var oldLen = oldText.length;
    var newLen = newText.length;
    var minLen = Math.min(oldLen, newLen);

    var oldARuns = attribRuns(Changeset.filterAttribNumbers(oldAttribs, incorpedAttribFilter));
    var newARuns = attribRuns(Changeset.filterAttribNumbers(newAttribs, incorpedAttribFilter));

    var commonStart = 0;
    var oldStartIter = attribIterator(oldARuns, false);
    var newStartIter = attribIterator(newARuns, false);
    while (commonStart < minLen)
    {
      if (oldText.charAt(commonStart) == newText.charAt(commonStart) && oldStartIter() == newStartIter())
      {
        commonStart++;
      }
      else break;
    }

    var commonEnd = 0;
    var oldEndIter = attribIterator(oldARuns, true);
    var newEndIter = attribIterator(newARuns, true);
    while (commonEnd < minLen)
    {
      if (commonEnd === 0)
      {
        // assume newline in common
        oldEndIter();
        newEndIter();
        commonEnd++;
      }
      else if (oldText.charAt(oldLen - 1 - commonEnd) == newText.charAt(newLen - 1 - commonEnd) && oldEndIter() == newEndIter())
      {
        commonEnd++;
      }
      else break;
    }

    var hintedCommonEnd = -1;
    if ((typeof optSelEndHint) == "number")
    {
      hintedCommonEnd = newLen - optSelEndHint;
    }


    if (commonStart + commonEnd > oldLen)
    {
      // ambiguous insertion
      var minCommonEnd = oldLen - commonStart;
      var maxCommonEnd = commonEnd;
      if (hintedCommonEnd >= minCommonEnd && hintedCommonEnd <= maxCommonEnd)
      {
        commonEnd = hintedCommonEnd;
      }
      else
      {
        commonEnd = minCommonEnd;
      }
      commonStart = oldLen - commonEnd;
    }
    if (commonStart + commonEnd > newLen)
    {
      // ambiguous deletion
      var minCommonEnd = newLen - commonStart;
      var maxCommonEnd = commonEnd;
      if (hintedCommonEnd >= minCommonEnd && hintedCommonEnd <= maxCommonEnd)
      {
        commonEnd = hintedCommonEnd;
      }
      else
      {
        commonEnd = minCommonEnd;
      }
      commonStart = newLen - commonEnd;
    }

    return [commonStart, commonEnd];
  }

  function equalLineAndChars(a, b)
  {
    if (!a) return !b;
    if (!b) return !a;
    return (a[0] == b[0] && a[1] == b[1]);
  }

  function performSelectionChange(selectStart, selectEnd, focusAtStart)
  {
    if (repSelectionChange(selectStart, selectEnd, focusAtStart))
    {
      currentCallStack.selectionAffected = true;
    }
  }
  editorInfo.ace_performSelectionChange = performSelectionChange;

  // Change the abstract representation of the document to have a different selection.
  // Should not rely on the line representation.  Should not affect the DOM.


  function repSelectionChange(selectStart, selectEnd, focusAtStart)
  {
    focusAtStart = !! focusAtStart;

    var newSelFocusAtStart = (focusAtStart && ((!selectStart) || (!selectEnd) || (selectStart[0] != selectEnd[0]) || (selectStart[1] != selectEnd[1])));

    if ((!equalLineAndChars(rep.selStart, selectStart)) || (!equalLineAndChars(rep.selEnd, selectEnd)) || (rep.selFocusAtStart != newSelFocusAtStart))
    {
      rep.selStart = selectStart;
      rep.selEnd = selectEnd;
      rep.selFocusAtStart = newSelFocusAtStart;
      if (mozillaFakeArrows) mozillaFakeArrows.notifySelectionChanged();
      currentCallStack.repChanged = true;

      return true;
      //console.log("selStart: %o, selEnd: %o, focusAtStart: %s", rep.selStart, rep.selEnd,
      //String(!!rep.selFocusAtStart));
    }
    return false;
    //console.log("%o %o %s", rep.selStart, rep.selEnd, rep.selFocusAtStart);
  }

  function doCreateDomLine(nonEmpty)
  {
    if (browser.msie && (!nonEmpty))
    {
      var result = {
        node: null,
        appendSpan: noop,
        prepareForAdd: noop,
        notifyAdded: noop,
        clearSpans: noop,
        finishUpdate: noop,
        lineMarker: 0
      };

      var lineElem = doc.createElement("div");
      result.node = lineElem;

      result.notifyAdded = function()
      {
        // magic -- settng an empty div's innerHTML to the empty string
        // keeps it from collapsing.  Apparently innerHTML must be set *after*
        // adding the node to the DOM.
        // Such a div is what IE 6 creates naturally when you make a blank line
        // in a document of divs.  However, when copy-and-pasted the div will
        // contain a space, so we note its emptiness with a property.
        lineElem.innerHTML = " "; // Frist we set a value that isnt blank
        // a primitive-valued property survives copy-and-paste
        setAssoc(lineElem, "shouldBeEmpty", true);
        // an object property doesn't
        setAssoc(lineElem, "unpasted", {});
        lineElem.innerHTML = ""; // Then we make it blank..  New line and no space = Awesome :)
      };
      var lineClass = 'ace-line';
      result.appendSpan = function(txt, cls)
      {
        if ((!txt) && cls)
        {
          // gain a whole-line style (currently to show insertion point in CSS)
          lineClass = domline.addToLineClass(lineClass, cls);
        }
        // otherwise, ignore appendSpan, this is an empty line
      };
      result.clearSpans = function()
      {
        lineClass = ''; // non-null to cause update
      };

      var writeClass = function()
      {
        if (lineClass !== null) lineElem.className = lineClass;
      };
      
      result.prepareForAdd = writeClass;
      result.finishUpdate = writeClass;
      result.getInnerHTML = function()
      {
        return "";
      };

      return result;
    }
    else
    {
      return domline.createDomLine(nonEmpty, doesWrap, browser, doc);
    }
  }

  function textify(str)
  {
    return str.replace(/[\n\r ]/g, ' ').replace(/\xa0/g, ' ').replace(/\t/g, '        ');
  }

  var _blockElems = {
    "div": 1,
    "p": 1,
    "pre": 1,
    "li": 1,
    "ol": 1,
    "ul": 1
  };

  _.each(hooks.callAll('aceRegisterBlockElements'), function(element){
      _blockElems[element] = 1;
  });

  function isBlockElement(n)
  {
    return !!_blockElems[(n.tagName || "").toLowerCase()];
  }

  function getDirtyRanges()
  {
    // based on observedChanges, return a list of ranges of original lines
    // that need to be removed or replaced with new user content to incorporate
    // the user's changes into the line representation.  ranges may be zero-length,
    // indicating inserted content.  for example, [0,0] means content was inserted
    // at the top of the document, while [3,4] means line 3 was deleted, modified,
    // or replaced with one or more new lines of content. ranges do not touch.
    var p = PROFILER("getDirtyRanges", false);
    p.forIndices = 0;
    p.consecutives = 0;
    p.corrections = 0;

    var cleanNodeForIndexCache = {};
    var N = rep.lines.length(); // old number of lines


    function cleanNodeForIndex(i)
    {
      // if line (i) in the un-updated line representation maps to a clean node
      // in the document, return that node.
      // if (i) is out of bounds, return true. else return false.
      if (cleanNodeForIndexCache[i] === undefined)
      {
        p.forIndices++;
        var result;
        if (i < 0 || i >= N)
        {
          result = true; // truthy, but no actual node
        }
        else
        {
          var key = rep.lines.atIndex(i).key;
          result = (getCleanNodeByKey(key) || false);
        }
        cleanNodeForIndexCache[i] = result;
      }
      return cleanNodeForIndexCache[i];
    }
    var isConsecutiveCache = {};

    function isConsecutive(i)
    {
      if (isConsecutiveCache[i] === undefined)
      {
        p.consecutives++;
        isConsecutiveCache[i] = (function()
        {
          // returns whether line (i) and line (i-1), assumed to be map to clean DOM nodes,
          // or document boundaries, are consecutive in the changed DOM
          var a = cleanNodeForIndex(i - 1);
          var b = cleanNodeForIndex(i);
          if ((!a) || (!b)) return false; // violates precondition
          if ((a === true) && (b === true)) return !root.firstChild;
          if ((a === true) && b.previousSibling) return false;
          if ((b === true) && a.nextSibling) return false;
          if ((a === true) || (b === true)) return true;
          return a.nextSibling == b;
        })();
      }
      return isConsecutiveCache[i];
    }

    function isClean(i)
    {
      // returns whether line (i) in the un-updated representation maps to a clean node,
      // or is outside the bounds of the document
      return !!cleanNodeForIndex(i);
    }
    // list of pairs, each representing a range of lines that is clean and consecutive
    // in the changed DOM.  lines (-1) and (N) are always clean, but may or may not
    // be consecutive with lines in the document.  pairs are in sorted order.
    var cleanRanges = [
      [-1, N + 1]
    ];

    function rangeForLine(i)
    {
      // returns index of cleanRange containing i, or -1 if none
      var answer = -1;
      _.each(cleanRanges ,function(r, idx)
      {
        if (i >= r[1]) return false; // keep looking
        if (i < r[0]) return true; // not found, stop looking
        answer = idx;
        return true; // found, stop looking
      });
      return answer;
    }

    function removeLineFromRange(rng, line)
    {
      // rng is index into cleanRanges, line is line number
      // precond: line is in rng
      var a = cleanRanges[rng][0];
      var b = cleanRanges[rng][1];
      if ((a + 1) == b) cleanRanges.splice(rng, 1);
      else if (line == a) cleanRanges[rng][0]++;
      else if (line == (b - 1)) cleanRanges[rng][1]--;
      else cleanRanges.splice(rng, 1, [a, line], [line + 1, b]);
    }

    function splitRange(rng, pt)
    {
      // precond: pt splits cleanRanges[rng] into two non-empty ranges
      var a = cleanRanges[rng][0];
      var b = cleanRanges[rng][1];
      cleanRanges.splice(rng, 1, [a, pt], [pt, b]);
    }
    var correctedLines = {};

    function correctlyAssignLine(line)
    {
      if (correctedLines[line]) return true;
      p.corrections++;
      correctedLines[line] = true;
      // "line" is an index of a line in the un-updated rep.
      // returns whether line was already correctly assigned (i.e. correctly
      // clean or dirty, according to cleanRanges, and if clean, correctly
      // attached or not attached (i.e. in the same range as) the prev and next lines).
      //console.log("correctly assigning: %d", line);
      var rng = rangeForLine(line);
      var lineClean = isClean(line);
      if (rng < 0)
      {
        if (lineClean)
        {
          console.debug("somehow lost clean line");
        }
        return true;
      }
      if (!lineClean)
      {
        // a clean-range includes this dirty line, fix it
        removeLineFromRange(rng, line);
        return false;
      }
      else
      {
        // line is clean, but could be wrongly connected to a clean line
        // above or below
        var a = cleanRanges[rng][0];
        var b = cleanRanges[rng][1];
        var didSomething = false;
        // we'll leave non-clean adjacent nodes in the clean range for the caller to
        // detect and deal with.  we deal with whether the range should be split
        // just above or just below this line.
        if (a < line && isClean(line - 1) && !isConsecutive(line))
        {
          splitRange(rng, line);
          didSomething = true;
        }
        if (b > (line + 1) && isClean(line + 1) && !isConsecutive(line + 1))
        {
          splitRange(rng, line + 1);
          didSomething = true;
        }
        return !didSomething;
      }
    }

    function detectChangesAroundLine(line, reqInARow)
    {
      // make sure cleanRanges is correct about line number "line" and the surrounding
      // lines; only stops checking at end of document or after no changes need
      // making for several consecutive lines. note that iteration is over old lines,
      // so this operation takes time proportional to the number of old lines
      // that are changed or missing, not the number of new lines inserted.
      var correctInARow = 0;
      var currentIndex = line;
      while (correctInARow < reqInARow && currentIndex >= 0)
      {
        if (correctlyAssignLine(currentIndex))
        {
          correctInARow++;
        }
        else correctInARow = 0;
        currentIndex--;
      }
      correctInARow = 0;
      currentIndex = line;
      while (correctInARow < reqInARow && currentIndex < N)
      {
        if (correctlyAssignLine(currentIndex))
        {
          correctInARow++;
        }
        else correctInARow = 0;
        currentIndex++;
      }
    }

    if (N === 0)
    {
      p.cancel();
      if (!isConsecutive(0))
      {
        splitRange(0, 0);
      }
    }
    else
    {
      p.mark("topbot");
      detectChangesAroundLine(0, 1);
      detectChangesAroundLine(N - 1, 1);

      p.mark("obs");
      //console.log("observedChanges: "+toSource(observedChanges));
      for (var k in observedChanges.cleanNodesNearChanges)
      {
        var key = k.substring(1);
        if (rep.lines.containsKey(key))
        {
          var line = rep.lines.indexOfKey(key);
          detectChangesAroundLine(line, 2);
        }
      }
      p.mark("stats&calc");
      p.literal(p.forIndices, "byidx");
      p.literal(p.consecutives, "cons");
      p.literal(p.corrections, "corr");
    }

    var dirtyRanges = [];
    for (var r = 0; r < cleanRanges.length - 1; r++)
    {
      dirtyRanges.push([cleanRanges[r][1], cleanRanges[r + 1][0]]);
    }

    p.end();

    return dirtyRanges;
  }

  function markNodeClean(n)
  {
    // clean nodes have knownHTML that matches their innerHTML
    var dirtiness = {};
    dirtiness.nodeId = uniqueId(n);
    dirtiness.knownHTML = n.innerHTML;
    if (browser.msie)
    {
      // adding a space to an "empty" div in IE designMode doesn't
      // change the innerHTML of the div's parent; also, other
      // browsers don't support innerText
      dirtiness.knownText = n.innerText;
    }
    setAssoc(n, "dirtiness", dirtiness);
  }

  function isNodeDirty(n)
  {
    var p = PROFILER("cleanCheck", false);
    if (n.parentNode != root) return true;
    var data = getAssoc(n, "dirtiness");
    if (!data) return true;
    if (n.id !== data.nodeId) return true;
    if (browser.msie)
    {
      if (n.innerText !== data.knownText) return true;
    }
    if (n.innerHTML !== data.knownHTML) return true;
    p.end();
    return false;
  }

  function getLineEntryTopBottom(entry, destObj)
  {
    var dom = entry.lineNode;
    var top = dom.offsetTop;
    var height = dom.offsetHeight;
    var obj = (destObj || {});
    obj.top = top;
    obj.bottom = (top + height);
    return obj;
  }

  function getViewPortTopBottom()
  {
    var theTop = getScrollY();
    var doc = outerWin.document;
    var height = doc.documentElement.clientHeight;
    return {
      top: theTop,
      bottom: (theTop + height)
    };
  }

  function getVisibleLineRange()
  {
    var viewport = getViewPortTopBottom();
    //console.log("viewport top/bottom: %o", viewport);
    var obj = {};
    var start = rep.lines.search(function(e)
    {
      return getLineEntryTopBottom(e, obj).bottom > viewport.top;
    });
    var end = rep.lines.search(function(e)
    {
      return getLineEntryTopBottom(e, obj).top >= viewport.bottom;
    });
    if (end < start) end = start; // unlikely
    //console.log(start+","+end);
    return [start, end];
  }

  function getVisibleCharRange()
  {
    var lineRange = getVisibleLineRange();
    return [rep.lines.offsetOfIndex(lineRange[0]), rep.lines.offsetOfIndex(lineRange[1])];
  }

  function handleClick(evt)
  {
    inCallStackIfNecessary("handleClick", function()
    {
      idleWorkTimer.atMost(200);
    });

    function isLink(n)
    {
      return (n.tagName || '').toLowerCase() == "a" && n.href;
    }
    
    // only want to catch left-click
    if ((!evt.ctrlKey) && (evt.button != 2) && (evt.button != 3))
    {
      // find A tag with HREF
      var n = evt.target;
      while (n && n.parentNode && !isLink(n))
      {
        n = n.parentNode;
      }
      if (n && isLink(n))
      {
        try
        {
          var newWindow = window.open(n.href, '_blank');
          newWindow.focus();
        }
        catch (e)
        {
          // absorb "user canceled" error in IE for certain prompts
        }
        evt.preventDefault();
      }
    }
    //hide the dropdownso
    if(window.parent.parent.padeditbar){ // required in case its in an iframe should probably use parent..  See Issue 327 https://github.com/Pita/etherpad-lite/issues/327
      window.parent.parent.padeditbar.toggleDropDown("none");
    }
  }

  function doReturnKey()
  {
    if (!(rep.selStart && rep.selEnd))
    {
      return;
    }
    
    var lineNum = rep.selStart[0];
    var listType = getLineListType(lineNum);

    if (listType)
    {
      var text = rep.lines.atIndex(lineNum).text;
      listType = /([a-z]+)([12345678])/.exec(listType);
      var type  = listType[1];
      var level = Number(listType[2]);
      
      //detect empty list item; exclude indentation
      if(text === '*' && type !== "indent")
      {
        //if not already on the highest level
        if(level > 1)
        {
          setLineListType(lineNum, type+(level-1));//automatically decrease the level
        }
        else
        {
          setLineListType(lineNum, '');//remove the list
          renumberList(lineNum + 1);//trigger renumbering of list that may be right after
        }
      }
      else if (lineNum + 1 < rep.lines.length())
      {
        performDocumentReplaceSelection('\n');
        setLineListType(lineNum + 1, type+level);
      }
    }
    else
    {
      performDocumentReplaceSelection('\n');
      handleReturnIndentation();
    }
  }

  function doIndentOutdent(isOut)
  {
    if (!(rep.selStart && rep.selEnd) ||
        ((rep.selStart[0] == rep.selEnd[0]) && (rep.selStart[1] == rep.selEnd[1]) &&  rep.selEnd[1] > 1))
    {
      return false;
    }

    var firstLine, lastLine;
    firstLine = rep.selStart[0];
    lastLine = Math.max(firstLine, rep.selEnd[0] - ((rep.selEnd[1] === 0) ? 1 : 0));

    var mods = [];
    for (var n = firstLine; n <= lastLine; n++)
    {
      var listType = getLineListType(n);
      var t = 'indent';
      var level = 0;
      if (listType)
      {
        listType = /([a-z]+)([12345678])/.exec(listType);
        if (listType)
        {
          t = listType[1];
          level = Number(listType[2]);
        }
      }
      var newLevel = Math.max(0, Math.min(MAX_LIST_LEVEL, level + (isOut ? -1 : 1)));
      if (level != newLevel)
      {
        mods.push([n, (newLevel > 0) ? t + newLevel : '']);
      }
    }

    _.each(mods, function(mod){
      setLineListType(mod[0], mod[1]);
    });
    return true;
  }
  editorInfo.ace_doIndentOutdent = doIndentOutdent;

  function doTabKey(shiftDown)
  {
    if (!doIndentOutdent(shiftDown))
    {
      performDocumentReplaceSelection(THE_TAB);
    }
  }

  function doDeleteKey(optEvt)
  {
    var evt = optEvt || {};
    var handled = false;
    if (rep.selStart)
    {
      if (isCaret())
      {
        var lineNum = caretLine();
        var col = caretColumn();
        var lineEntry = rep.lines.atIndex(lineNum);
        var lineText = lineEntry.text;
        var lineMarker = lineEntry.lineMarker;
        if (/^ +$/.exec(lineText.substring(lineMarker, col)))
        {
          var col2 = col - lineMarker;
          var tabSize = THE_TAB.length;
          var toDelete = ((col2 - 1) % tabSize) + 1;
          performDocumentReplaceRange([lineNum, col - toDelete], [lineNum, col], '');
          //scrollSelectionIntoView();
          handled = true;
        }
      }
      if (!handled)
      {
        if (isCaret())
        {
          var theLine = caretLine();
          var lineEntry = rep.lines.atIndex(theLine);
          if (caretColumn() <= lineEntry.lineMarker)
          {
            // delete at beginning of line
            var action = 'delete_newline';
            var prevLineListType = (theLine > 0 ? getLineListType(theLine - 1) : '');
            var thisLineListType = getLineListType(theLine);
            var prevLineEntry = (theLine > 0 && rep.lines.atIndex(theLine - 1));
            var prevLineBlank = (prevLineEntry && prevLineEntry.text.length == prevLineEntry.lineMarker);
            
            var thisLineHasMarker = documentAttributeManager.lineHasMarker(theLine);
            
            if (thisLineListType)
            {
              // this line is a list
              if (prevLineBlank && !prevLineListType)
              {
                // previous line is blank, remove it
                performDocumentReplaceRange([theLine - 1, prevLineEntry.text.length], [theLine, 0], '');
              }
              else
              {
                // delistify
                performDocumentReplaceRange([theLine, 0], [theLine, lineEntry.lineMarker], '');
              }
            }else if (thisLineHasMarker && prevLineEntry){
              // If the line has any attributes assigned, remove them by removing the marker '*'
              performDocumentReplaceRange([theLine -1 , prevLineEntry.text.length], [theLine, lineEntry.lineMarker], '');
            }
            else if (theLine > 0)
            {
              // remove newline
              performDocumentReplaceRange([theLine - 1, prevLineEntry.text.length], [theLine, 0], '');
            }
          }
          else
          {
            var docChar = caretDocChar();
            if (docChar > 0)
            {
              if (evt.metaKey || evt.ctrlKey || evt.altKey)
              {
                // delete as many unicode "letters or digits" in a row as possible;
                // always delete one char, delete further even if that first char
                // isn't actually a word char.
                var deleteBackTo = docChar - 1;
                while (deleteBackTo > lineEntry.lineMarker && isWordChar(rep.alltext.charAt(deleteBackTo - 1)))
                {
                  deleteBackTo--;
                }
                performDocumentReplaceCharRange(deleteBackTo, docChar, '');
              }
              else
              {
                // normal delete
                performDocumentReplaceCharRange(docChar - 1, docChar, '');
              }
            }
          }
        }
        else
        {
          performDocumentReplaceSelection('');
        }
      }
    }
     //if the list has been removed, it is necessary to renumber
    //starting from the *next* line because the list may have been
    //separated. If it returns null, it means that the list was not cut, try
    //from the current one.
    var line = caretLine();
    if(line != -1 && renumberList(line+1) === null)
    {
      renumberList(line);
    }
  }

  // set of "letter or digit" chars is based on section 20.5.16 of the original Java Language Spec
  var REGEX_WORDCHAR = /[\u0030-\u0039\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u1FFF\u3040-\u9FFF\uF900-\uFDFF\uFE70-\uFEFE\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFDC]/;
  var REGEX_SPACE = /\s/;

  function isWordChar(c)
  {
    return !!REGEX_WORDCHAR.exec(c);
  }

  function isSpaceChar(c)
  {
    return !!REGEX_SPACE.exec(c);
  }

  function moveByWordInLine(lineText, initialIndex, forwardNotBack)
  {
    var i = initialIndex;

    function nextChar()
    {
      if (forwardNotBack) return lineText.charAt(i);
      else return lineText.charAt(i - 1);
    }

    function advance()
    {
      if (forwardNotBack) i++;
      else i--;
    }

    function isDone()
    {
      if (forwardNotBack) return i >= lineText.length;
      else return i <= 0;
    }

    // On Mac and Linux, move right moves to end of word and move left moves to start;
    // on Windows, always move to start of word.
    // On Windows, Firefox and IE disagree on whether to stop for punctuation (FF says no).
    if (browser.windows && forwardNotBack)
    {
      while ((!isDone()) && isWordChar(nextChar()))
      {
        advance();
      }
      while ((!isDone()) && !isWordChar(nextChar()))
      {
        advance();
      }
    }
    else
    {
      while ((!isDone()) && !isWordChar(nextChar()))
      {
        advance();
      }
      while ((!isDone()) && isWordChar(nextChar()))
      {
        advance();
      }
    }

    return i;
  }

  function handleKeyEvent(evt)
  {
    // if (DEBUG && window.DONT_INCORP) return;
    if (!isEditable) return;

    var type = evt.type;
    var charCode = evt.charCode;
    var keyCode = evt.keyCode;
    var which = evt.which;

    // prevent ESC key
    if (keyCode == 27)
    {
      evt.preventDefault();
      return;
    }

    //dmesg("keyevent type: "+type+", which: "+which);
    // Don't take action based on modifier keys going up and down.
    // Modifier keys do not generate "keypress" events.
    // 224 is the command-key under Mac Firefox.
    // 91 is the Windows key in IE; it is ASCII for open-bracket but isn't the keycode for that key
    // 20 is capslock in IE.
    var isModKey = ((!charCode) && ((type == "keyup") || (type == "keydown")) && (keyCode == 16 || keyCode == 17 || keyCode == 18 || keyCode == 20 || keyCode == 224 || keyCode == 91));
    if (isModKey) return;

    var specialHandled = false;
    var isTypeForSpecialKey = ((browser.msie || browser.safari) ? (type == "keydown") : (type == "keypress"));
    var isTypeForCmdKey = ((browser.msie || browser.safari) ? (type == "keydown") : (type == "keypress"));

    var stopped = false;

    inCallStackIfNecessary("handleKeyEvent", function()
    {

      if (type == "keypress" || (isTypeForSpecialKey && keyCode == 13 /*return*/ ))
      {
        // in IE, special keys don't send keypress, the keydown does the action
        if (!outsideKeyPress(evt))
        {
          evt.preventDefault();
          stopped = true;
        }
      }
      else if (type == "keydown")
      {
        outsideKeyDown(evt);
      }

      if (!stopped)
      {
        if (isTypeForSpecialKey && keyCode == 8)
        {
          // "delete" key; in mozilla, if we're at the beginning of a line, normalize now,
          // or else deleting a blank line can take two delete presses.
          // --
          // we do deletes completely customly now:
          //  - allows consistent (and better) meta-delete behavior
          //  - normalizing and then allowing default behavior confused IE
          //  - probably eliminates a few minor quirks
          fastIncorp(3);
          evt.preventDefault();
          doDeleteKey(evt);
          specialHandled = true;
        }
        if ((!specialHandled) && isTypeForSpecialKey && keyCode == 13)
        {
          // return key, handle specially;
          // note that in mozilla we need to do an incorporation for proper return behavior anyway.
          fastIncorp(4);
          evt.preventDefault();
          doReturnKey();
          //scrollSelectionIntoView();
          scheduler.setTimeout(function()
          {
            outerWin.scrollBy(-100, 0);
          }, 0);
          specialHandled = true;
        }
        if ((!specialHandled) && isTypeForSpecialKey && keyCode == 9 && !(evt.metaKey || evt.ctrlKey))
        {
          // tab
          fastIncorp(5);
          evt.preventDefault();
          doTabKey(evt.shiftKey);
          //scrollSelectionIntoView();
          specialHandled = true;
        }
        if ((!specialHandled) && isTypeForCmdKey && String.fromCharCode(which).toLowerCase() == "z" && (evt.metaKey || evt.ctrlKey) && !evt.altKey)
        {
          // cmd-Z (undo)
          fastIncorp(6);
          evt.preventDefault();
          if (evt.shiftKey)
          {
            doUndoRedo("redo");
          }
          else
          {
            doUndoRedo("undo");
          }
          specialHandled = true;
        }
        if ((!specialHandled) && isTypeForCmdKey && String.fromCharCode(which).toLowerCase() == "y" && (evt.metaKey || evt.ctrlKey))
        {
          // cmd-Y (redo)
          fastIncorp(10);
          evt.preventDefault();
          doUndoRedo("redo");
          specialHandled = true;
        }
        if ((!specialHandled) && isTypeForCmdKey && String.fromCharCode(which).toLowerCase() == "b" && (evt.metaKey || evt.ctrlKey))
        {
          // cmd-B (bold)
          fastIncorp(13);
          evt.preventDefault();
          toggleAttributeOnSelection('bold');
          specialHandled = true;
        }
        if ((!specialHandled) && isTypeForCmdKey && String.fromCharCode(which).toLowerCase() == "i" && (evt.metaKey || evt.ctrlKey))
        {
          // cmd-I (italic)
          fastIncorp(14);
          evt.preventDefault();
          toggleAttributeOnSelection('italic');
          specialHandled = true;
        }
        if ((!specialHandled) && isTypeForCmdKey && String.fromCharCode(which).toLowerCase() == "u" && (evt.metaKey || evt.ctrlKey))
        {
          // cmd-U (underline)
          fastIncorp(15);
          evt.preventDefault();
          toggleAttributeOnSelection('underline');
          specialHandled = true;
        }
        if ((!specialHandled) && isTypeForCmdKey && String.fromCharCode(which).toLowerCase() == "h" && (evt.ctrlKey))
        {
          // cmd-H (backspace)
          fastIncorp(20);
          evt.preventDefault();
          doDeleteKey();
          specialHandled = true;
        }

        if (mozillaFakeArrows && mozillaFakeArrows.handleKeyEvent(evt))
        {
          evt.preventDefault();
          specialHandled = true;
        }
      }

      if (type == "keydown")
      {
        idleWorkTimer.atLeast(500);
      }
      else if (type == "keypress")
      {
        if ((!specialHandled) && false /*parenModule.shouldNormalizeOnChar(charCode)*/)
        {
          idleWorkTimer.atMost(0);
        }
        else
        {
          idleWorkTimer.atLeast(500);
        }
      }
      else if (type == "keyup")
      {
        var wait = 200;
        idleWorkTimer.atLeast(wait);
        idleWorkTimer.atMost(wait);
      }

      // Is part of multi-keystroke international character on Firefox Mac
      var isFirefoxHalfCharacter = (browser.mozilla && evt.altKey && charCode === 0 && keyCode === 0);

      // Is part of multi-keystroke international character on Safari Mac
      var isSafariHalfCharacter = (browser.safari && evt.altKey && keyCode == 229);

      if (thisKeyDoesntTriggerNormalize || isFirefoxHalfCharacter || isSafariHalfCharacter)
      {
        idleWorkTimer.atLeast(3000); // give user time to type
        // if this is a keydown, e.g., the keyup shouldn't trigger a normalize
        thisKeyDoesntTriggerNormalize = true;
      }

      if ((!specialHandled) && (!thisKeyDoesntTriggerNormalize) && (!window.parent.parent.inInternationalComposition))
      {
        if (type != "keyup" || !incorpIfQuick())
        {
          observeChangesAroundSelection();
        }
      }

      if (type == "keyup")
      {
        thisKeyDoesntTriggerNormalize = false;
      }
    });
  }

  var thisKeyDoesntTriggerNormalize = false;

  function doUndoRedo(which)
  {
    // precond: normalized DOM
    if (undoModule.enabled)
    {
      var whichMethod;
      if (which == "undo") whichMethod = 'performUndo';
      if (which == "redo") whichMethod = 'performRedo';
      if (whichMethod)
      {
        var oldEventType = currentCallStack.editEvent.eventType;
        currentCallStack.startNewEvent(which);
        undoModule[whichMethod](function(backset, selectionInfo)
        {
          if (backset)
          {
            performDocumentApplyChangeset(backset);
          }
          if (selectionInfo)
          {
            performSelectionChange(lineAndColumnFromChar(selectionInfo.selStart), lineAndColumnFromChar(selectionInfo.selEnd), selectionInfo.selFocusAtStart);
          }
          var oldEvent = currentCallStack.startNewEvent(oldEventType, true);
          return oldEvent;
        });
      }
    }
  }
  editorInfo.ace_doUndoRedo = doUndoRedo;

  function updateBrowserSelectionFromRep()
  {
    // requires normalized DOM!
    var selStart = rep.selStart,
        selEnd = rep.selEnd;

    if (!(selStart && selEnd))
    {
      setSelection(null);
      return;
    }

    var selection = {};

    var ss = [selStart[0], selStart[1]];
    selection.startPoint = getPointForLineAndChar(ss);

    var se = [selEnd[0], selEnd[1]];
    selection.endPoint = getPointForLineAndChar(se);

    selection.focusAtStart = !! rep.selFocusAtStart;

    setSelection(selection);
  }

  function nodeMaxIndex(nd)
  {
    if (isNodeText(nd)) return nd.nodeValue.length;
    else return 1;
  }

  function hasIESelection()
  {
    var browserSelection;
    try
    {
      browserSelection = doc.selection;
    }
    catch (e)
    {}
    if (!browserSelection) return false;
    var origSelectionRange;
    try
    {
      origSelectionRange = browserSelection.createRange();
    }
    catch (e)
    {}
    if (!origSelectionRange) return false;
    return true;
  }

  function getSelection()
  {
    // returns null, or a structure containing startPoint and endPoint,
    // each of which has node (a magicdom node), index, and maxIndex.  If the node
    // is a text node, maxIndex is the length of the text; else maxIndex is 1.
    // index is between 0 and maxIndex, inclusive.
    if (browser.msie)
    {
      var browserSelection;
      try
      {
        browserSelection = doc.selection;
      }
      catch (e)
      {}
      if (!browserSelection) return null;
      var origSelectionRange;
      try
      {
        origSelectionRange = browserSelection.createRange();
      }
      catch (e)
      {}
      if (!origSelectionRange) return null;
      var selectionParent = origSelectionRange.parentElement();
      if (selectionParent.ownerDocument != doc) return null;

      var newRange = function()
      {
        return doc.body.createTextRange();
      };

      var rangeForElementNode = function(nd)
      {
        var rng = newRange();
        // doesn't work on text nodes
        rng.moveToElementText(nd);
        return rng;
      };

      var pointFromCollapsedRange = function(rng)
      {
        var parNode = rng.parentElement();
        var elemBelow = -1;
        var elemAbove = parNode.childNodes.length;
        var rangeWithin = rangeForElementNode(parNode);

        if (rng.compareEndPoints("StartToStart", rangeWithin) === 0)
        {
          return {
            node: parNode,
            index: 0,
            maxIndex: 1
          };
        }
        else if (rng.compareEndPoints("EndToEnd", rangeWithin) === 0)
        {
          if (isBlockElement(parNode) && parNode.nextSibling)
          {
            // caret after block is not consistent across browsers
            // (same line vs next) so put caret before next node
            return {
              node: parNode.nextSibling,
              index: 0,
              maxIndex: 1
            };
          }
          return {
            node: parNode,
            index: 1,
            maxIndex: 1
          };
        }
        else if (parNode.childNodes.length === 0)
        {
          return {
            node: parNode,
            index: 0,
            maxIndex: 1
          };
        }

        for (var i = 0; i < parNode.childNodes.length; i++)
        {
          var n = parNode.childNodes.item(i);
          if (!isNodeText(n))
          {
            var nodeRange = rangeForElementNode(n);
            var startComp = rng.compareEndPoints("StartToStart", nodeRange);
            var endComp = rng.compareEndPoints("EndToEnd", nodeRange);
            if (startComp >= 0 && endComp <= 0)
            {
              var index = 0;
              if (startComp > 0)
              {
                index = 1;
              }
              return {
                node: n,
                index: index,
                maxIndex: 1
              };
            }
            else if (endComp > 0)
            {
              if (i > elemBelow)
              {
                elemBelow = i;
                rangeWithin.setEndPoint("StartToEnd", nodeRange);
              }
            }
            else if (startComp < 0)
            {
              if (i < elemAbove)
              {
                elemAbove = i;
                rangeWithin.setEndPoint("EndToStart", nodeRange);
              }
            }
          }
        }
        if ((elemAbove - elemBelow) == 1)
        {
          if (elemBelow >= 0)
          {
            return {
              node: parNode.childNodes.item(elemBelow),
              index: 1,
              maxIndex: 1
            };
          }
          else
          {
            return {
              node: parNode.childNodes.item(elemAbove),
              index: 0,
              maxIndex: 1
            };
          }
        }
        var idx = 0;
        var r = rng.duplicate();
        // infinite stateful binary search! call function for values 0 to inf,
        // expecting the answer to be about 40.  return index of smallest
        // true value.
        var indexIntoRange = binarySearchInfinite(40, function(i)
        {
          // the search algorithm whips the caret back and forth,
          // though it has to be moved relatively and may hit
          // the end of the buffer
          var delta = i - idx;
          var moved = Math.abs(r.move("character", -delta));
          // next line is work-around for fact that when moving left, the beginning
          // of a text node is considered to be after the start of the parent element:
          if (r.move("character", -1)) r.move("character", 1);
          if (delta < 0) idx -= moved;
          else idx += moved;
          return (r.compareEndPoints("StartToStart", rangeWithin) <= 0);
        });
        // iterate over consecutive text nodes, point is in one of them
        var textNode = elemBelow + 1;
        var indexLeft = indexIntoRange;
        while (textNode < elemAbove)
        {
          var tn = parNode.childNodes.item(textNode);
          if (indexLeft <= tn.nodeValue.length)
          {
            return {
              node: tn,
              index: indexLeft,
              maxIndex: tn.nodeValue.length
            };
          }
          indexLeft -= tn.nodeValue.length;
          textNode++;
        }
        var tn = parNode.childNodes.item(textNode - 1);
        return {
          node: tn,
          index: tn.nodeValue.length,
          maxIndex: tn.nodeValue.length
        };
      };
      
      var selection = {};
      if (origSelectionRange.compareEndPoints("StartToEnd", origSelectionRange) === 0)
      {
        // collapsed
        var pnt = pointFromCollapsedRange(origSelectionRange);
        selection.startPoint = pnt;
        selection.endPoint = {
          node: pnt.node,
          index: pnt.index,
          maxIndex: pnt.maxIndex
        };
      }
      else
      {
        var start = origSelectionRange.duplicate();
        start.collapse(true);
        var end = origSelectionRange.duplicate();
        end.collapse(false);
        selection.startPoint = pointFromCollapsedRange(start);
        selection.endPoint = pointFromCollapsedRange(end);
/*if ((!selection.startPoint.node.isText) && (!selection.endPoint.node.isText)) {
  console.log(selection.startPoint.node.uniqueId()+","+
    selection.startPoint.index+" / "+
    selection.endPoint.node.uniqueId()+","+
    selection.endPoint.index);
	}*/
      }
      return selection;
    }
    else
    {
      // non-IE browser
      var browserSelection = window.getSelection();
      if (browserSelection && browserSelection.type != "None" && browserSelection.rangeCount !== 0)
      {
        var range = browserSelection.getRangeAt(0);

        function isInBody(n)
        {
          while (n && !(n.tagName && n.tagName.toLowerCase() == "body"))
          {
            n = n.parentNode;
          }
          return !!n;
        }

        function pointFromRangeBound(container, offset)
        {
          if (!isInBody(container))
          {
            // command-click in Firefox selects whole document, HEAD and BODY!
            return {
              node: root,
              index: 0,
              maxIndex: 1
            };
          }
          var n = container;
          var childCount = n.childNodes.length;
          if (isNodeText(n))
          {
            return {
              node: n,
              index: offset,
              maxIndex: n.nodeValue.length
            };
          }
          else if (childCount === 0)
          {
            return {
              node: n,
              index: 0,
              maxIndex: 1
            };
          }
          // treat point between two nodes as BEFORE the second (rather than after the first)
          // if possible; this way point at end of a line block-element is treated as
          // at beginning of next line
          else if (offset == childCount)
          {
            var nd = n.childNodes.item(childCount - 1);
            var max = nodeMaxIndex(nd);
            return {
              node: nd,
              index: max,
              maxIndex: max
            };
          }
          else
          {
            var nd = n.childNodes.item(offset);
            var max = nodeMaxIndex(nd);
            return {
              node: nd,
              index: 0,
              maxIndex: max
            };
          }
        }
        var selection = {};
        selection.startPoint = pointFromRangeBound(range.startContainer, range.startOffset);
        selection.endPoint = pointFromRangeBound(range.endContainer, range.endOffset);
        selection.focusAtStart = (((range.startContainer != range.endContainer) || (range.startOffset != range.endOffset)) && browserSelection.anchorNode && (browserSelection.anchorNode == range.endContainer) && (browserSelection.anchorOffset == range.endOffset));
        return selection;
      }
      else return null;
    }
  }

  function setSelection(selection)
  {
    function copyPoint(pt)
    {
      return {
        node: pt.node,
        index: pt.index,
        maxIndex: pt.maxIndex
      };
    }
    if (browser.msie)
    {
      // Oddly enough, accessing scrollHeight fixes return key handling on IE 8,
      // presumably by forcing some kind of internal DOM update.
      doc.body.scrollHeight;

      function moveToElementText(s, n)
      {
        while (n.firstChild && !isNodeText(n.firstChild))
        {
          n = n.firstChild;
        }
        s.moveToElementText(n);
      }

      function newRange()
      {
        return doc.body.createTextRange();
      }

      function setCollapsedBefore(s, n)
      {
        // s is an IE TextRange, n is a dom node
        if (isNodeText(n))
        {
          // previous node should not also be text, but prevent inf recurs
          if (n.previousSibling && !isNodeText(n.previousSibling))
          {
            setCollapsedAfter(s, n.previousSibling);
          }
          else
          {
            setCollapsedBefore(s, n.parentNode);
          }
        }
        else
        {
          moveToElementText(s, n);
          // work around for issue that caret at beginning of line
          // somehow ends up at end of previous line
          if (s.move('character', 1))
          {
            s.move('character', -1);
          }
          s.collapse(true); // to start
        }
      }

      function setCollapsedAfter(s, n)
      {
        // s is an IE TextRange, n is a magicdom node
        if (isNodeText(n))
        {
          // can't use end of container when no nextSibling (could be on next line),
          // so use previousSibling or start of container and move forward.
          setCollapsedBefore(s, n);
          s.move("character", n.nodeValue.length);
        }
        else
        {
          moveToElementText(s, n);
          s.collapse(false); // to end
        }
      }

      function getPointRange(point)
      {
        var s = newRange();
        var n = point.node;
        if (isNodeText(n))
        {
          setCollapsedBefore(s, n);
          s.move("character", point.index);
        }
        else if (point.index === 0)
        {
          setCollapsedBefore(s, n);
        }
        else
        {
          setCollapsedAfter(s, n);
        }
        return s;
      }

      if (selection)
      {
        if (!hasIESelection())
        {
          return; // don't steal focus
        }

        var startPoint = copyPoint(selection.startPoint);
        var endPoint = copyPoint(selection.endPoint);

        // fix issue where selection can't be extended past end of line
        // with shift-rightarrow or shift-downarrow
        if (endPoint.index == endPoint.maxIndex && endPoint.node.nextSibling)
        {
          endPoint.node = endPoint.node.nextSibling;
          endPoint.index = 0;
          endPoint.maxIndex = nodeMaxIndex(endPoint.node);
        }
        var range = getPointRange(startPoint);
        range.setEndPoint("EndToEnd", getPointRange(endPoint));

        // setting the selection in IE causes everything to scroll
        // so that the selection is visible.  if setting the selection
        // definitely accomplishes nothing, don't do it.


        function isEqualToDocumentSelection(rng)
        {
          var browserSelection;
          try
          {
            browserSelection = doc.selection;
          }
          catch (e)
          {}
          if (!browserSelection) return false;
          var rng2 = browserSelection.createRange();
          if (rng2.parentElement().ownerDocument != doc) return false;
          if (rng.compareEndPoints("StartToStart", rng2) !== 0) return false;
          if (rng.compareEndPoints("EndToEnd", rng2) !== 0) return false;
          return true;
        }
        if (!isEqualToDocumentSelection(range))
        {
          //dmesg(toSource(selection));
          //dmesg(escapeHTML(doc.body.innerHTML));
          range.select();
        }
      }
      else
      {
        try
        {
          doc.selection.empty();
        }
        catch (e)
        {}
      }
    }
    else
    {
      // non-IE browser
      var isCollapsed;

      function pointToRangeBound(pt)
      {
        var p = copyPoint(pt);
        // Make sure Firefox cursor is deep enough; fixes cursor jumping when at top level,
        // and also problem where cut/copy of a whole line selected with fake arrow-keys
        // copies the next line too.
        if (isCollapsed)
        {
          function diveDeep()
          {
            while (p.node.childNodes.length > 0)
            {
              //&& (p.node == root || p.node.parentNode == root)) {
              if (p.index === 0)
              {
                p.node = p.node.firstChild;
                p.maxIndex = nodeMaxIndex(p.node);
              }
              else if (p.index == p.maxIndex)
              {
                p.node = p.node.lastChild;
                p.maxIndex = nodeMaxIndex(p.node);
                p.index = p.maxIndex;
              }
              else break;
            }
          }
          // now fix problem where cursor at end of text node at end of span-like element
          // with background doesn't seem to show up...
          if (isNodeText(p.node) && p.index == p.maxIndex)
          {
            var n = p.node;
            while ((!n.nextSibling) && (n != root) && (n.parentNode != root))
            {
              n = n.parentNode;
            }
            if (n.nextSibling && (!((typeof n.nextSibling.tagName) == "string" && n.nextSibling.tagName.toLowerCase() == "br")) && (n != p.node) && (n != root) && (n.parentNode != root))
            {
              // found a parent, go to next node and dive in
              p.node = n.nextSibling;
              p.maxIndex = nodeMaxIndex(p.node);
              p.index = 0;
              diveDeep();
            }
          }
          // try to make sure insertion point is styled;
          // also fixes other FF problems
          if (!isNodeText(p.node))
          {
            diveDeep();
          }
        }
        if (isNodeText(p.node))
        {
          return {
            container: p.node,
            offset: p.index
          };
        }
        else
        {
          // p.index in {0,1}
          return {
            container: p.node.parentNode,
            offset: childIndex(p.node) + p.index
          };
        }
      }
      var browserSelection = window.getSelection();
      if (browserSelection)
      {
        browserSelection.removeAllRanges();
        if (selection)
        {
          isCollapsed = (selection.startPoint.node === selection.endPoint.node && selection.startPoint.index === selection.endPoint.index);
          var start = pointToRangeBound(selection.startPoint);
          var end = pointToRangeBound(selection.endPoint);

          if ((!isCollapsed) && selection.focusAtStart && browserSelection.collapse && browserSelection.extend)
          {
            // can handle "backwards"-oriented selection, shift-arrow-keys move start
            // of selection
            browserSelection.collapse(end.container, end.offset);
            //console.trace();
            //console.log(htmlPrettyEscape(rep.alltext));
            //console.log("%o %o", rep.selStart, rep.selEnd);
            //console.log("%o %d", start.container, start.offset);
            browserSelection.extend(start.container, start.offset);
          }
          else
          {
            var range = doc.createRange();
            range.setStart(start.container, start.offset);
            range.setEnd(end.container, end.offset);
            browserSelection.removeAllRanges();
            browserSelection.addRange(range);
          }
        }
      }
    }
  }

  function childIndex(n)
  {
    var idx = 0;
    while (n.previousSibling)
    {
      idx++;
      n = n.previousSibling;
    }
    return idx;
  }

  function fixView()
  {
    // calling this method repeatedly should be fast
    if (getInnerWidth() === 0 || getInnerHeight() === 0)
    {
      return;
    }

    function setIfNecessary(obj, prop, value)
    {
      if (obj[prop] != value)
      {
        obj[prop] = value;
      }
    }

    var lineNumberWidth = sideDiv.firstChild.offsetWidth;
    var newSideDivWidth = lineNumberWidth + LINE_NUMBER_PADDING_LEFT;
    if (newSideDivWidth < MIN_LINEDIV_WIDTH) newSideDivWidth = MIN_LINEDIV_WIDTH;
    iframePadLeft = EDIT_BODY_PADDING_LEFT;
    if (hasLineNumbers) iframePadLeft += newSideDivWidth + LINE_NUMBER_PADDING_RIGHT;
    setIfNecessary(iframe.style, "left", iframePadLeft + "px");
    setIfNecessary(sideDiv.style, "width", newSideDivWidth + "px");

    for (var i = 0; i < 2; i++)
    {
      var newHeight = root.clientHeight;
      var newWidth = (browser.msie ? root.createTextRange().boundingWidth : root.clientWidth);
      var viewHeight = getInnerHeight() - iframePadBottom - iframePadTop;
      var viewWidth = getInnerWidth() - iframePadLeft - iframePadRight;
      if (newHeight < viewHeight)
      {
        newHeight = viewHeight;
        if (browser.msie) setIfNecessary(outerWin.document.documentElement.style, 'overflowY', 'auto');
      }
      else
      {
        if (browser.msie) setIfNecessary(outerWin.document.documentElement.style, 'overflowY', 'scroll');
      }
      if (doesWrap)
      {
        newWidth = viewWidth;
      }
      else
      {
        if (newWidth < viewWidth) newWidth = viewWidth;
      }
      setIfNecessary(iframe.style, "height", newHeight + "px");
      setIfNecessary(iframe.style, "width", newWidth + "px");
      setIfNecessary(sideDiv.style, "height", newHeight + "px");
    }
    if (browser.mozilla)
    {
      if (!doesWrap)
      {
        // the body:display:table-cell hack makes mozilla do scrolling
        // correctly by shrinking the <body> to fit around its content,
        // but mozilla won't act on clicks below the body.  We keep the
        // style.height property set to the viewport height (editor height
        // not including scrollbar), so it will never shrink so that part of
        // the editor isn't clickable.
        var body = root;
        var styleHeight = viewHeight + "px";
        setIfNecessary(body.style, "height", styleHeight);
      }
      else
      {
        setIfNecessary(root.style, "height", "");
      }
    }
    // if near edge, scroll to edge
    var scrollX = getScrollX();
    var scrollY = getScrollY();
    var win = outerWin;
    var r = 20;

    enforceEditability();

    $(sideDiv).addClass('sidedivdelayed');
  }

  function getScrollXY()
  {
    var win = outerWin;
    var odoc = outerWin.document;
    if (typeof(win.pageYOffset) == "number")
    {
      return {
        x: win.pageXOffset,
        y: win.pageYOffset
      };
    }
    var docel = odoc.documentElement;
    if (docel && typeof(docel.scrollTop) == "number")
    {
      return {
        x: docel.scrollLeft,
        y: docel.scrollTop
      };
    }
  }

  function getScrollX()
  {
    return getScrollXY().x;
  }

  function getScrollY()
  {
    return getScrollXY().y;
  }

  function setScrollX(x)
  {
    outerWin.scrollTo(x, getScrollY());
  }

  function setScrollY(y)
  {
    outerWin.scrollTo(getScrollX(), y);
  }

  function setScrollXY(x, y)
  {
    outerWin.scrollTo(x, y);
  }

  var _teardownActions = [];

  function teardown()
  {
    _.each(_teardownActions, function(a)
    {
      a();
    });
  }

  function setDesignMode(newVal)
  {
    try
    {
      function setIfNecessary(target, prop, val)
      {
        if (String(target[prop]).toLowerCase() != val)
        {
          target[prop] = val;
          return true;
        }
        return false;
      }
      if (browser.msie || browser.safari)
      {
        setIfNecessary(root, 'contentEditable', (newVal ? 'true' : 'false'));
      }
      else
      {
        var wasSet = setIfNecessary(doc, 'designMode', (newVal ? 'on' : 'off'));
        if (wasSet && newVal && browser.opera)
        {
          // turning on designMode clears event handlers
          bindTheEventHandlers();
        }
      }
      return true;
    }
    catch (e)
    {
      return false;
    }
  }

  var iePastedLines = null;

  function handleIEPaste(evt)
  {
    // Pasting in IE loses blank lines in a way that loses information;
    // "one\n\ntwo\nthree" becomes "<p>one</p><p>two</p><p>three</p>",
    // which becomes "one\ntwo\nthree".  We can get the correct text
    // from the clipboard directly, but we still have to let the paste
    // happen to get the style information.
    var clipText = window.clipboardData && window.clipboardData.getData("Text");
    if (clipText && doc.selection)
    {
      // this "paste" event seems to mess with the selection whether we try to
      // stop it or not, so can't really do document-level manipulation now
      // or in an idle call-stack.  instead, use IE native manipulation
      //function escapeLine(txt) {
      //return processSpaces(escapeHTML(textify(txt)));
      //}
      //var newHTML = map(clipText.replace(/\r/g,'').split('\n'), escapeLine).join('<br>');
      //doc.selection.createRange().pasteHTML(newHTML);
      //evt.preventDefault();
      //iePastedLines = map(clipText.replace(/\r/g,'').split('\n'), textify);
    }
  }

  function handleCompositionEvent(evt)
  {
      window.parent.parent.handleCompositionEvent(evt);
  }

  function bindTheEventHandlers()
  {
    $(document).on("keydown", handleKeyEvent);
    $(document).on("keypress", handleKeyEvent);
    $(document).on("keyup", handleKeyEvent);
    $(document).on("click", handleClick);
    $(root).on("blur", handleBlur);
    if (browser.msie)
    {
      $(document).on("click", handleIEOuterClick);
    }
    if (browser.msie) $(root).on("paste", handleIEPaste);
    // CompositionEvent is not implemented below IE version 8
    if ( !(browser.msie && browser.version < 9) && document.documentElement)
    {
      $(document.documentElement).on("compositionstart", handleCompositionEvent);
      $(document.documentElement).on("compositionend", handleCompositionEvent);
    }
  }

  function handleIEOuterClick(evt)
  {
    if ((evt.target.tagName || '').toLowerCase() != "html")
    {
      return;
    }
    if (!(evt.pageY > root.clientHeight))
    {
      return;
    }

    // click below the body
    inCallStackIfNecessary("handleOuterClick", function()
    {
      // put caret at bottom of doc
      fastIncorp(11);
      if (isCaret())
      { // don't interfere with drag
        var lastLine = rep.lines.length() - 1;
        var lastCol = rep.lines.atIndex(lastLine).text.length;
        performSelectionChange([lastLine, lastCol], [lastLine, lastCol]);
      }
    });
  }

  function getClassArray(elem, optFilter)
  {
    var bodyClasses = [];
    (elem.className || '').replace(/\S+/g, function(c)
    {
      if ((!optFilter) || (optFilter(c)))
      {
        bodyClasses.push(c);
      }
    });
    return bodyClasses;
  }

  function setClassArray(elem, array)
  {
    elem.className = array.join(' ');
  }

  function setClassPresence(elem, className, present)
  {
    if (present) $(elem).addClass(className);
    else $(elem).removeClass(className);
  }

  function setup()
  {
    doc = document; // defined as a var in scope outside
    inCallStackIfNecessary("setup", function()
    {
      var body = doc.getElementById("innerdocbody");
      root = body; // defined as a var in scope outside
      if (browser.mozilla) addClass(root, "mozilla");
      if (browser.safari) addClass(root, "safari");
      if (browser.msie) addClass(root, "msie");
      if (browser.msie)
      {
        // cache CSS background images
        try
        {
          doc.execCommand("BackgroundImageCache", false, true);
        }
        catch (e)
        { /* throws an error in some IE 6 but not others! */
        }
      }
      setClassPresence(root, "authorColors", true);
      setClassPresence(root, "doesWrap", doesWrap);

      initDynamicCSS();

      enforceEditability();

      // set up dom and rep
      while (root.firstChild) root.removeChild(root.firstChild);
      var oneEntry = createDomLineEntry("");
      doRepLineSplice(0, rep.lines.length(), [oneEntry]);
      insertDomLines(null, [oneEntry.domInfo], null);
      rep.alines = Changeset.splitAttributionLines(
      Changeset.makeAttribution("\n"), "\n");

      bindTheEventHandlers();

    });

    scheduler.setTimeout(function()
    {
      parent.readyFunc(); // defined in code that sets up the inner iframe
    }, 0);

    isSetUp = true;
  }

  function focus()
  {
    window.focus();
  }

  function handleBlur(evt)
  {
    if (browser.msie)
    {
      // a fix: in IE, clicking on a control like a button outside the
      // iframe can "blur" the editor, causing it to stop getting
      // events, though typing still affects it(!).
      setSelection(null);
    }
  }

  function getSelectionPointX(point)
  {
    // doesn't work in wrap-mode
    var node = point.node;
    var index = point.index;

    function leftOf(n)
    {
      return n.offsetLeft;
    }

    function rightOf(n)
    {
      return n.offsetLeft + n.offsetWidth;
    }
    if (!isNodeText(node))
    {
      if (index === 0) return leftOf(node);
      else return rightOf(node);
    }
    else
    {
      // we can get bounds of element nodes, so look for those.
      // allow consecutive text nodes for robustness.
      var charsToLeft = index;
      var charsToRight = node.nodeValue.length - index;
      var n;
      for (n = node.previousSibling; n && isNodeText(n); n = n.previousSibling)
      charsToLeft += n.nodeValue;
      var leftEdge = (n ? rightOf(n) : leftOf(node.parentNode));
      for (n = node.nextSibling; n && isNodeText(n); n = n.nextSibling)
      charsToRight += n.nodeValue;
      var rightEdge = (n ? leftOf(n) : rightOf(node.parentNode));
      var frac = (charsToLeft / (charsToLeft + charsToRight));
      var pixLoc = leftEdge + frac * (rightEdge - leftEdge);
      return Math.round(pixLoc);
    }
  }

  function getPageHeight()
  {
    var win = outerWin;
    var odoc = win.document;
    if (win.innerHeight && win.scrollMaxY) return win.innerHeight + win.scrollMaxY;
    else if (odoc.body.scrollHeight > odoc.body.offsetHeight) return odoc.body.scrollHeight;
    else return odoc.body.offsetHeight;
  }

  function getPageWidth()
  {
    var win = outerWin;
    var odoc = win.document;
    if (win.innerWidth && win.scrollMaxX) return win.innerWidth + win.scrollMaxX;
    else if (odoc.body.scrollWidth > odoc.body.offsetWidth) return odoc.body.scrollWidth;
    else return odoc.body.offsetWidth;
  }

  function getInnerHeight()
  {
    var win = outerWin;
    var odoc = win.document;
    var h;
    if (browser.opera) h = win.innerHeight;
    else h = odoc.documentElement.clientHeight;
    if (h) return h;

    // deal with case where iframe is hidden, hope that
    // style.height of iframe container is set in px
    return Number(editorInfo.frame.parentNode.style.height.replace(/[^0-9]/g, '') || 0);
  }

  function getInnerWidth()
  {
    var win = outerWin;
    var odoc = win.document;
    return odoc.documentElement.clientWidth;
  }

  function scrollNodeVerticallyIntoView(node)
  {
    // requires element (non-text) node;
    // if node extends above top of viewport or below bottom of viewport (or top of scrollbar),
    // scroll it the minimum distance needed to be completely in view.
    var win = outerWin;
    var odoc = outerWin.document;
    var distBelowTop = node.offsetTop + iframePadTop - win.scrollY;
    var distAboveBottom = win.scrollY + getInnerHeight() - (node.offsetTop + iframePadTop + node.offsetHeight);

    if (distBelowTop < 0)
    {
      win.scrollBy(0, distBelowTop);
    }
    else if (distAboveBottom < 0)
    {
      win.scrollBy(0, -distAboveBottom);
    }
  }

  function scrollXHorizontallyIntoView(pixelX)
  {
    var win = outerWin;
    var odoc = outerWin.document;
    pixelX += iframePadLeft;
    var distInsideLeft = pixelX - win.scrollX;
    var distInsideRight = win.scrollX + getInnerWidth() - pixelX;
    if (distInsideLeft < 0)
    {
      win.scrollBy(distInsideLeft, 0);
    }
    else if (distInsideRight < 0)
    {
      win.scrollBy(-distInsideRight + 1, 0);
    }
  }

  function scrollSelectionIntoView()
  {
    if (!rep.selStart) return;
    fixView();
    var focusLine = (rep.selFocusAtStart ? rep.selStart[0] : rep.selEnd[0]);
    scrollNodeVerticallyIntoView(rep.lines.atIndex(focusLine).lineNode);
    if (!doesWrap)
    {
      var browserSelection = getSelection();
      if (browserSelection)
      {
        var focusPoint = (browserSelection.focusAtStart ? browserSelection.startPoint : browserSelection.endPoint);
        var selectionPointX = getSelectionPointX(focusPoint);
        scrollXHorizontallyIntoView(selectionPointX);
        fixView();
      }
    }
  }
  
  var listAttributeName = 'list';
  
  function getLineListType(lineNum)
  {
    return documentAttributeManager.getAttributeOnLine(lineNum, listAttributeName)
  }

  function setLineListType(lineNum, listType)
  {
    if(listType == ''){
      documentAttributeManager.removeAttributeOnLine(lineNum, listAttributeName);
    }else{
      documentAttributeManager.setAttributeOnLine(lineNum, listAttributeName, listType);
    }
    
    //if the list has been removed, it is necessary to renumber
    //starting from the *next* line because the list may have been
    //separated. If it returns null, it means that the list was not cut, try
    //from the current one.
    if(renumberList(lineNum+1)==null)
    {
      renumberList(lineNum);
    }
  }
  
  function renumberList(lineNum){
    //1-check we are in a list
    var type = getLineListType(lineNum);
    if(!type)
    {
      return null;
    }
    type = /([a-z]+)[12345678]/.exec(type);
    if(type[1] == "indent")
    {
      return null;
    }
    
    //2-find the first line of the list
    while(lineNum-1 >= 0 && (type=getLineListType(lineNum-1)))
    {
      type = /([a-z]+)[12345678]/.exec(type);
      if(type[1] == "indent")
        break;
      lineNum--;
    }
    
    //3-renumber every list item of the same level from the beginning, level 1
    //IMPORTANT: never skip a level because there imbrication may be arbitrary
    var builder = Changeset.builder(rep.lines.totalWidth());
    loc = [0,0];
    function applyNumberList(line, level)
    {
      //init
      var position = 1;
      var curLevel = level;
      var listType;
      //loop over the lines
      while(listType = getLineListType(line))
      {
        //apply new num
        listType = /([a-z]+)([12345678])/.exec(listType);
        curLevel = Number(listType[2]);
        if(isNaN(curLevel) || listType[0] == "indent")
        {
          return line;
        }
        else if(curLevel == level)
        {
          ChangesetUtils.buildKeepRange(rep, builder, loc, (loc = [line, 0]));
          ChangesetUtils.buildKeepRange(rep, builder, loc, (loc = [line, 1]), [
            ['start', position]
          ], rep.apool);
          
          position++;
          line++;
        }
        else if(curLevel < level)
        {
          return line;//back to parent
        }
        else
        {
          line = applyNumberList(line, level+1);//recursive call
        }
      }
      return line;
    }
    
    applyNumberList(lineNum, 1);
    var cs = builder.toString();
    if (!Changeset.isIdentity(cs))
    {
      performDocumentApplyChangeset(cs);
    }
    
    //4-apply the modifications
    
    
  }
  

  function doInsertList(type)
  {
    if (!(rep.selStart && rep.selEnd))
    {
      return;
    }

    var firstLine, lastLine;
    firstLine = rep.selStart[0];
    lastLine = Math.max(firstLine, rep.selEnd[0] - ((rep.selEnd[1] === 0) ? 1 : 0));

    var allLinesAreList = true;
    for (var n = firstLine; n <= lastLine; n++)
    {
      var listType = getLineListType(n);
      if (!listType || listType.slice(0, type.length) != type)
      {
        allLinesAreList = false;
        break;
      }
    }

    var mods = [];
    for (var n = firstLine; n <= lastLine; n++)
    {
      var t = '';
      var level = 0;
      var listType = /([a-z]+)([12345678])/.exec(getLineListType(n));
      if (listType)
      {
        t = listType[1];
        level = Number(listType[2]);
      }
      var t = getLineListType(n);
      mods.push([n, allLinesAreList ? 'indent' + level : (t ? type + level : type + '1')]);
    }
    
    _.each(mods, function(mod){
      setLineListType(mod[0], mod[1]);
    });
  }
  
  function doInsertUnorderedList(){
    doInsertList('bullet');
  }
  function doInsertOrderedList(){
    doInsertList('number');
  }
  editorInfo.ace_doInsertUnorderedList = doInsertUnorderedList;
  editorInfo.ace_doInsertOrderedList = doInsertOrderedList;

  var mozillaFakeArrows = (browser.mozilla && (function()
  {
    // In Firefox 2, arrow keys are unstable while DOM-manipulating
    // operations are going on.  Specifically, if an operation
    // (computation that ties up the event queue) is going on (in the
    // call-stack of some event, like a timeout) that at some point
    // mutates nodes involved in the selection, then the arrow
    // keypress may (randomly) move the caret to the beginning or end
    // of the document.  If the operation also mutates the selection
    // range, the old selection or the new selection may be used, or
    // neither.
    // As long as the arrow is pressed during the busy operation, it
    // doesn't seem to matter that the keydown and keypress events
    // aren't generated until afterwards, or that the arrow movement
    // can still be stopped (meaning it hasn't been performed yet);
    // Firefox must be preserving some old information about the
    // selection or the DOM from when the key was initially pressed.
    // However, it also doesn't seem to matter when the key was
    // actually pressed relative to the time of the mutation within
    // the prolonged operation.  Also, even in very controlled tests
    // (like a mutation followed by a long period of busyWaiting), the
    // problem shows up often but not every time, with no discernable
    // pattern.  Who knows, it could have something to do with the
    // caret-blinking timer, or DOM changes not being applied
    // immediately.
    // This problem, mercifully, does not show up at all in IE or
    // Safari.  My solution is to have my own, full-featured arrow-key
    // implementation for Firefox.
    // Note that the problem addressed here is potentially very subtle,
    // especially if the operation is quick and is timed to usually happen
    // when the user is idle.
    // features:
    // - 'up' and 'down' arrows preserve column when passing through shorter lines
    // - shift-arrows extend the "focus" point, which may be start or end of range
    // - the focus point is kept horizontally and vertically scrolled into view
    // - arrows without shift cause caret to move to beginning or end of selection (left,right)
    //   or move focus point up or down a line (up,down)
    // - command-(left,right,up,down) on Mac acts like (line-start, line-end, doc-start, doc-end)
    // - takes wrapping into account when doesWrap is true, i.e. up-arrow and down-arrow move
    //   between the virtual lines within a wrapped line; this was difficult, and unfortunately
    //   requires mutating the DOM to get the necessary information
    var savedFocusColumn = 0; // a value of 0 has no effect
    var updatingSelectionNow = false;

    function getVirtualLineView(lineNum)
    {
      var lineNode = rep.lines.atIndex(lineNum).lineNode;
      while (lineNode.firstChild && isBlockElement(lineNode.firstChild))
      {
        lineNode = lineNode.firstChild;
      }
      return makeVirtualLineView(lineNode);
    }

    function markerlessLineAndChar(line, chr)
    {
      return [line, chr - rep.lines.atIndex(line).lineMarker];
    }

    function markerfulLineAndChar(line, chr)
    {
      return [line, chr + rep.lines.atIndex(line).lineMarker];
    }

    return {
      notifySelectionChanged: function()
      {
        if (!updatingSelectionNow)
        {
          savedFocusColumn = 0;
        }
      },
      handleKeyEvent: function(evt)
      {
        // returns "true" if handled
        if (evt.type != "keypress") return false;
        var keyCode = evt.keyCode;
        if (keyCode < 37 || keyCode > 40) return false;
        incorporateUserChanges();

        if (!(rep.selStart && rep.selEnd)) return true;

        // {byWord,toEnd,normal}
        var moveMode = (evt.altKey ? "byWord" : (evt.ctrlKey ? "byWord" : (evt.metaKey ? "toEnd" : "normal")));

        var anchorCaret = markerlessLineAndChar(rep.selStart[0], rep.selStart[1]);
        var focusCaret = markerlessLineAndChar(rep.selEnd[0], rep.selEnd[1]);
        var wasCaret = isCaret();
        if (rep.selFocusAtStart)
        {
          var tmp = anchorCaret;
          anchorCaret = focusCaret;
          focusCaret = tmp;
        }
        var K_UP = 38,
            K_DOWN = 40,
            K_LEFT = 37,
            K_RIGHT = 39;
        var dontMove = false;
        if (wasCaret && !evt.shiftKey)
        {
          // collapse, will mutate both together
          anchorCaret = focusCaret;
        }
        else if ((!wasCaret) && (!evt.shiftKey))
        {
          if (keyCode == K_LEFT)
          {
            // place caret at beginning
            if (rep.selFocusAtStart) anchorCaret = focusCaret;
            else focusCaret = anchorCaret;
            if (moveMode == "normal") dontMove = true;
          }
          else if (keyCode == K_RIGHT)
          {
            // place caret at end
            if (rep.selFocusAtStart) focusCaret = anchorCaret;
            else anchorCaret = focusCaret;
            if (moveMode == "normal") dontMove = true;
          }
          else
          {
            // collapse, will mutate both together
            anchorCaret = focusCaret;
          }
        }
        if (!dontMove)
        {
          function lineLength(i)
          {
            var entry = rep.lines.atIndex(i);
            return entry.text.length - entry.lineMarker;
          }

          function lineText(i)
          {
            var entry = rep.lines.atIndex(i);
            return entry.text.substring(entry.lineMarker);
          }

          if (keyCode == K_UP || keyCode == K_DOWN)
          {
            var up = (keyCode == K_UP);
            var canChangeLines = ((up && focusCaret[0]) || ((!up) && focusCaret[0] < rep.lines.length() - 1));
            var virtualLineView, virtualLineSpot, canChangeVirtualLines = false;
            if (doesWrap)
            {
              virtualLineView = getVirtualLineView(focusCaret[0]);
              virtualLineSpot = virtualLineView.getVLineAndOffsetForChar(focusCaret[1]);
              canChangeVirtualLines = ((up && virtualLineSpot.vline > 0) || ((!up) && virtualLineSpot.vline < (
              virtualLineView.getNumVirtualLines() - 1)));
            }
            var newColByVirtualLineChange;
            if (moveMode == "toEnd")
            {
              if (up)
              {
                focusCaret[0] = 0;
                focusCaret[1] = 0;
              }
              else
              {
                focusCaret[0] = rep.lines.length() - 1;
                focusCaret[1] = lineLength(focusCaret[0]);
              }
            }
            else if (moveMode == "byWord")
            {
              // move by "paragraph", a feature that Firefox lacks but IE and Safari both have
              if (up)
              {
                if (focusCaret[1] === 0 && canChangeLines)
                {
                  focusCaret[0]--;
                  focusCaret[1] = 0;
                }
                else focusCaret[1] = 0;
              }
              else
              {
                var lineLen = lineLength(focusCaret[0]);
                if (browser.windows)
                {
                  if (canChangeLines)
                  {
                    focusCaret[0]++;
                    focusCaret[1] = 0;
                  }
                  else
                  {
                    focusCaret[1] = lineLen;
                  }
                }
                else
                {
                  if (focusCaret[1] == lineLen && canChangeLines)
                  {
                    focusCaret[0]++;
                    focusCaret[1] = lineLength(focusCaret[0]);
                  }
                  else
                  {
                    focusCaret[1] = lineLen;
                  }
                }
              }
              savedFocusColumn = 0;
            }
            else if (canChangeVirtualLines)
            {
              var vline = virtualLineSpot.vline;
              var offset = virtualLineSpot.offset;
              if (up) vline--;
              else vline++;
              if (savedFocusColumn > offset) offset = savedFocusColumn;
              else
              {
                savedFocusColumn = offset;
              }
              var newSpot = virtualLineView.getCharForVLineAndOffset(vline, offset);
              focusCaret[1] = newSpot.lineChar;
            }
            else if (canChangeLines)
            {
              if (up) focusCaret[0]--;
              else focusCaret[0]++;
              var offset = focusCaret[1];
              if (doesWrap)
              {
                offset = virtualLineSpot.offset;
              }
              if (savedFocusColumn > offset) offset = savedFocusColumn;
              else
              {
                savedFocusColumn = offset;
              }
              if (doesWrap)
              {
                var newLineView = getVirtualLineView(focusCaret[0]);
                var vline = (up ? newLineView.getNumVirtualLines() - 1 : 0);
                var newSpot = newLineView.getCharForVLineAndOffset(vline, offset);
                focusCaret[1] = newSpot.lineChar;
              }
              else
              {
                var lineLen = lineLength(focusCaret[0]);
                if (offset > lineLen) offset = lineLen;
                focusCaret[1] = offset;
              }
            }
            else
            {
              if (up) focusCaret[1] = 0;
              else focusCaret[1] = lineLength(focusCaret[0]);
              savedFocusColumn = 0;
            }
          }
          else if (keyCode == K_LEFT || keyCode == K_RIGHT)
          {
            var left = (keyCode == K_LEFT);
            if (left)
            {
              if (moveMode == "toEnd") focusCaret[1] = 0;
              else if (focusCaret[1] > 0)
              {
                if (moveMode == "byWord")
                {
                  focusCaret[1] = moveByWordInLine(lineText(focusCaret[0]), focusCaret[1], false);
                }
                else
                {
                  focusCaret[1]--;
                }
              }
              else if (focusCaret[0] > 0)
              {
                focusCaret[0]--;
                focusCaret[1] = lineLength(focusCaret[0]);
                if (moveMode == "byWord")
                {
                  focusCaret[1] = moveByWordInLine(lineText(focusCaret[0]), focusCaret[1], false);
                }
              }
            }
            else
            {
              var lineLen = lineLength(focusCaret[0]);
              if (moveMode == "toEnd") focusCaret[1] = lineLen;
              else if (focusCaret[1] < lineLen)
              {
                if (moveMode == "byWord")
                {
                  focusCaret[1] = moveByWordInLine(lineText(focusCaret[0]), focusCaret[1], true);
                }
                else
                {
                  focusCaret[1]++;
                }
              }
              else if (focusCaret[0] < rep.lines.length() - 1)
              {
                focusCaret[0]++;
                focusCaret[1] = 0;
                if (moveMode == "byWord")
                {
                  focusCaret[1] = moveByWordInLine(lineText(focusCaret[0]), focusCaret[1], true);
                }
              }
            }
            savedFocusColumn = 0;
          }
        }

        var newSelFocusAtStart = ((focusCaret[0] < anchorCaret[0]) || (focusCaret[0] == anchorCaret[0] && focusCaret[1] < anchorCaret[1]));
        var newSelStart = (newSelFocusAtStart ? focusCaret : anchorCaret);
        var newSelEnd = (newSelFocusAtStart ? anchorCaret : focusCaret);
        updatingSelectionNow = true;
        performSelectionChange(markerfulLineAndChar(newSelStart[0], newSelStart[1]), markerfulLineAndChar(newSelEnd[0], newSelEnd[1]), newSelFocusAtStart);
        updatingSelectionNow = false;
        currentCallStack.userChangedSelection = true;
        return true;
      }
    };
  })());
  
  var lineNumbersShown;
  var sideDivInner;

  function initLineNumbers()
  {
    lineNumbersShown = 1;
    sideDiv.innerHTML = '<table border="0" cellpadding="0" cellspacing="0" align="right">' + '<tr><td id="sidedivinner"><div>1</div></td></tr></table>';
    sideDivInner = outerWin.document.getElementById("sidedivinner");
  }

  function updateLineNumbers()
  {
    var newNumLines = rep.lines.length();
    if (newNumLines < 1) newNumLines = 1;
    //update height of all current line numbers
  
    var a = sideDivInner.firstChild;
    var b = doc.body.firstChild;
    var n = 0;
    
    if (currentCallStack && currentCallStack.domClean)
    {

      while (a && b)
      {
        if(n > lineNumbersShown) //all updated, break
        break;

        var h = (b.clientHeight || b.offsetHeight);
        if (b.nextSibling)
        {
          // when text is zoomed in mozilla, divs have fractional
          // heights (though the properties are always integers)
          // and the line-numbers don't line up unless we pay
          // attention to where the divs are actually placed...
          // (also: padding on TTs/SPANs in IE...)
          h = b.nextSibling.offsetTop - b.offsetTop;
        }
        if (h)
        {
          var hpx = h + "px";
          if (a.style.height != hpx) {
            a.style.height = hpx;
          }
        }
        a = a.nextSibling;
        b = b.nextSibling;
        n++;
      }
    }	
	
    if (newNumLines != lineNumbersShown)
    {
      var container = sideDivInner;
      var odoc = outerWin.document;
      var fragment = odoc.createDocumentFragment();
      while (lineNumbersShown < newNumLines)
      {
        lineNumbersShown++;
        var n = lineNumbersShown;
        var div = odoc.createElement("DIV");	
        //calculate height for new line number
        var h = (b.clientHeight || b.offsetHeight);
        
        if (b.nextSibling)
          h = b.nextSibling.offsetTop - b.offsetTop;
        
        if(h) // apply style to div
          div.style.height = h +"px";
			
        div.appendChild(odoc.createTextNode(String(n)));
        fragment.appendChild(div);
        b = b.nextSibling;
      }
      
      container.appendChild(fragment);
      while (lineNumbersShown > newNumLines)
      {
        container.removeChild(container.lastChild);
        lineNumbersShown--;
      }
    }
  }
  
  
  // Init documentAttributeManager
  documentAttributeManager = new AttributeManager(rep, performDocumentApplyChangeset);
  editorInfo.ace_performDocumentApplyAttributesToRange = function () {
    return documentAttributeManager.setAttributesOnRange.apply(documentAttributeManager, arguments);
  };

  $(document).ready(function(){
    doc = document; // defined as a var in scope outside
    inCallStack("setup", function()
    {
      var body = doc.getElementById("innerdocbody");
      root = body; // defined as a var in scope outside
      if (browser.mozilla) $(root).addClass("mozilla");
      if (browser.safari) $(root).addClass("safari");
      if (browser.msie) $(root).addClass("msie");
      if (browser.msie)
      {
        // cache CSS background images
        try
        {
          doc.execCommand("BackgroundImageCache", false, true);
        }
        catch (e)
        { /* throws an error in some IE 6 but not others! */
        }
      }
      setClassPresence(root, "authorColors", true);
      setClassPresence(root, "doesWrap", doesWrap);

      initDynamicCSS();

      enforceEditability();

      // set up dom and rep
      while (root.firstChild) root.removeChild(root.firstChild);
      var oneEntry = createDomLineEntry("");
      doRepLineSplice(0, rep.lines.length(), [oneEntry]);
      insertDomLines(null, [oneEntry.domInfo], null);
      rep.alines = Changeset.splitAttributionLines(
      Changeset.makeAttribution("\n"), "\n");

      bindTheEventHandlers();

    });
    
    hooks.callAll('aceInitialized', {
      editorInfo: editorInfo,
      rep: rep,
      documentAttributeManager: documentAttributeManager
    });
    
    scheduler.setTimeout(function()
    {
      parent.readyFunc(); // defined in code that sets up the inner iframe
    }, 0);

    isSetUp = true;
  });

}

// Ensure that plugins are loaded before initializing the editor
plugins.ensure(function () {
  var editor = new Ace2Inner();
});