aboutsummaryrefslogtreecommitdiffhomepage
path: root/test/test.lua
blob: 319a7e167b4b0a26a8d118398fec65480bb0e7f5 (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
-- Copyright 2020 Mitchell mitchell.att.foicica.com. See LICENSE.

-- In the past, Scintilla used 0-based indices as opposed to Lua's 1-based
-- indices, so these conversions were needed. Now, they are vestigal.
local function LINE(i) return i end
local function POS(i) return i end
local function INDEX(i) return i end

local _tostring = tostring
-- Overloads tostring() to print more user-friendly output for `assert_equal()`.
function tostring(value)
  if type(value) == 'table' then
    return string.format('{%s}', table.concat(value, ', '))
  elseif type(value) == 'string' then
    return string.format('%q', value)
  else
    return _tostring(value)
  end
end

-- Asserts that values *v1* and *v2* are equal.
-- Tables are compared by value, not by reference.
function assert_equal(v1, v2)
  if v1 == v2 then return end
  if type(v1) == 'table' and type(v2) == 'table' then
    if #v1 == #v2 then
      for k, v in pairs(v1) do if v2[k] ~= v then goto continue end end
      for k, v in pairs(v2) do if v1[k] ~= v then goto continue end end
      return
    end
    ::continue::
  end
  error(string.format('%s ~= %s', v1, v2), 2)
end


-- Asserts that function *f* raises an error whose error message contains string
-- *expected_errmsg*.
-- @param f Function to call.
-- @param expected_errmsg String the error message should contain.
function assert_raises(f, expected_errmsg)
  local ok, errmsg = pcall(f)
  if ok then error('error expected', 2) end
  if expected_errmsg ~= errmsg and
     not tostring(errmsg):find(expected_errmsg, 1, true) then
    error(string.format(
      'error message %q expected, was %q', expected_errmsg, errmsg), 2)
  end
end

local expected_failures = {}
function expected_failure(f) expected_failures[f] = true end
local unstable_tests = {}
function unstable(f) unstable_tests[f] = true end

--------------------------------------------------------------------------------

function test_assert()
  assert_equal(assert(true, 'okay'), true)
  assert_raises(function() assert(false, 'not okay') end, 'not okay')
  assert_raises(function() assert(false, 'not okay: %s', false) end, 'not okay: false')
  assert_raises(function() assert(false, 'not okay: %s') end, 'no value')
  assert_raises(function() assert(false, 1234) end, '1234')
  assert_raises(function() assert(false) end, 'assertion failed!')
end

function test_assert_types()
  function foo(bar, baz, quux)
    assert_type(bar, 'string', 1)
    assert_type(baz, 'boolean/nil', 2)
    assert_type(quux, 'string/table/nil', 3)
    return bar
  end
  assert_equal(foo('bar'), 'bar')
  assert_raises(function() foo(1) end, "bad argument #1 to 'foo' (string expected, got number")
  assert_raises(function() foo('bar', 'baz') end, "bad argument #2 to 'foo' (boolean/nil expected, got string")
  assert_raises(function() foo('bar', true, 1) end, "bad argument #3 to 'foo' (string/table/nil expected, got number")

  function foo(bar) assert_type(bar, string) end
  assert_raises(function() foo(1) end, "bad argument #2 to 'assert_type' (string expected, got table")
  function foo(bar) assert_type(bar, 'string') end
  assert_raises(function() foo(1) end, "bad argument #3 to 'assert_type' (value expected, got nil")
end

function test_events_basic()
  local emitted = false
  local event, handler = 'test_basic', function() emitted = true end
  events.connect(event, handler)
  events.emit(event)
  assert(emitted, 'event not emitted or handled')
  emitted = false
  events.disconnect(event, handler)
  events.emit(event)
  assert(not emitted, 'event still handled')

  assert_raises(function() events.connect(nil) end, 'string expected')
  assert_raises(function() events.connect(event, nil) end, 'function expected')
  assert_raises(function() events.connect(event, function() end, 'bar') end, 'number/nil expected')
  assert_raises(function() events.disconnect() end, 'expected, got nil')
  assert_raises(function() events.disconnect(event, nil) end, 'function expected')
  assert_raises(function() events.emit(nil) end, 'string expected')
end

function test_events_single_handle()
  local count = 0
  local event, handler = 'test_single_handle', function() count = count + 1 end
  events.connect(event, handler)
  events.connect(event, handler) -- should disconnect first
  events.emit(event)
  assert_equal(count, 1)
end

function test_events_insert()
  local foo = {}
  local event = 'test_insert'
  events.connect(event, function() foo[#foo + 1] = 2 end)
  events.connect(event, function() foo[#foo + 1] = 1 end, 1)
  events.emit(event)
  assert_equal(foo, {1, 2})
end

function test_events_short_circuit()
  local emitted = false
  local event = 'test_short_circuit'
  events.connect(event, function() return true end)
  events.connect(event, function() emitted = true end)
  assert_equal(events.emit(event), true)
  assert_equal(emitted, false)
end

function test_events_disconnect_during_handle()
  local foo = {}
  local event, handlers = 'test_disconnect_during_handle', {}
  for i = 1, 3 do
    handlers[i] = function()
      foo[#foo + 1] = i
      events.disconnect(event, handlers[i])
    end
    events.connect(event, handlers[i])
  end
  events.emit(event)
  assert_equal(foo, {1, 2, 3})
end

function test_events_error()
  local errmsg
  local event, handler = 'test_error', function(message)
    errmsg = message
    return false -- halt propagation
  end
  events.connect(events.ERROR, handler, 1)
  events.connect(event, function() error('foo') end)
  events.emit(event)
  events.disconnect(events.ERROR, handler)
  assert(errmsg:find('foo'), 'error handler did not run')
end

function test_events_value_passing()
  local event = 'test_value_passing'
  events.connect(event, function() return end)
  events.connect(event, function() return {1, 2, 3} end) -- halts propagation
  events.connect(event, function() return 'foo' end)
  assert_equal(events.emit(event), {1, 2, 3})
end

local locales = {}
-- Load localizations from *locale_conf* and return them in a table.
-- @param locale_conf String path to a local file to load.
local function load_locale(locale_conf)
  if locales[locale_conf] then return locales[locale_conf] end
  print(string.format('Loading locale "%s"', locale_conf))
  local L = {}
  for line in io.lines(locale_conf) do
    if not line:find('^%s*[^%w_%[]') then
      local id, str = line:match('^(.-)%s*=%s*(.+)$')
      if id and str and assert(not L[id], 'duplicate locale id "%s"', id) then
        L[id] = str
      end
    end
  end
  locales[locale_conf] = L
  return L
end

-- Looks for use of localization in the given Lua file and verifies that each
-- use is okay.
-- @param filename String filename of the Lua file to check.
-- @param L Table of localizations to read from.
local function check_localizations(filename, L)
  print(string.format('Processing file "%s"', filename:gsub(_HOME, '')))
  local count = 0
  for line in io.lines(filename) do
    for id in line:gmatch([=[_L%[['"]([^'"]+)['"]%]]=]) do
      assert(L[id], 'locale missing id "%s"', id)
      count = count + 1
    end
  end
  print(string.format('Checked %d localizations.', count))
end

local loaded_extra = {}
-- Records localization assignments in the given Lua file for use in subsequent
-- checks.
-- @param L Table of localizations to add to.
local function load_extra_localizations(filename, L)
  if loaded_extra[filename] then return end
  print(string.format('Processing file "%s"', filename:gsub(_HOME, '')))
  local count = 0
  for line in io.lines(filename) do
    if line:find('_L%b[]%s*=') then
      for id in line:gmatch([=[_L%[['"]([^'"]+)['"]%]%s*=]=]) do
        assert(not L[id], 'duplicate locale id "%s"', id)
        L[id], count = true, count + 1
      end
    end
  end
  loaded_extra[filename] = true
  print(string.format('Added %d localizations.', count))
end

local LOCALE_CONF = _HOME .. '/core/locale.conf'
local LOCALE_DIR = _HOME .. '/core/locales'

function test_locale_load()
  local L = load_locale(LOCALE_CONF)
  lfs.dir_foreach(LOCALE_DIR, function(locale_conf)
    local l = load_locale(locale_conf)
    for id in pairs(L) do assert(l[id], 'locale missing id "%s"', id) end
    for id in pairs(l) do assert(L[id], 'locale has extra id "%s"', id) end
  end)
end

function test_locale_use_core()
  local L = load_locale(LOCALE_CONF)
  local ta_dirs = {'core', 'modules/ansi_c', 'modules/lua', 'modules/textadept'}
  for _, dir in ipairs(ta_dirs) do
    dir = _HOME .. '/' .. dir
    lfs.dir_foreach(
      dir, function(filename) check_localizations(filename, L) end, '.lua')
  end
  check_localizations(_HOME .. '/init.lua', L)
end

function test_locale_use_extra()
  local L = load_locale(LOCALE_CONF)
  lfs.dir_foreach(
    _HOME, function(filename) load_extra_localizations(filename, L) end, '.lua')
  lfs.dir_foreach(
    _HOME, function(filename) check_localizations(filename, L) end, '.lua')
end

function test_locale_use_userhome()
  local L = load_locale(LOCALE_CONF)
  lfs.dir_foreach(
    _HOME, function(filename) load_extra_localizations(filename, L) end, '.lua')
  lfs.dir_foreach(_USERHOME, function(filename)
    load_extra_localizations(filename, L)
  end, '.lua')
  L['%1'] = true -- snippet
  lfs.dir_foreach(
    _USERHOME, function(filename) check_localizations(filename, L) end, '.lua')
end

function test_file_io_open_file_detect_encoding()
  io.recent_files = {} -- clear
  local recent_files = {}
  local files = {
    [_HOME .. '/test/file_io/utf8'] = 'UTF-8',
    [_HOME .. '/test/file_io/cp1252'] = 'CP1252',
    [_HOME .. '/test/file_io/utf16'] = 'UTF-16',
    [_HOME .. '/test/file_io/binary'] = '',
  }
  for filename, encoding in pairs(files) do
    print(string.format('Opening file %s', filename))
    io.open_file(filename)
    assert_equal(buffer.filename, filename)
    local f = io.open(filename, 'rb')
    local contents = f:read('a')
    f:close()
    if encoding ~= '' then
      --assert_equal(buffer:get_text():iconv(encoding, 'UTF-8'), contents)
      assert_equal(buffer.encoding, encoding)
      assert_equal(buffer.code_page, buffer.CP_UTF8)
    else
      assert_equal(buffer:get_text(), contents)
      assert_equal(buffer.encoding, nil)
      assert_equal(buffer.code_page, 0)
    end
    buffer:close()
    table.insert(recent_files, 1, filename)
  end
  assert_equal(io.recent_files, recent_files)

  assert_raises(function() io.open_file(1) end, 'string/table/nil expected, got number')
  assert_raises(function() io.open_file('/tmp/foo', true) end, 'string/table/nil expected, got boolean')
  -- TODO: encoding failure
end

function test_file_io_open_file_detect_newlines()
  local files = {
    [_HOME .. '/test/file_io/lf'] = buffer.EOL_LF,
    [_HOME .. '/test/file_io/crlf'] = buffer.EOL_CRLF,
  }
  for filename, mode in pairs(files) do
    io.open_file(filename)
    assert_equal(buffer.eol_mode, mode)
    buffer:close()
  end
end

function test_file_io_open_file_with_encoding()
  local num_buffers = #_BUFFERS
  local files = {
    _HOME .. '/test/file_io/utf8',
    _HOME .. '/test/file_io/cp1252',
    _HOME .. '/test/file_io/utf16'
  }
  local encodings = {nil, 'CP1252', 'UTF-16'}
  io.open_file(files, encodings)
  assert_equal(#_BUFFERS, num_buffers + #files)
  for i = #files, 1, -1 do
    view:goto_buffer(_BUFFERS[num_buffers + i])
    assert_equal(buffer.filename, files[i])
    if encodings[i] then assert_equal(buffer.encoding, encodings[i]) end
    buffer:close()
  end
end

function test_file_io_open_file_already_open()
  local filename = _HOME .. '/test/file_io/utf8'
  io.open_file(filename)
  buffer.new()
  local num_buffers = #_BUFFERS
  io.open_file(filename)
  assert_equal(buffer.filename, filename)
  assert_equal(#_BUFFERS, num_buffers)
  view:goto_buffer(1)
  buffer:close() -- untitled
  buffer:close() -- filename
end

function test_file_io_open_file_interactive()
  local num_buffers = #_BUFFERS
  io.open_file()
  if #_BUFFERS > num_buffers then buffer:close() end
end

function test_file_io_open_file_errors()
  if LINUX then
    assert_raises(function() io.open_file('/etc/group-') end, 'cannot open /etc/group-: Permission denied')
  end
  -- TODO: find a case where the file can be opened, but not read
end

function test_file_io_reload_file()
  io.open_file(_HOME .. '/test/file_io/utf8')
  local pos = 10
  buffer:goto_pos(pos)
  local text = buffer:get_text()
  buffer:append_text('foo')
  assert(buffer:get_text() ~= text, 'buffer text is unchanged')
  buffer:reload()
  assert_equal(buffer:get_text(), text)
  assert_equal(buffer.current_pos, pos)
  buffer:close()
end

function test_file_io_set_encoding()
  io.open_file(_HOME .. '/test/file_io/utf8')
  local pos = 10
  buffer:goto_pos(pos)
  local text = buffer:get_text()
  buffer:set_encoding('CP1252')
  assert_equal(buffer.encoding, 'CP1252')
  assert_equal(buffer.code_page, buffer.CP_UTF8)
  assert_equal(buffer:get_text(), text) -- fundamentally the same
  assert_equal(buffer.current_pos, pos)
  buffer:reload()
  buffer:close()

  assert_raises(function() buffer:set_encoding(true) end, 'string/nil expected, got boolean')
end

function test_file_io_save_file()
  buffer.new()
  buffer._type = '[Foo Buffer]'
  buffer:append_text('foo')
  local filename = os.tmpname()
  buffer:save_as(filename)
  local f = assert(io.open(filename))
  local contents = f:read('a')
  f:close()
  assert_equal(buffer:get_text(), contents)
  assert(not buffer._type, 'still has a type')
  buffer:append_text('bar')
  io.save_all_files()
  f = assert(io.open(filename))
  contents = f:read('a')
  f:close()
  assert_equal(buffer:get_text(), contents)
  buffer:close()
  os.remove(filename)

  assert_raises(function() buffer:save_as(1) end, 'string/nil expected, got number')
end

function test_file_io_non_global_buffer_functions()
  local filename = os.tmpname()
  local buf = buffer.new()
  buf:append_text('foo')
  view:goto_buffer(-1)
  assert(buffer ~= buf, 'still in untitled buffer')
  assert_equal(buf:get_text(), 'foo')
  assert(buffer ~= buf, 'jumped to untitled buffer')
  buf:save_as(filename)
  assert(buffer ~= buf, 'jumped to untitled buffer')
  view:goto_buffer(1)
  assert(buffer == buf, 'not in saved buffer')
  assert_equal(buffer.filename, filename)
  assert(not buffer.modify, 'saved buffer still marked modified')
  local f = io.open(filename, 'rb')
  local contents = f:read('a')
  f:close()
  assert_equal(buffer:get_text(), contents)
  buffer:append_text('bar')
  view:goto_buffer(-1)
  assert(buffer ~= buf, 'still in saved buffer')
  buf:save()
  assert(buffer ~= buf, 'jumped to untitled buffer')
  f = io.open(filename, 'rb')
  contents = f:read('a')
  f:close()
  assert_equal(buf:get_text(), contents)
  buf:append_text('baz')
  assert_equal(buf:get_text(), contents .. 'baz')
  assert(buf.modify, 'buffer not marked modified')
  buf:reload()
  assert_equal(buf:get_text(), contents)
  assert(not buf.modify, 'buffer still marked modified')
  buf:append_text('baz')
  buf:close(true)
  assert(buffer ~= buf, 'closed the wrong buffer')
  os.remove(filename)
end

function test_file_io_file_detect_modified()
  local modified = false
  local handler = function(filename)
    assert_type(filename, 'string', 1)
    modified = true
    return false -- halt propagation
  end
  events.connect(events.FILE_CHANGED, handler, 1)
  local filename = os.tmpname()
  local f = assert(io.open(filename, 'w'))
  f:write('foo\n'):flush()
  io.open_file(filename)
  assert_equal(buffer:get_text(), 'foo\n')
  view:goto_buffer(-1)
  os.execute('sleep 1') -- filesystem mod time has 1-second granularity
  f:write('bar\n'):flush()
  view:goto_buffer(1)
  assert_equal(modified, true)
  buffer:close()
  f:close()
  os.remove(filename)
  events.disconnect(events.FILE_CHANGED, handler)
end

function test_file_io_file_detect_modified_interactive()
  local filename = os.tmpname()
  local f = assert(io.open(filename, 'w'))
  f:write('foo\n'):flush()
  io.open_file(filename)
  assert_equal(buffer:get_text(), 'foo\n')
  view:goto_buffer(-1)
  os.execute('sleep 1') -- filesystem mod time has 1-second granularity
  f:write('bar\n'):flush()
  view:goto_buffer(1)
  assert_equal(buffer:get_text(), 'foo\nbar\n')
  buffer:close()
  f:close()
  os.remove(filename)
end

function test_file_io_recent_files()
  io.recent_files = {} -- clear
  local recent_files = {}
  local files = {
    _HOME .. '/test/file_io/utf8',
    _HOME .. '/test/file_io/cp1252',
    _HOME .. '/test/file_io/utf16',
    _HOME .. '/test/file_io/binary'
  }
  for _, filename in ipairs(files) do
    io.open_file(filename)
    buffer:close()
    table.insert(recent_files, 1, filename)
  end
  assert_equal(io.recent_files, recent_files)
end

function test_file_io_open_recent_interactive()
  local filename = _HOME .. '/test/file_io/utf8'
  io.open_file(filename)
  buffer:close()
  io.open_recent_file()
  assert_equal(buffer.filename, filename)
  buffer:close()
end

function test_file_io_get_project_root()
  local cwd = lfs.currentdir()
  lfs.chdir(_HOME)
  assert_equal(io.get_project_root(), _HOME)
  lfs.chdir(cwd)
  assert_equal(io.get_project_root(_HOME), _HOME)
  assert_equal(io.get_project_root(_HOME .. '/core'), _HOME)
  assert_equal(io.get_project_root(_HOME .. '/core/init.lua'), _HOME)
  assert_equal(io.get_project_root('/tmp'), nil)

  assert_raises(function() io.get_project_root(1) end, 'string/nil expected, got number')
end

function test_file_io_quick_open_interactive()
  local num_buffers = #_BUFFERS
  local cwd = lfs.currentdir()
  local dir = _HOME .. '/core'
  lfs.chdir(dir)
  io.quick_open_filters[dir] = '.lua'
  io.quick_open(dir)
  if #_BUFFERS > num_buffers then
    assert(buffer.filename:find('%.lua$'), '.lua file filter did not work')
    buffer:close()
  end
  io.quick_open_filters[dir] = true
  assert_raises(function() io.quick_open(dir) end, 'string/table/nil expected, got boolean')
  io.quick_open_filters[_HOME] = '.lua'
  io.quick_open()
  if #_BUFFERS > num_buffers then
    assert(buffer.filename:find('%.lua$'), '.lua file filter did not work')
    buffer:close()
  end
  lfs.chdir(cwd)

  assert_raises(function() io.quick_open(1) end, 'string/table/nil expected, got number')
  assert_raises(function() io.quick_open(_HOME, true) end, 'string/table/nil expected, got boolean')
  assert_raises(function() io.quick_open(_HOME, nil, 1) end, 'table/nil expected, got number')
end

function test_keys_keychain()
  local ca = keys.ca
  local foo = false
  keys.ca = {a = function() foo = true end}
  events.emit(events.KEYPRESS, string.byte('a'))
  assert(not foo, 'foo set outside keychain')
  events.emit(events.KEYPRESS, string.byte('a'), false, true)
  assert_equal(#keys.keychain, 1)
  --assert_equal(keys.keychain[1], 'ca')
  events.emit(events.KEYPRESS, not CURSES and 0xFF1B or 7) -- esc
  assert_equal(#keys.keychain, 0, 'keychain not canceled')
  events.emit(events.KEYPRESS, string.byte('a'))
  assert(not foo, 'foo set outside keychain')
  events.emit(events.KEYPRESS, string.byte('a'), false, true)
  events.emit(events.KEYPRESS, string.byte('a'))
  assert(foo, 'foo not set')
  keys.ca = ca -- restore
end

function test_keys_propagation()
  buffer:new()
  local foo, bar, baz = false, false, false
  keys.a = function() foo = true end
  keys.b = function() bar = true end
  keys.c = function() baz = true end
  keys.cpp = {
    a = function() end, -- halt
    b = function() return false end, -- propagate
    c = function()
      keys.mode = 'test_mode'
      return false -- propagate
    end
  }
  buffer:set_lexer('cpp')
  events.emit(events.KEYPRESS, string.byte('a'))
  assert(not foo, 'foo set')
  events.emit(events.KEYPRESS, string.byte('b'))
  assert(bar, 'bar set')
  events.emit(events.KEYPRESS, string.byte('c'))
  assert(not baz, 'baz set') -- mode changed, so cannot propagate to keys.c
  assert_equal(keys.mode, 'test_mode')
  keys.mode = nil
  keys.a, keys.b, keys.c, keys.cpp = nil, nil, nil, nil -- reset
  buffer:close()
end

function test_keys_modes()
  buffer.new()
  local foo, bar = false, false
  keys.a = function() foo = true end
  keys.test_mode = {a = function()
    bar = true
    keys.mode = nil
    return false -- propagate
  end}
  keys.cpp = {a = function() keys.mode = 'test_mode' end}
  events.emit(events.KEYPRESS, string.byte('a'))
  assert(foo, 'foo not set')
  assert(not keys.mode, 'key mode entered')
  assert(not bar, 'bar set outside mode')
  foo = false
  buffer:set_lexer('cpp')
  events.emit(events.KEYPRESS, string.byte('a'))
  assert_equal(keys.mode, 'test_mode')
  assert(not foo, 'foo set outside mode')
  assert(not bar, 'bar set outside mode')
  events.emit(events.KEYPRESS, string.byte('a'))
  assert(bar, 'bar not set')
  assert(not keys.mode, 'key mode still active')
  assert(not foo, 'foo set') -- TODO: should this propagate?
  keys.a, keys.test_mode, keys.cpp = nil, nil, nil -- reset
  buffer:close()
end

function test_lfs_ext_dir_foreach()
  local files, directories = 0, 0
  lfs.dir_foreach(_HOME .. '/core', function(filename)
    if not filename:find('/$') then
      files = files + 1
    else
      directories = directories + 1
    end
  end, nil, nil, true)
  assert(files > 0, 'no files found')
  assert(directories > 0, 'no directories found')

  assert_raises(function() lfs.dir_foreach() end, 'string expected, got nil')
  assert_raises(function() lfs.dir_foreach(_HOME) end, 'function expected, got nil')
  assert_raises(function() lfs.dir_foreach(_HOME, function() end, 1) end, 'string/table/nil expected, got number')
  assert_raises(function() lfs.dir_foreach(_HOME, function() end, nil, true) end, 'number/nil expected, got boolean')
end

function test_lfs_ext_dir_foreach_filter_lua()
  local count = 0
  lfs.dir_foreach(_HOME .. '/core', function(filename)
    assert(filename:find('%.lua$'), '"%s" not a Lua file', filename)
    count = count + 1
  end, '.lua')
  assert(count > 0, 'no Lua files found')
end

function test_lfs_ext_dir_foreach_filter_exclusive()
  local count = 0
  lfs.dir_foreach(_HOME .. '/core', function(filename)
    assert(not filename:find('%.lua$'), '"%s" is a Lua file', filename)
    count = count + 1
  end, '!.lua')
  assert(count > 0, 'no non-Lua files found')
end

function test_lfs_ext_dir_foreach_filter_dir()
  local count = 0
  lfs.dir_foreach(_HOME, function(filename)
    assert(filename:find('/core/'), '"%s" is not in core/', filename)
    count = count + 1
  end, '/core')
  assert(count > 0, 'no core files found')
end
expected_failure(test_lfs_ext_dir_foreach_filter_dir)

function test_lfs_ext_dir_foreach_filter_mixed()
  local count = 0
  lfs.dir_foreach(_HOME .. '/core', function(filename)
    assert(not filename:find('/locales/') and filename:find('%.lua$'), '"%s" should not match', filename)
    count = count + 1
  end, {'!/locales', '.lua'})
  assert(count > 0, 'no matching files found')
end

function test_lfs_ext_dir_foreach_max_depth()
  local count = 0
  lfs.dir_foreach(
    _HOME, function(filename) count = count + 1 end, '.lua', 0)
  assert_equal(count, 1) -- init.lua
end

function test_lfs_ext_dir_foreach_halt()
  local count, count_at_halt = 0, 0
  lfs.dir_foreach(_HOME .. '/core', function(filename)
    count = count + 1
    if filename:find('/locales/.') then
      count_at_halt = count
      return false
    end
  end)
  assert_equal(count, count_at_halt)

  lfs.dir_foreach(_HOME .. '/core', function(filename)
    count = count + 1
    if filename:find('[/\\]$') then
      count_at_halt = count
      return false
    end
  end, nil, nil, true)
  assert_equal(count, count_at_halt)
end

function test_lfs_ext_dir_foreach_win32()
  local win32 = _G.WIN32
  _G.WIN32 = true
  local count = 0
  lfs.dir_foreach(_HOME, function(filename)
    assert(not filename:find('/'), '"%s" has /', filename)
    if filename:find('\\core') then count = count + 1 end
  end, {'/core'})
  assert(count > 0, 'no core files found')
  _G.WIN32 = win32 -- reset just in case
end

function test_lfs_ext_abs_path()
  assert_equal(lfs.abspath('bar', '/foo'), '/foo/bar')
  assert_equal(lfs.abspath('./bar', '/foo'), '/foo/bar')
  assert_equal(lfs.abspath('../bar', '/foo'), '/bar')
  assert_equal(lfs.abspath('/bar', '/foo'), '/bar')
  assert_equal(lfs.abspath('../../././baz', '/foo/bar'), '/baz')
  local win32 = _G.WIN32
  _G.WIN32 = true
  assert_equal(lfs.abspath('bar', 'C:\\foo'), 'C:\\foo\\bar')
  assert_equal(lfs.abspath('.\\bar', 'C:\\foo'), 'C:\\foo\\bar')
  assert_equal(lfs.abspath('..\\bar', 'C:\\foo'), 'C:\\bar')
  assert_equal(lfs.abspath('C:\\bar', 'C:\\foo'), 'C:\\bar')
  assert_equal(lfs.abspath('c:\\bar', 'c:\\foo'), 'C:\\bar')
  assert_equal(lfs.abspath('..\\../.\\./baz', 'C:\\foo\\bar'), 'C:\\baz')
  _G.WIN32 = win32 -- reset just in case

  assert_raises(function() lfs.abspath() end, 'string expected, got nil')
  assert_raises(function() lfs.abspath('foo', 1) end, 'string/nil expected, got number')
end

function test_ui_print()
  local tabs = ui.tabs
  local silent_print = ui.silent_print

  ui.tabs = true
  ui.silent_print = false
  ui.print('foo')
  assert_equal(buffer._type, _L['[Message Buffer]'])
  assert_equal(#_VIEWS, 1)
  assert_equal(buffer:get_text(), 'foo\n')
  assert(buffer:line_from_position(buffer.current_pos) > LINE(1), 'still on first line')
  ui.print('bar', 'baz')
  assert_equal(buffer:get_text(), 'foo\nbar\tbaz\n')
  buffer:close()

  ui.tabs = false
  ui.print(1, 2, 3)
  assert_equal(buffer._type, _L['[Message Buffer]'])
  assert_equal(#_VIEWS, 2)
  assert_equal(buffer:get_text(), '1\t2\t3\n')
  ui.goto_view(-1) -- first view
  assert(buffer._type ~= _L['[Message Buffer]'], 'still in message buffer')
  ui.print(4, 5, 6) -- should jump to second view
  assert_equal(buffer._type, _L['[Message Buffer]'])
  assert_equal(buffer:get_text(), '1\t2\t3\n4\t5\t6\n')
  ui.goto_view(-1) -- first view
  assert(buffer._type ~= _L['[Message Buffer]'], 'still in message buffer')
  ui.silent_print = true
  ui.print(7, 8, 9) -- should stay in first view
  assert(buffer._type ~= _L['[Message Buffer]'], 'switched to message buffer')
  assert_equal(_BUFFERS[#_BUFFERS]:get_text(), '1\t2\t3\n4\t5\t6\n7\t8\t9\n')
  ui.silent_print = false
  ui.goto_view(1) -- second view
  assert_equal(buffer._type, _L['[Message Buffer]'])
  view:goto_buffer(-1)
  assert(buffer._type ~= _L['[Message Buffer]'], 'message buffer still visible')
  ui.print()
  assert_equal(buffer._type, _L['[Message Buffer]'])
  assert_equal(buffer:get_text(), '1\t2\t3\n4\t5\t6\n7\t8\t9\n\n')
  view:unsplit()

  buffer:close()
  ui.tabs = tabs
  ui.silent_print = silent_print
end

function test_ui_dialogs_colorselect_interactive()
  local color = ui.dialogs.colorselect{title = 'Blue', color = 0xFF0000}
  assert_equal(color, 0xFF0000)
  color = ui.dialogs.colorselect{
    title = 'Red', color = '#FF0000', palette = {'#FF0000', 0x00FF00},
    string_output = true
  }
  assert_equal(color, '#FF0000')

  assert_raises(function() ui.dialogs.colorselect{title = function() end} end, "bad argument #title to 'colorselect' (string/number/table/boolean expected, got function")
  assert_raises(function() ui.dialogs.colorselect{palette = {true}} end, "bad argument #palette[1] to 'colorselect' (string/number expected, got boolean")
end

function test_ui_dialogs_dropdown_interactive()
  local dropdowns = {'dropdown', 'standard_dropdown'}
  for _, dropdown in ipairs(dropdowns) do
    print('Running ' .. dropdown)
    local button, i = ui.dialogs[dropdown]{items = {'foo', 'bar', 'baz'}}
    assert_equal(type(button), 'number')
    assert_equal(i, 1)
    button, i = ui.dialogs[dropdown]{
      text = 'foo', items = {'bar', 'baz', 'quux'}, select = 2,
      no_cancel = true, width = 400, height = 400
    }
    assert_equal(i, 2)
  end

  assert_raises(function() ui.dialogs.dropdown{items = {'foo', 'bar', 'baz'}, select = true} end, "bad argument #select to 'dropdown' (number expected, got boolean")
  assert_raises(function() ui.dialogs.dropdown{items = {'foo', 'bar', 'baz', true}} end, "bad argument #items[4] to 'dropdown' (string/number expected, got boolean")
end

function test_ui_dialogs_filesave_fileselect_interactive()
  local test_filename = _HOME .. '/test/ui/empty'
  local test_dir, test_file = test_filename:match('^(.+[/\\])([^/\\]+)$')
  local filename = ui.dialogs.filesave{
    with_directory = test_dir, with_file = test_file,
    no_create_directories = true
  }
  assert_equal(filename, test_filename)
  filename = ui.dialogs.fileselect{
    with_directory = test_dir, with_file = test_file, select_multiple = true
  }
  assert_equal(filename, {test_filename})
  filename = ui.dialogs.fileselect{
    with_directory = test_dir, select_only_directories = true
  }
  assert_equal(filename, test_dir:match('^(.+)/$'))
end

function test_ui_dialogs_filteredlist_interactive()
  local _, i = ui.dialogs.filteredlist{
    informative_text = 'foo', columns = '1', items = {'bar', 'baz', 'quux'},
    text = 'b z'
  }
  assert_equal(i, 2)
  local _, text = ui.dialogs.filteredlist{
    columns = {'1', '2'},
    items = {'foo', 'foobar', 'bar', 'barbaz', 'baz', 'bazfoo'},
    search_column = 2, text = 'baz', output_column = 2, string_output = true,
    select_multiple = true, button1 = _L['OK'], button2 = _L['Cancel'],
    button3 = 'Other', width = ui.size[1] / 2
  }
  assert_equal(text, {'barbaz'})
end

function test_ui_dialogs_fontselect_interactive()
  local font = ui.dialogs.fontselect{
    font_name = 'Monospace', font_size = 14, font_style = 'Bold'
  }
  assert_equal(font, 'Monospace Bold 14')
end

function test_ui_dialogs_inputbox_interactive()
  local inputboxes = {
    'inputbox', 'secure_inputbox', 'standard_inputbox',
    'secure_standard_inputbox'
  }
  for _, inputbox in ipairs(inputboxes) do
    print('Running ' .. inputbox)
    local button, text = ui.dialogs[inputbox]{text = 'foo'}
    assert_equal(type(button), 'number')
    assert_equal(text, 'foo')
    button, text = ui.dialogs[inputbox]{
      text = 'foo', string_output = true, no_cancel = true
    }
    assert_equal(type(button), 'string')
    assert_equal(text, 'foo')
  end

  local button, text = ui.dialogs.inputbox{
    informative_text = {'info', 'foo', 'baz'}, text = {'bar', 'quux'}
  }
  assert_equal(type(button), 'number')
  assert_equal(text, {'bar', 'quux'})
  button = ui.dialogs.inputbox{
    informative_text = {'info', 'foo', 'baz'}, text = {'bar', 'quux'},
    string_output = true
  }
  assert_equal(type(button), 'string')
end

function test_ui_dialogs_msgbox_interactive()
  local msgboxes = {'msgbox', 'ok_msgbox', 'yesno_msgbox'}
  local icons = {'gtk-dialog-info', 'gtk-dialog-warning', 'gtk-dialog-question'}
  for i, msgbox in ipairs(msgboxes) do
    print('Running ' .. msgbox)
    local button = ui.dialogs[msgbox]{icon = icons[i]}
    assert_equal(type(button), 'number')
    button = ui.dialogs[msgbox]{
      icon_file = _HOME .. '/core/images/ta_32x32.png', string_output = true,
      no_cancel = true
    }
    assert_equal(type(button), 'string')
  end
end

function test_ui_dialogs_optionselect_interactive()
  local _, selected = ui.dialogs.optionselect{items = 'foo', select = 1}
  assert_equal(selected, {1})
  _, selected = ui.dialogs.optionselect{
    items = {'foo', 'bar', 'baz'}, select = {1, 3}, string_output = true
  }
  assert_equal(selected, {'foo', 'baz'})

  assert_raises(function() ui.dialogs.optionselect{items = {'foo', 'bar', 'baz'}, select = {1, 'bar'}} end, "bad argument #select[2] to 'optionselect' (number expected, got string")
end

function test_ui_dialogs_progressbar_interactive()
  local i = 0
  ui.dialogs.progressbar({title = 'foo'}, function()
    os.execute('sleep 0.1')
    i = i + 10
    if i > 100 then return nil end
    return i, i .. '%'
  end)

  local stopped = ui.dialogs.progressbar({
    title = 'foo', indeterminite = true, stoppable = true
  }, function()
    os.execute('sleep 0.1')
    return 50
  end)
  assert(stopped, 'progressbar not stopped')

  ui.update() -- allow GTK to remove callback for previous function
  i = 0
  ui.dialogs.progressbar({title = 'foo', stoppable = true}, function()
    os.execute('sleep 0.1')
    i = i + 10
    if i > 100 then return nil end
    return i, i <= 50 and "stop disable" or "stop enable"
  end)

  local errmsg
  local handler = function(message)
    errmsg = message
    return false -- halt propagation
  end
  events.connect(events.ERROR, handler, 1)
  ui.dialogs.progressbar({}, function() error('foo') end)
  assert(errmsg:find('foo'), 'error handler did not run')
  ui.dialogs.progressbar({}, function() return true end)
  assert(errmsg:find('invalid return values'), 'error handler did not run')
  events.disconnect(events.ERROR, handler)
end

function test_ui_dialogs_textbox_interactive()
  ui.dialogs.textbox{
    text = 'foo', editable = true, selected = true, monospaced_font = true
  }
  ui.dialogs.textbox{text_from_file = _HOME .. '/LICENSE', scroll_to = 'bottom'}
end

function test_ui_switch_buffer_interactive()
  buffer.new()
  buffer:append_text('foo')
  buffer.new()
  buffer:append_text('bar')
  buffer:new()
  buffer:append_text('baz')
  ui.switch_buffer() -- back to [Test Output]
  local text = buffer:get_text()
  assert(text ~= 'foo' and text ~= 'bar' and text ~= 'baz')
  for i = 1, 3 do view:goto_buffer(1) end -- cycle back to baz
  ui.switch_buffer(true)
  assert_equal(buffer:get_text(), 'bar')
  for i = 1, 3 do buffer:close(true) end
end

function test_ui_goto_file()
  local dir1_file1 = _HOME .. '/core/ui/dir1/file1'
  local dir1_file2 = _HOME .. '/core/ui/dir1/file2'
  local dir2_file1 = _HOME .. '/core/ui/dir2/file1'
  local dir2_file2 = _HOME .. '/core/ui/dir2/file2'
  ui.goto_file(dir1_file1) -- current view
  assert_equal(#_VIEWS, 1)
  assert_equal(buffer.filename, dir1_file1)
  ui.goto_file(dir1_file2, true) -- split view
  assert_equal(#_VIEWS, 2)
  assert_equal(buffer.filename, dir1_file2)
  assert_equal(_VIEWS[1].buffer.filename, dir1_file1)
  ui.goto_file(dir1_file1) -- should go back to first view
  assert_equal(buffer.filename, dir1_file1)
  assert_equal(_VIEWS[2].buffer.filename, dir1_file2)
  ui.goto_file(dir2_file2, true, nil, true) -- should sloppily go back to second view
  assert_equal(buffer.filename, dir1_file2) -- sloppy
  assert_equal(_VIEWS[1].buffer.filename, dir1_file1)
  ui.goto_file(dir2_file1) -- should go back to first view
  assert_equal(buffer.filename, dir2_file1)
  assert_equal(_VIEWS[2].buffer.filename, dir1_file2)
  ui.goto_file(dir2_file2, false, _VIEWS[1]) -- should go to second view
  assert_equal(#_VIEWS, 2)
  assert_equal(buffer.filename, dir2_file2)
  assert_equal(_VIEWS[1].buffer.filename, dir2_file1)
  view:unsplit()
  assert_equal(#_VIEWS, 1)
  for i = 1, 4 do buffer:close() end
end

function test_ui_uri_drop()
  local filename = _HOME .. '/test/ui/uri drop'
  local uri = 'file://' .. _HOME .. '/test/ui/uri%20drop'
  events.emit(events.URI_DROPPED, uri)
  assert_equal(buffer.filename, filename)
  buffer:close()
  local buffer = buffer
  events.emit(events.URI_DROPPED, 'file://' .. _HOME)
  assert_equal(buffer, _G.buffer) -- do not open directory

  -- TODO: WIN32
  -- TODO: OSX
end

function test_ui_buffer_switch_save_restore_properties()
  local filename = _HOME .. '/test/ui/test.lua'
  io.open_file(filename)
  buffer:goto_pos(10)
  view:fold_line(
    buffer:line_from_position(buffer.current_pos), view.FOLDACTION_CONTRACT)
  view.view_eol = true
  view.margin_width_n[INDEX(1)] = 0 -- hide line numbers
  view:goto_buffer(-1)
  assert(view.margin_width_n[INDEX(1)] > 0, 'line numbers are still hidden')
  view:goto_buffer(1)
  assert_equal(buffer.current_pos, 10)
  assert_equal(view.fold_expanded[buffer:line_from_position(buffer.current_pos)], false)
  assert_equal(view.view_eol, true)
  assert_equal(view.margin_width_n[INDEX(1)], 0)
  buffer:close()
end

if CURSES then
  -- TODO: clipboard, mouse events, etc.
end

if WIN32 and CURSES then
  function test_spawn()
    -- TODO:
  end
end

function test_buffer_text_range()
  buffer.new()
  buffer:set_text('foo\nbar\nbaz')
  buffer:set_target_range(POS(5), POS(8))
  assert_equal(buffer.target_text, 'bar')
  assert_equal(buffer:text_range(POS(1), buffer.length + 1), 'foo\nbar\nbaz')
  assert_equal(buffer:text_range(-1, POS(4)), 'foo')
  assert_equal(buffer:text_range(POS(9), POS(16)), 'baz')
  assert_equal(buffer.target_text, 'bar') -- assert target range is unchanged
  buffer:close(true)

  assert_raises(function() buffer:text_range() end, 'number expected, got nil')
  assert_raises(function() buffer:text_range(POS(5)) end, 'number expected, got nil')
end

function test_bookmarks()
  local function has_bookmark(line)
    return buffer:marker_get(line) & 1 << textadept.bookmarks.MARK_BOOKMARK - 1 > 0
  end

  buffer.new()
  buffer:new_line()
  assert(buffer:line_from_position(buffer.current_pos) > LINE(1), 'still on first line')
  textadept.bookmarks.toggle()
  assert(has_bookmark(LINE(2)), 'no bookmark')
  textadept.bookmarks.toggle()
  assert(not has_bookmark(LINE(2)), 'bookmark still there')

  buffer:goto_pos(buffer:position_from_line(LINE(1)))
  textadept.bookmarks.toggle()
  buffer:goto_pos(buffer:position_from_line(LINE(2)))
  textadept.bookmarks.toggle()
  textadept.bookmarks.goto_mark(true)
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(1))
  textadept.bookmarks.goto_mark(true)
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(2))
  textadept.bookmarks.goto_mark(false)
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(1))
  textadept.bookmarks.goto_mark(false)
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(2))
  textadept.bookmarks.clear()
  assert(not has_bookmark(LINE(1)), 'bookmark still there')
  assert(not has_bookmark(LINE(2)), 'bookmark still there')
  buffer:close(true)
end

function test_bookmarks_interactive()
  buffer.new()
  buffer:new_line()
  textadept.bookmarks.toggle()
  buffer:line_up()
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(1))
  textadept.bookmarks.goto_mark()
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(2))
  buffer:close(true)
end

function test_command_entry_run()
  local command_run, tab_pressed = false, false
  ui.command_entry.run(function(command) command_run = command end, {
    ['\t'] = function() tab_pressed = true end
  }, nil, 2)
  ui.update() -- redraw command entry
  assert_equal(ui.command_entry:get_lexer(), 'text')
  assert(ui.command_entry.height > ui.command_entry:text_height(0), 'height < 2 lines')
  ui.command_entry:set_text('foo')
  events.emit(events.KEYPRESS, string.byte('\t'))
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n
  assert_equal(command_run, 'foo')
  assert(tab_pressed, '\\t not registered')

  assert_raises(function() ui.command_entry.run(function() end, 1) end, 'table/string/nil expected, got number')
  assert_raises(function() ui.command_entry.run(function() end, {}, 1) end, 'string/nil expected, got number')
  assert_raises(function() ui.command_entry.run(function() end, {}, 'lua', true) end, 'number/nil expected, got boolean')
  assert_raises(function() ui.command_entry.run(function() end, 'lua', true) end, 'number/nil expected, got boolean')
end

local function run_lua_command(command)
  ui.command_entry.run()
  ui.command_entry:set_text(command)
  assert_equal(ui.command_entry:get_lexer(), 'lua')
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n
end

function test_command_entry_run_lua()
  run_lua_command('print(_HOME)')
  assert_equal(buffer._type, _L['[Message Buffer]'])
  assert_equal(buffer:get_text(), _HOME .. '\n')
  run_lua_command('{key="value"}')
  assert(buffer:get_text():find('{key = value}'), 'table not pretty-printed')
  -- TODO: multi-line table pretty print.
  if #_VIEWS > 1 then view:unsplit() end
  buffer:close()
end

function test_command_entry_run_lua_abbreviated_env()
  -- buffer get/set.
  run_lua_command('length')
  assert(buffer:get_text():find('%d+%s*$'), 'buffer.length result not a number')
  run_lua_command('auto_c_active')
  assert(buffer:get_text():find('false%s*$'), 'buffer:auto_c_active() result not false')
  run_lua_command('view_eol=true')
  assert_equal(view.view_eol, true)
  -- view get/set.
  if #_VIEWS > 1 then view:unsplit() end
  run_lua_command('split')
  assert_equal(#_VIEWS, 2)
  run_lua_command('size=1')
  assert_equal(view.size, 1)
  run_lua_command('unsplit')
  assert_equal(#_VIEWS, 1)
  -- ui get/set.
  run_lua_command('dialogs')
  assert(buffer:get_text():find('%b{}%s*$'), 'ui.dialogs result not a table')
  run_lua_command('statusbar_text="foo"')
  -- _G get/set.
  run_lua_command('foo="bar"')
  run_lua_command('foo')
  assert(buffer:get_text():find('bar%s*$'), 'foo result not "bar"')
  buffer:close()
end

local function assert_lua_autocompletion(text, first_item)
  ui.command_entry:set_text(text)
  ui.command_entry:goto_pos(ui.command_entry.length + 1)
  events.emit(events.KEYPRESS, string.byte('\t'))
  assert_equal(ui.command_entry:auto_c_active(), true)
  assert_equal(ui.command_entry.auto_c_current_text, first_item)
  events.emit(events.KEYPRESS, not CURSES and 0xFF54 or 300) -- down
  events.emit(events.KEYPRESS, not CURSES and 0xFF52 or 301) -- up
  assert_equal(ui.command_entry:get_text(), text) -- no history cycling
  assert_equal(ui.command_entry:auto_c_active(), true)
  assert_equal(ui.command_entry.auto_c_current_text, first_item)
  ui.command_entry:auto_c_cancel()
end

function test_command_entry_complete_lua()
  ui.command_entry.run()
  assert_lua_autocompletion('string.', 'byte')
  assert_lua_autocompletion('auto', 'auto_c_active')
  assert_lua_autocompletion('buffer.auto', 'auto_c_auto_hide')
  assert_lua_autocompletion('buffer:auto', 'auto_c_active')
  assert_lua_autocompletion('goto', 'goto_buffer')
  assert_lua_autocompletion('_', '_BUFFERS')
  -- TODO: textadept.editing.show_documentation key binding.
  ui.command_entry:focus() -- hide
end

function test_command_entry_history()
  local one, two = function() end, function() end

  ui.command_entry.run(one)
  events.emit(events.KEYPRESS, not CURSES and 0xFF52 or 301) -- up
  assert_equal(ui.command_entry:get_text(), '') -- no prior history
  events.emit(events.KEYPRESS, not CURSES and 0xFF54 or 300) -- down
  assert_equal(ui.command_entry:get_text(), '') -- no further history
  ui.command_entry:add_text('foo')
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n

  ui.command_entry.run(two)
  events.emit(events.KEYPRESS, not CURSES and 0xFF52 or 301) -- up
  assert_equal(ui.command_entry:get_text(), '') -- no prior history
  events.emit(events.KEYPRESS, not CURSES and 0xFF54 or 300) -- down
  assert_equal(ui.command_entry:get_text(), '') -- no further history
  ui.command_entry:add_text('bar')
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n

  ui.command_entry.run(one)
  assert_equal(ui.command_entry:get_text(), 'foo')
  assert_equal(ui.command_entry.selection_start, 1)
  assert_equal(ui.command_entry.selection_end, 4)
  events.emit(events.KEYPRESS, not CURSES and 0xFF52 or 301) -- up
  assert_equal(ui.command_entry:get_text(), 'foo') -- no prior history
  events.emit(events.KEYPRESS, not CURSES and 0xFF54 or 300) -- down
  assert_equal(ui.command_entry:get_text(), 'foo') -- no further history
  ui.command_entry:set_text('baz')
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n

  ui.command_entry.run(one)
  events.emit(events.KEYPRESS, not CURSES and 0xFF52 or 301) -- up
  assert_equal(ui.command_entry:get_text(), 'foo')
  events.emit(events.KEYPRESS, not CURSES and 0xFF54 or 300) -- down
  assert_equal(ui.command_entry:get_text(), 'baz')
  events.emit(events.KEYPRESS, not CURSES and 0xFF52 or 301) -- up, 'foo'
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n

  ui.command_entry.run(one)
  events.emit(events.KEYPRESS, not CURSES and 0xFF52 or 301) -- up
  assert_equal(ui.command_entry:get_text(), 'baz')
  events.emit(events.KEYPRESS, not CURSES and 0xFF52 or 301) -- up
  assert_equal(ui.command_entry:get_text(), 'foo')
  events.emit(events.KEYPRESS, not CURSES and 0xFF1B or 7) -- esc

  ui.command_entry.run(two)
  assert_equal(ui.command_entry:get_text(), 'bar')
  events.emit(events.KEYPRESS, not CURSES and 0xFF1B or 7) -- esc
end

function test_command_entry_mode_restore()
  local mode = 'test_mode'
  keys.mode = mode
  ui.command_entry.run(nil)
  assert(keys.mode ~= mode)
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n
  assert_equal(keys.mode, mode)
  keys.mode = nil
end

function test_editing_auto_pair()
  buffer.new()
  -- Single selection.
  buffer:add_text('foo(')
  events.emit(events.CHAR_ADDED, string.byte('('))
  assert_equal(buffer:get_text(), 'foo()')
  events.emit(events.KEYPRESS, string.byte(')'))
  assert_equal(buffer.current_pos, buffer.line_end_position[LINE(1)])
  buffer:char_left()
  -- Note: cannot check for brace highlighting; indicator search does not work.
  events.emit(events.KEYPRESS, not CURSES and 0xFF08 or 263) -- \b
  assert_equal(buffer:get_text(), 'foo')
  -- Multi-selection.
  buffer:set_text('foo(\nfoo(')
  local pos1 = buffer.line_end_position[LINE(1)]
  local pos2 = buffer.line_end_position[LINE(2)]
  buffer:set_selection(pos1, pos1)
  buffer:add_selection(pos2, pos2)
  events.emit(events.CHAR_ADDED, string.byte('('))
  assert_equal(buffer:get_text(), 'foo()\nfoo()')
  assert_equal(buffer.selections, 2)
  assert_equal(buffer.selection_n_start[INDEX(1)], buffer.selection_n_end[INDEX(1)])
  assert_equal(buffer.selection_n_start[INDEX(1)], pos1)
  assert_equal(buffer.selection_n_start[INDEX(2)], buffer.selection_n_end[INDEX(2)])
  assert_equal(buffer.selection_n_start[INDEX(2)], pos2 + 1)
  -- TODO: typeover.
  events.emit(events.KEYPRESS, not CURSES and 0xFF08 or 263) -- \b
  assert_equal(buffer:get_text(), 'foo\nfoo')
  -- Verify atomic undo for multi-select.
  buffer:undo() -- simulated backspace
  buffer:undo() -- normal undo that a user would perform
  assert_equal(buffer:get_text(), 'foo()\nfoo()')
  buffer:undo()
  assert_equal(buffer:get_text(), 'foo(\nfoo(')
  buffer:close(true)
end

function test_editing_auto_indent()
  buffer.new()
  buffer:add_text('foo')
  buffer:new_line()
  assert_equal(buffer.line_indentation[LINE(2)], 0)
  buffer:tab()
  buffer:add_text('bar')
  buffer:new_line()
  assert_equal(buffer.line_indentation[LINE(3)], buffer.tab_width)
  assert_equal(buffer.current_pos, buffer.line_indent_position[LINE(3)])
  buffer:new_line()
  buffer:back_tab()
  assert_equal(buffer.line_indentation[LINE(4)], 0)
  assert_equal(buffer.current_pos, buffer:position_from_line(LINE(4)))
  buffer:new_line() -- should indent since previous line is blank
  assert_equal(buffer.line_indentation[LINE(5)], buffer.tab_width)
  assert_equal(buffer.current_pos, buffer.line_indent_position[LINE(5)])
  buffer:goto_pos(buffer:position_from_line(LINE(2))) -- "\tbar"
  buffer:new_line() -- should not change indentation
  assert_equal(buffer.line_indentation[LINE(3)], buffer.tab_width)
  assert_equal(buffer.current_pos, buffer:position_from_line(LINE(3)))
  buffer:close(true)
end

function test_editing_strip_trailing_spaces()
  local strip = textadept.editing.strip_trailing_spaces
  textadept.editing.strip_trailing_spaces = true
  buffer.new()
  local text = table.concat({
    'foo ',
    '  bar\t\r',
    'baz\t '
  }, '\n')
  buffer:set_text(text)
  buffer:goto_pos(buffer.line_end_position[LINE(2)])
  events.emit(events.FILE_BEFORE_SAVE)
  assert_equal(buffer:get_text(), table.concat({
    'foo',
    '  bar',
    'baz',
    ''
  }, '\n'))
  assert_equal(buffer.current_pos, buffer.line_end_position[LINE(2)])
  buffer:undo()
  assert_equal(buffer:get_text(), text)
  buffer:close(true)
  textadept.editing.strip_trailing_spaces = strip -- restore
end

function test_editing_paste_reindent_tabs_to_tabs()
  ui.clipboard_text = table.concat({
    '\tfoo',
    '',
    '\t\tbar',
    '\tbaz'
  }, '\n')
  buffer.new()
  buffer.use_tabs, buffer.eol_mode = true, buffer.EOL_CRLF
  buffer:add_text('quux\r\n')
  textadept.editing.paste_reindent()
  assert_equal(buffer:get_text(), table.concat({
    'quux',
    'foo',
    '',
    '\tbar',
    'baz'
  }, '\r\n'))
  buffer:clear_all()
  buffer:add_text('\t\tquux\r\n\r\n') -- no auto-indent
  assert_equal(buffer.line_indentation[LINE(2)], 0)
  assert_equal(buffer.line_indentation[LINE(3)], 0)
  textadept.editing.paste_reindent()
  assert_equal(buffer:get_text(), table.concat({
    '\t\tquux',
    '',
    '\t\tfoo',
    '\t\t',
    '\t\t\tbar',
    '\t\tbaz'
  }, '\r\n'))
  buffer:clear_all()
  buffer:add_text('\t\tquux\r\n')
  assert_equal(buffer.line_indentation[LINE(2)], 0)
  buffer:new_line() -- auto-indent
  assert_equal(buffer.line_indentation[LINE(3)], 2 * buffer.tab_width)
  textadept.editing.paste_reindent()
  assert_equal(buffer:get_text(), table.concat({
    '\t\tquux',
    '',
    '\t\tfoo',
    '\t\t',
    '\t\t\tbar',
    '\t\tbaz'
  }, '\r\n'))
  buffer:close(true)
end
expected_failure(test_editing_paste_reindent_tabs_to_tabs)

function test_editing_paste_reindent_spaces_to_spaces()
  ui.clipboard_text = table.concat({
    '    foo',
    '',
    '        bar',
    '            baz',
    '    quux'
  }, '\n')
  buffer.new()
  buffer.use_tabs, buffer.tab_width = false, 2
  buffer:add_text('foobar\n')
  textadept.editing.paste_reindent()
  assert_equal(buffer:get_text(), table.concat({
    'foobar',
    'foo',
    '',
    '  bar',
    '    baz',
    'quux'
  }, '\n'))
  buffer:clear_all()
  buffer:add_text('    foobar\n\n') -- no auto-indent
  assert_equal(buffer.line_indentation[LINE(2)], 0)
  assert_equal(buffer.line_indentation[LINE(3)], 0)
  textadept.editing.paste_reindent()
  assert_equal(buffer:get_text(), table.concat({
    '    foobar',
    '',
    '    foo',
    '    ',
    '      bar',
    '        baz',
    '    quux'
  }, '\n'))
  buffer:clear_all()
  buffer:add_text('    foobar\n')
  assert_equal(buffer.line_indentation[LINE(2)], 0)
  buffer:new_line() -- auto-indent
  assert_equal(buffer.line_indentation[LINE(3)], 4)
  textadept.editing.paste_reindent()
  assert_equal(buffer:get_text(), table.concat({
    '    foobar',
    '',
    '    foo',
    '    ',
    '      bar',
    '        baz',
    '    quux'
  }, '\n'))
  buffer:close(true)
end
expected_failure(test_editing_paste_reindent_spaces_to_spaces)

function test_editing_paste_reindent_spaces_to_tabs()
  ui.clipboard_text = table.concat({
    '  foo',
    '    bar',
    '  baz'
  }, '\n')
  buffer.new()
  buffer.use_tabs, buffer.tab_width = true, 4
  buffer:add_text('\tquux')
  buffer:new_line()
  textadept.editing.paste_reindent()
  assert_equal(buffer:get_text(), table.concat({
    '\tquux',
    '\tfoo',
    '\t\tbar',
    '\tbaz'
  }, '\n'))
  buffer:close(true)
end

function test_editing_paste_reindent_tabs_to_spaces()
  ui.clipboard_text = table.concat({
    '\tif foo and',
    '\t   bar then',
    '\t\tbaz()',
    '\tend',
    ''
  }, '\n')
  buffer.new()
  buffer.use_tabs, buffer.tab_width = false, 2
  buffer:set_lexer('lua')
  buffer:add_text('function quux()')
  buffer:new_line()
  buffer:insert_text(-1, 'end')
  buffer:colourise(POS(1), -1) -- first line should be a fold header
  textadept.editing.paste_reindent()
  assert_equal(buffer:get_text(), table.concat({
    'function quux()',
    '  if foo and',
    '     bar then',
    '    baz()',
    '  end',
    'end'
  }, '\n'))
  buffer:close(true)
end
expected_failure(test_editing_paste_reindent_tabs_to_spaces)

function test_editing_block_comment_lines()
  buffer.new()
  buffer:add_text('foo')
  textadept.editing.block_comment()
  assert_equal(buffer:get_text(), 'foo')
  buffer:set_lexer('lua')
  local text = table.concat({
    '',
    'local foo = "bar"',
    '  local baz = "quux"',
    ''
  }, '\n')
  buffer:set_text(text)
  buffer:goto_pos(buffer:position_from_line(LINE(2)))
  textadept.editing.block_comment()
  assert_equal(buffer:get_text(), table.concat({
    '',
    '--local foo = "bar"',
    '  local baz = "quux"',
    ''
  }, '\n'))
  assert_equal(buffer.current_pos, buffer:position_from_line(LINE(2)) + 2)
  textadept.editing.block_comment() -- uncomment
  assert_equal(buffer:get_line(LINE(2)), 'local foo = "bar"\n')
  assert_equal(buffer.current_pos, buffer:position_from_line(LINE(2)))
  local offset = 5
  buffer:set_sel(buffer:position_from_line(LINE(2)) + offset, buffer:position_from_line(LINE(4)) - offset)
  textadept.editing.block_comment()
  assert_equal(buffer:get_text(), table.concat({
    '',
    '--local foo = "bar"',
    '--  local baz = "quux"',
    ''
  }, '\n'))
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(2)) + offset + 2)
  assert_equal(buffer.selection_end, buffer:position_from_line(LINE(4)) - offset)
  textadept.editing.block_comment() -- uncomment
  assert_equal(buffer:get_text(), table.concat({
    '',
    'local foo = "bar"',
    '  local baz = "quux"',
    ''
  }, '\n'))
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(2)) + offset)
  assert_equal(buffer.selection_end, buffer:position_from_line(LINE(4)) - offset)
  buffer:undo() -- comment
  buffer:undo() -- uncomment
  assert_equal(buffer:get_text(), text) -- verify atomic undo
  buffer:close(true)
end

function test_editing_block_comment()
  buffer.new()
  buffer:set_lexer('ansi_c')
  buffer:set_text(table.concat({
    '',
    '  const char *foo = "bar";',
    'const char *baz = "quux";',
    ''
  }, '\n'))
  buffer:set_sel(buffer:position_from_line(LINE(2)), buffer:position_from_line(LINE(4)))
  textadept.editing.block_comment()
  assert_equal(buffer:get_text(), table.concat({
    '',
    '  /*const char *foo = "bar";*/',
    '/*const char *baz = "quux";*/',
    ''
  }, '\n'))
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(2)) + 2)
  assert_equal(buffer.selection_end, buffer:position_from_line(LINE(4)))
  textadept.editing.block_comment() -- uncomment
  assert_equal(buffer:get_text(), table.concat({
    '',
    '  const char *foo = "bar";',
    'const char *baz = "quux";',
    ''
  }, '\n'))
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(2)))
  assert_equal(buffer.selection_end, buffer:position_from_line(LINE(4)))
  buffer:close(true)
end

function test_editing_goto_line()
  buffer.new()
  buffer:new_line()
  textadept.editing.goto_line(LINE(1))
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(1))
  textadept.editing.goto_line(LINE(2))
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(2))
  buffer:close(true)

  assert_raises(function() textadept.editing.goto_line(true) end, 'number/nil expected, got boolean')
end

-- TODO: test_editing_goto_line_interactive

function test_editing_transpose_chars()
  buffer.new()
  buffer:add_text('foobar')
  textadept.editing.transpose_chars()
  assert_equal(buffer:get_text(), 'foobra')
  buffer:char_left()
  textadept.editing.transpose_chars()
  assert_equal(buffer:get_text(), 'foobar')
  buffer:clear_all()
  buffer:add_text('⌘⇧⌥')
  textadept.editing.transpose_chars()
  assert_equal(buffer:get_text(), '⌘⌥⇧')
  buffer:char_left()
  textadept.editing.transpose_chars()
  assert_equal(buffer:get_text(), '⌘⇧⌥')
  -- TODO: multiple selection?
  buffer:close(true)
end

function test_editing_join_lines()
  buffer.new()
  buffer:append_text('foo\nbar\n  baz\nquux\n')
  textadept.editing.join_lines()
  assert_equal(buffer:get_text(), 'foo bar\n  baz\nquux\n')
  assert_equal(buffer.current_pos, POS(4))
  buffer:set_sel(buffer:position_from_line(LINE(2)) + 5, buffer:position_from_line(LINE(4)) - 5)
  textadept.editing.join_lines()
  assert_equal(buffer:get_text(), 'foo bar\n  baz quux\n')
  buffer:close(true)
end

function test_editing_enclose()
  buffer.new()
  buffer.add_text('foo bar')
  textadept.editing.enclose('"', '"')
  assert_equal(buffer:get_text(), 'foo "bar"')
  buffer:undo()
  buffer:select_all()
  textadept.editing.enclose('(', ')')
  assert_equal(buffer:get_text(), '(foo bar)')
  buffer:undo()
  buffer:append_text('\nfoo bar')
  buffer:set_selection(buffer.line_end_position[LINE(1)], buffer.line_end_position[LINE(1)])
  buffer:add_selection(buffer.line_end_position[LINE(2)], buffer.line_end_position[LINE(2)])
  textadept.editing.enclose('<', '>')
  assert_equal(buffer:get_text(), 'foo <bar>\nfoo <bar>')
  buffer:undo()
  assert_equal(buffer:get_text(), 'foo bar\nfoo bar') -- verify atomic undo
  buffer:set_selection(buffer:position_from_line(LINE(1)), buffer.line_end_position[LINE(1)])
  buffer:add_selection(buffer:position_from_line(LINE(2)), buffer.line_end_position[LINE(2)])
  textadept.editing.enclose('-', '-')
  assert_equal(buffer:get_text(), '-foo bar-\n-foo bar-')
  buffer:close(true)

  assert_raises(function() textadept.editing.enclose() end, 'string expected, got nil')
  assert_raises(function() textadept.editing.enclose('<', 1) end, 'string expected, got number')
end

function test_editing_select_enclosed()
  buffer.new()
  buffer:add_text('("foo bar")')
  buffer:goto_pos(POS(6))
  textadept.editing.select_enclosed()
  assert_equal(buffer:get_sel_text(), 'foo bar')
  textadept.editing.select_enclosed()
  assert_equal(buffer:get_sel_text(), '"foo bar"')
  textadept.editing.select_enclosed()
  assert_equal(buffer:get_sel_text(), 'foo bar')
  buffer:goto_pos(POS(6))
  textadept.editing.select_enclosed('("', '")')
  assert_equal(buffer:get_sel_text(), 'foo bar')
  textadept.editing.select_enclosed('("', '")')
  assert_equal(buffer:get_sel_text(), '("foo bar")')
  textadept.editing.select_enclosed('("', '")')
  assert_equal(buffer:get_sel_text(), 'foo bar')
  buffer:append_text('"baz"')
  buffer:goto_pos(POS(10)) -- last " on first line
  textadept.editing.select_enclosed()
  assert_equal(buffer:get_sel_text(), 'foo bar')
  buffer:close(true)

  assert_raises(function() textadept.editing.select_enclosed('"') end, 'string expected, got nil')
end
expected_failure(test_editing_select_enclosed)

function test_editing_select_word()
  buffer.new()
  buffer:append_text(table.concat({
    'foo',
    'foobar',
    'bar foo',
    'baz foo bar',
    'fooquux',
    'foo'
  }, '\n'))
  textadept.editing.select_word()
  assert_equal(buffer:get_sel_text(), 'foo')
  textadept.editing.select_word()
  assert_equal(buffer.selections, 2)
  assert_equal(buffer:get_sel_text(), 'foofoo') -- Scintilla stores it this way
  textadept.editing.select_word(true)
  assert_equal(buffer.selections, 4)
  assert_equal(buffer:get_sel_text(), 'foofoofoofoo')
  local lines = {}
  for i = INDEX(1), INDEX(buffer.selections) do
    lines[#lines + 1] = buffer:line_from_position(buffer.selection_n_start[i])
  end
  table.sort(lines)
  assert_equal(lines, {LINE(1), LINE(3), LINE(4), LINE(6)})
  buffer:close(true)
end

function test_editing_select_line()
  buffer.new()
  buffer:add_text('foo\n  bar')
  textadept.editing.select_line()
  assert_equal(buffer:get_sel_text(), '  bar')
  buffer:close(true)
end

function test_editing_select_paragraph()
  buffer.new()
  buffer:set_text(table.concat({
    'foo',
    '',
    'bar',
    'baz',
    '',
    'quux'
  }, '\n'))
  buffer:goto_pos(buffer:position_from_line(LINE(3)))
  textadept.editing.select_paragraph()
  assert_equal(buffer:get_sel_text(), 'bar\nbaz\n\n')
  buffer:close(true)
end

function test_editing_convert_indentation()
  buffer.new()
  local text = table.concat({
    '\tfoo',
    '  bar',
    '\t    baz',
    '    \tquux'
  }, '\n')
  buffer:set_text(text)
  buffer.use_tabs, buffer.tab_width = true, 4
  textadept.editing.convert_indentation()
  assert_equal(buffer:get_text(), table.concat({
    '\tfoo',
    '  bar',
    '\t\tbaz',
    '\t\tquux'
  }, '\n'))
  buffer:undo()
  assert_equal(buffer:get_text(), text) -- verify atomic undo
  buffer.use_tabs, buffer.tab_width = false, 2
  textadept.editing.convert_indentation()
  assert_equal(buffer:get_text(), table.concat({
    '  foo',
    '  bar',
    '      baz',
    '      quux'
  }, '\n'))
  buffer:close(true)
end

function test_editing_highlight_word()
  buffer.new()
  buffer:append_text(table.concat({
    'foo',
    'foobar',
    'bar foo',
    'baz foo bar',
    'fooquux',
    'foo'
  }, '\n'))
  textadept.editing.highlight_word()
  local indics = {
    buffer:position_from_line(LINE(1)),
    buffer:position_from_line(LINE(3)) + 4,
    buffer:position_from_line(LINE(4)) + 4,
    buffer:position_from_line(LINE(6))
  }
  local bit = 1 << textadept.editing.INDIC_HIGHLIGHT - 1
  for _, pos in ipairs(indics) do
    local mask = buffer:indicator_all_on_for(pos)
    assert(mask & bit > 0, 'no indicator on line %d', buffer:line_from_position(pos))
  end
  buffer:close(true)
end

function test_editing_filter_through()
  buffer.new()
  buffer:set_text('3|baz\n1|foo\n5|foobar\n1|foo\n4|quux\n2|bar\n')
  textadept.editing.filter_through('sort')
  assert_equal(buffer:get_text(), '1|foo\n1|foo\n2|bar\n3|baz\n4|quux\n5|foobar\n')
  buffer:undo()
  textadept.editing.filter_through('sort | uniq|cut -d "|" -f2')
  assert_equal(buffer:get_text(), 'foo\nbar\nbaz\nquux\nfoobar\n')
  buffer:undo()
  buffer:set_sel(buffer:position_from_line(LINE(2)) + 2, buffer.line_end_position[LINE(2)])
  textadept.editing.filter_through('sed -e "s/o/O/g;"')
  assert_equal(buffer:get_text(), '3|baz\n1|fOO\n5|foobar\n1|foo\n4|quux\n2|bar\n')
  buffer:undo()
  buffer:set_sel(buffer:position_from_line(LINE(2)), buffer:position_from_line(LINE(5)))
  textadept.editing.filter_through('sort')
  assert_equal(buffer:get_text(), '3|baz\n1|foo\n1|foo\n5|foobar\n4|quux\n2|bar\n')
  buffer:undo()
  buffer:set_sel(buffer:position_from_line(LINE(2)), buffer:position_from_line(LINE(5)) + 1)
  textadept.editing.filter_through('sort')
  assert_equal(buffer:get_text(), '3|baz\n1|foo\n1|foo\n4|quux\n5|foobar\n2|bar\n')
  buffer:close(true)

  assert_raises(function() textadept.editing.filter_through() end, 'string expected, got nil')
end
unstable(test_editing_filter_through)

function test_editing_autocomplete()
  assert_raises(function() textadept.editing.autocomplete() end, 'string expected, got nil')
end

function test_editing_autocomplete_word()
  local all_words = textadept.editing.autocomplete_all_words
  textadept.editing.autocomplete_all_words = false
  buffer.new()
  buffer:add_text('foo f')
  textadept.editing.autocomplete('word')
  assert_equal(buffer:get_text(), 'foo foo')
  buffer:add_text('bar f')
  textadept.editing.autocomplete('word')
  assert(buffer:auto_c_active(), 'autocomplete list not shown')
  buffer:auto_c_select('foob')
  buffer:auto_c_complete()
  assert_equal(buffer:get_text(), 'foo foobar foobar')
  buffer.new()
  buffer:add_text('foob')
  textadept.editing.autocomplete_all_words = true
  textadept.editing.autocomplete('word')
  textadept.editing.autocomplete_all_words = all_words
  assert_equal(buffer:get_text(), 'foobar')
  buffer:close(true)
  buffer:close(true)
end

function test_editing_show_documentation()
  buffer.new()
  textadept.editing.api_files['text'] = {
    _HOME .. '/test/modules/textadept/editing/api',
    function() return _HOME .. '/test/modules/textadept/editing/api2' end
  }
  buffer:add_text('foo')
  textadept.editing.show_documentation()
  assert(buffer:call_tip_active(), 'documentation not found')
  buffer:call_tip_cancel()
  buffer:add_text('2')
  textadept.editing.show_documentation()
  assert(buffer:call_tip_active(), 'documentation not found')
  buffer:call_tip_cancel()
  buffer:add_text('bar')
  textadept.editing.show_documentation()
  assert(not buffer:call_tip_active(), 'documentation found')
  buffer:clear_all()
  buffer:add_text('FOO')
  textadept.editing.show_documentation(nil, true)
  assert(buffer:call_tip_active(), 'documentation not found')
  buffer:call_tip_cancel()
  buffer:add_text('(')
  textadept.editing.show_documentation(nil, true)
  assert(buffer:call_tip_active(), 'documentation not found')
  buffer:call_tip_cancel()
  buffer:add_text('bar')
  textadept.editing.show_documentation(nil, true)
  assert(buffer:call_tip_active(), 'documentation not found')
  events.emit(events.CALL_TIP_CLICK, 1)
  -- TODO: test calltip cycling.
  buffer:close(true)
  textadept.editing.api_files['text'] = nil

  assert_raises(function() textadept.editing.show_documentation(true) end, 'number/nil expected, got boolean')
end

function test_file_types_get_lexer()
  buffer.new()
  buffer:set_lexer('html')
  buffer:set_text(table.concat({
    '<html><head><style type="text/css">',
    'h1 {}',
    '</style></head></html>'
  }, '\n'))
  buffer:colourise(POS(1), -1)
  buffer:goto_pos(buffer:position_from_line(LINE(2)))
  assert_equal(buffer:get_lexer(), 'html')
  assert_equal(buffer:get_lexer(true), 'css')
  assert_equal(buffer:name_of_style(buffer.style_at[buffer.current_pos]), 'identifier')
  buffer:close(true)
end

function test_file_types_set_lexer()
  local lexer_loaded
  local handler = function(lexer) lexer_loaded = lexer end
  events.connect(events.LEXER_LOADED, handler)
  buffer.new()
  buffer.filename = 'foo.lua'
  buffer:set_lexer()
  assert_equal(buffer:get_lexer(), 'lua')
  assert_equal(lexer_loaded, 'lua')
  buffer.filename = 'foo'
  buffer:set_text('#!/bin/sh')
  buffer:set_lexer()
  assert_equal(buffer:get_lexer(), 'bash')
  buffer:undo()
  buffer.filename = 'Makefile'
  buffer:set_lexer()
  assert_equal(buffer:get_lexer(), 'makefile')
  -- Verify lexer after certain events.
  buffer.filename = 'foo.c'
  events.emit(events.FILE_AFTER_SAVE, nil, true)
  assert_equal(buffer:get_lexer(), 'ansi_c')
  buffer.filename = 'foo.cpp'
  events.emit(events.FILE_OPENED)
  assert_equal(buffer:get_lexer(), 'cpp')
  view:goto_buffer(1)
  view:goto_buffer(-1)
  assert_equal(buffer:get_lexer(), 'cpp')
  events.disconnect(events.LEXER_LOADED, handler)
  buffer:close(true)

  assert_raises(function() buffer:set_lexer(true) end, 'string/nil expected, got boolean')
end

function test_file_types_select_lexer_interactive()
  buffer.new()
  local lexer = buffer:get_lexer()
  textadept.file_types.select_lexer()
  assert(buffer:get_lexer() ~= lexer, 'lexer unchanged')
  buffer:close()
end

function test_file_types_load_lexers()
  local lexers = {}
  for name in buffer:private_lexer_call(_SCINTILLA.functions.property_names[1]):gmatch('[^\n]+') do
    lexers[#lexers + 1] = name
  end
  print('Loading lexers...')
  if #_VIEWS > 1 then view:unsplit() end
  view:goto_buffer(-1)
  ui.silent_print = true
  buffer.new()
  for _, name in ipairs(lexers) do
    print('Loading lexer ' .. name)
    buffer:set_lexer(name)
  end
  buffer:close()
  ui.silent_print = false
end

function test_ui_find_find_text()
  local wrapped = false
  local handler = function() wrapped = true end
  buffer.new()
  buffer:set_text(table.concat({
    ' foo',
    'foofoo',
    'FOObar',
    'foo bar baz',
  }, '\n'))
  ui.find.find_entry_text = 'foo'
  ui.find.find_next()
  assert_equal(buffer.selection_start, POS(1) + 1)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  ui.find.whole_word = true
  ui.find.find_next()
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(4)))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  events.connect(events.FIND_WRAPPED, handler)
  ui.find.find_next()
  assert(wrapped, 'search did not wrap')
  events.disconnect(events.FIND_WRAPPED, handler)
  assert_equal(buffer.selection_start, POS(1) + 1)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  ui.find.find_prev()
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(4)))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  ui.find.match_case, ui.find.whole_word = true, false
  ui.find.find_entry_text = 'FOO'
  ui.find.find_next()
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(3)))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  ui.find.find_next()
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(3)))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  ui.find.regex = true
  ui.find.find_entry_text = 'f(.)\\1'
  ui.find.find_next()
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(4)))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  ui.find.find_entry_text = 'quux'
  ui.find.find_next()
  assert_equal(buffer.selection_start, buffer.selection_end) -- no match
  ui.find.find_entry_text = '' -- reset
  ui.find.match_case, ui.find.regex = false, false -- reset
  buffer:close(true)
end

function test_ui_find_incremental()
  if not rawget(ui.find.find_incremental_keys, '\n') then
    -- Overwritten in _USERHOME.
    ui.find.find_incremental_keys['\n'] = function()
      ui.find.find_entry_text = ui.command_entry:get_text() -- save
      ui.find.find_incremental(ui.command_entry:get_text(), true, true)
    end
  end

  buffer.new()
  buffer:set_text(table.concat({
    ' foo',
    'foobar',
    'FOObaz',
    'FOOquux'
  }, '\n'))
  assert_equal(buffer.current_pos, POS(1))
  ui.find.find_incremental()
  events.emit(events.KEYPRESS, string.byte('f'))
  ui.command_entry:add_text('f') -- simulate keypress
  assert_equal(buffer.selection_start, POS(1) + 1)
  assert_equal(buffer.selection_end, buffer.selection_start + 1)
  events.emit(events.KEYPRESS, string.byte('o'))
  ui.command_entry:add_text('o') -- simulate keypress
  events.emit(events.KEYPRESS, string.byte('o'))
  ui.command_entry:add_text('o') -- simulate keypress
  assert_equal(buffer.selection_start, POS(1) + 1)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(2)))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  events.emit(events.KEYPRESS, string.byte('q'))
  ui.command_entry:add_text('q') -- simulate keypress
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(4)))
  assert_equal(buffer.selection_end, buffer.selection_start + 4)
  events.emit(events.KEYPRESS, not CURSES and 0xFF08 or 263) -- \b
  ui.command_entry:delete_back() -- simulate keypress
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(2)))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n
  assert_equal(buffer.selection_start, buffer:position_from_line(LINE(3)))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  ui.find.match_case = true
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n, wrap
  assert_equal(buffer.selection_start, POS(1) + 1)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  ui.find.match_case = false
  ui.find.find_entry_text = '' -- reset
  buffer:close(true)

  assert_raises(function() ui.find.find_incremental(1) end, 'string/nil expected, got number')
end

function test_ui_find_find_in_files()
  ui.find.find_entry_text = 'foo'
  ui.find.match_case = true
  ui.find.find_in_files(_HOME .. '/test')
  assert_equal(buffer._type, _L['[Files Found Buffer]'])
  if #_VIEWS > 1 then view:unsplit() end
  local count = 0
  for filename, line, text in buffer:get_text():gmatch('\n([^:]+):(%d+):([^\n]+)') do
    assert(filename:find('^' .. _HOME .. '/test'), 'invalid filename "%s"', filename)
    assert(text:find('foo'), '"foo" not found in "%s"', text)
    count = count + 1
  end
  assert(count > 0, 'no files found')
  local s = buffer:indicator_end(ui.find.INDIC_FIND, 0)
  while true do
    local e = buffer:indicator_end(ui.find.INDIC_FIND, s + 1)
    if e == s then break end -- no more results
    assert_equal(buffer:text_range(s, e), 'foo')
    s = buffer:indicator_end(ui.find.INDIC_FIND, e + 1)
  end
  ui.find.goto_file_found(nil, true) -- wraps around
  assert_equal(#_VIEWS, 2)
  assert(buffer.filename, 'not in file found result')
  ui.goto_view(1)
  assert_equal(view.buffer._type, _L['[Files Found Buffer]'])
  local filename, line_num = view.buffer:get_sel_text():match('^([^:]+):(%d+)')
  ui.goto_view(-1)
  assert_equal(buffer.filename, filename)
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(tonumber(line_num)))
  assert_equal(buffer:get_sel_text(), 'foo')
  ui.goto_view(1) -- files found buffer
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n
  assert_equal(buffer.filename, filename)
  ui.goto_view(1) -- files found buffer
  events.emit(events.DOUBLE_CLICK, nil, buffer:line_from_position(buffer.current_pos))
  assert_equal(buffer.filename, filename)
  buffer:close()
  ui.goto_view(1) -- files found buffer
  ui.find.goto_file_found(nil, false) -- wraps around
  assert(buffer.filename and buffer.filename ~= filename, 'opened the same file')
  buffer:close()
  ui.goto_view(1) -- files found buffer
  assert_raises(function() ui.find.goto_file_found(true) end, 'number/nil expected, got boolean')
  ui.find.find_entry_text = ''
  view:unsplit()
  buffer:close()
  -- TODO: ui.find.find_in_files() -- no param
end

function test_ui_find_replace()
  buffer.new()
  buffer:set_text('foofoo')
  ui.find.find_entry_text = 'foo'
  ui.find.find_next()
  ui.find.replace_entry_text = 'bar'
  ui.find.replace()
  assert_equal(buffer.selection_start, POS(4))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  assert_equal(buffer:get_sel_text(), 'foo')
  assert_equal(buffer:get_text(), 'barfoo')
  ui.find.regex = true
  ui.find.find_entry_text = 'f(.)\\1'
  ui.find.find_next()
  ui.find.replace_entry_text = 'b\\1\\1\\u1234'
  ui.find.replace()
  assert_equal(buffer:get_text(), 'barbooሴ')
  ui.find.regex = false
  ui.find.find_entry_text = 'quux'
  ui.find.find_next()
  ui.find.replace_entry_text = ''
  ui.find.replace()
  assert_equal(buffer:get_text(), 'barbooሴ')
  ui.find.find_entry_text, ui.find.replace_entry_text = '', '' -- reset
  buffer:close(true)
end

function test_ui_find_replace_all()
  buffer.new()
  local text = table.concat({
    'foo',
    'foobar',
    'foobaz',
    'foofoo'
  }, '\n')
  buffer:set_text(text)
  ui.find.find_entry_text, ui.find.replace_entry_text = 'foo', 'bar'
  ui.find.replace_all()
  assert_equal(buffer:get_text(), 'bar\nbarbar\nbarbaz\nbarbar')
  buffer:undo()
  assert_equal(buffer:get_text(), text) -- verify atomic undo
  ui.find.regex = true
  buffer:set_sel(buffer:position_from_line(LINE(2)), buffer:position_from_line(LINE(4)) + 3)
  ui.find.find_entry_text, ui.find.replace_entry_text = 'f(.)\\1', 'b\\1\\1'
  ui.find.replace_all() -- replace in selection
  assert_equal(buffer:get_text(), 'foo\nboobar\nboobaz\nboofoo')
  ui.find.regex = false
  buffer:undo()
  ui.find.find_entry_text, ui.find.replace_entry_text = 'foo', ''
  ui.find.replace_all()
  assert_equal(buffer:get_text(), '\nbar\nbaz\n')
  ui.find.find_entry_text, ui.find.replace_entry_text = 'quux', ''
  ui.find.replace_all()
  assert_equal(buffer:get_text(), '\nbar\nbaz\n')
  ui.find.find_entry_text, ui.find.replace_entry_text = '', '' -- reset
  buffer:close(true)
end

function test_macro_record_play_save_load()
  textadept.macros.save() -- should not do anything
  textadept.macros.play() -- should not do anything
  assert_equal(#_BUFFERS, 1)
  assert(not buffer.modify, 'a macro was played')

  textadept.macros.record()
  events.emit(events.MENU_CLICKED, 1) -- File > New
  buffer:add_text('f')
  events.emit(events.CHAR_ADDED, string.byte('f'))
  events.emit(events.FIND, 'f', true)
  events.emit(events.REPLACE, 'b')
  buffer:replace_sel('a') -- typing would do this
  events.emit(events.CHAR_ADDED, string.byte('a'))
  buffer:add_text('r')
  events.emit(events.CHAR_ADDED, string.byte('r'))
  events.emit(events.KEYPRESS, string.byte('t'), false, true) -- transpose
  textadept.macros.play() -- should not do anything
  textadept.macros.save() -- should not do anything
  textadept.macros.load() -- should not do anything
  textadept.macros.record() -- stop
  assert_equal(#_BUFFERS, 2)
  assert_equal(buffer:get_text(), 'ra')
  buffer:close(true)
  textadept.macros.play()
  assert_equal(#_BUFFERS, 2)
  assert_equal(buffer:get_text(), 'ra')
  buffer:close(true)
  local filename = os.tmpname()
  textadept.macros.save(filename)
  textadept.macros.record()
  textadept.macros.record()
  textadept.macros.load(filename)
  textadept.macros.play()
  assert_equal(#_BUFFERS, 2)
  assert_equal(buffer:get_text(), 'ra')
  buffer:close(true)
  os.remove(filename)

  assert_raises(function() textadept.macros.save(1) end, 'string/nil expected, got number')
  assert_raises(function() textadept.macros.load(1) end, 'string/nil expected, got number')
end

function test_macro_record_play_with_keys_only()
  if keys.f9 ~= textadept.macros.record then
    print('Note: not running since F9 does not toggle macro recording')
    return
  end
  buffer.new()
  buffer:append_text('foo\nbar\nbaz\n')
  events.emit(events.KEYPRESS, 0xFFC6) -- f9; start recording
  events.emit(events.KEYPRESS, not CURSES and 0xFF57 or 305) -- end
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 13) -- \n
  buffer:new_line()
  events.emit(events.KEYPRESS, not CURSES and 0xFF54 or 300) -- down
  events.emit(events.KEYPRESS, 0xFFC6) -- f9; stop recording
  assert_equal(buffer:get_text(), 'foo\n\nbar\nbaz\n');
  assert_equal(buffer.current_pos, buffer:position_from_line(LINE(3)))
  if not CURSES then
    events.emit(events.KEYPRESS, 0xFFC6, true) -- sf9; play
  else
    events.emit(events.KEYPRESS, 0xFFC7) -- f10; play
  end
  assert_equal(buffer:get_text(), 'foo\n\nbar\n\nbaz\n');
  assert_equal(buffer.current_pos, buffer:position_from_line(LINE(5)))
  if not CURSES then
    events.emit(events.KEYPRESS, 0xFFC6, true) -- sf9; play
  else
    events.emit(events.KEYPRESS, 0xFFC7) -- f10; play
  end
  assert_equal(buffer:get_text(), 'foo\n\nbar\n\nbaz\n\n');
  assert_equal(buffer.current_pos, buffer:position_from_line(LINE(7)))
  buffer:close(true)
end

function test_menu_menu_functions()
  buffer.new()
  textadept.menu.menubar[_L['Buffer']][_L['Indentation']][_L['Tab width: 8']][2]()
  assert_equal(buffer.tab_width, 8)
  textadept.menu.menubar[_L['Buffer']][_L['EOL Mode']][_L['CRLF']][2]()
  assert_equal(buffer.eol_mode, buffer.EOL_CRLF)
  textadept.menu.menubar[_L['Buffer']][_L['Encoding']][_L['CP-1252 Encoding']][2]()
  assert_equal(buffer.encoding, 'CP1252')
  buffer:set_text('foo')
  textadept.menu.menubar[_L['Edit']][_L['Delete Word']][2]()
  assert_equal(buffer:get_text(), '')
  buffer:set_text('(foo)')
  textadept.menu.menubar[_L['Edit']][_L['Match Brace']][2]()
  assert_equal(buffer.char_at[buffer.current_pos], string.byte(')'))
  buffer:set_text('foo f')
  buffer:line_end()
  textadept.menu.menubar[_L['Edit']][_L['Complete Word']][2]()
  assert_equal(buffer:get_text(), 'foo foo')
  buffer:set_text('2\n1\n3\n')
  if not CURSES then -- this is unstable in curses
    textadept.menu.menubar[_L['Edit']][_L['Filter Through']][2]()
    ui.command_entry:set_text('sort')
    events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n
    assert_equal(buffer:get_text(), '1\n2\n3\n')
  end
  buffer:set_text('foo')
  buffer:line_end()
  textadept.menu.menubar[_L['Edit']][_L['Selection']][_L['Enclose as XML Tags']][2]()
  assert_equal(buffer:get_text(), '<foo></foo>')
  assert_equal(buffer.current_pos, POS(6))
  buffer:undo()
  assert_equal(buffer:get_text(), 'foo') -- verify atomic undo
  textadept.menu.menubar[_L['Edit']][_L['Selection']][_L['Enclose as Single XML Tag']][2]()
  assert_equal(buffer:get_text(), '<foo />')
  assert_equal(buffer.current_pos, buffer.line_end_position[LINE(1)])
  if not CURSES then -- there are focus issues in curses
    textadept.menu.menubar[_L['Search']][_L['Find in Files']][2]()
    assert(ui.find.in_files, 'not finding in files')
    textadept.menu.menubar[_L['Search']][_L['Find']][2]()
    assert(not ui.find.in_files, 'finding in files')
  end
  buffer:clear_all()
  buffer:set_lexer('lua')
  buffer:add_text('string.')
  textadept.menu.menubar[_L['Tools']][_L['Complete Symbol']][2]()
  assert(buffer:auto_c_active(), 'no autocompletions')
  assert_equal(buffer.auto_c_current_text, 'byte')
  buffer:auto_c_cancel()
  buffer:char_left()
  textadept.menu.menubar[_L['Tools']][_L['Show Style']][2]()
  assert(buffer:call_tip_active(), 'style not shown')
  buffer:call_tip_cancel()
  local use_tabs = buffer.use_tabs
  textadept.menu.menubar[_L['Buffer']][_L['Indentation']][_L['Toggle Use Tabs']][2]()
  assert(buffer.use_tabs ~= use_tabs, 'use tabs not toggled')
  local view_eol = view.view_eol
  textadept.menu.menubar[_L['Buffer']][_L['Toggle View EOL']][2]()
  assert(view.view_eol ~= view_eol, 'view EOL not toggled')
  local wrap_mode = view.wrap_mode
  textadept.menu.menubar[_L['Buffer']][_L['Toggle Wrap Mode']][2]()
  assert(view.wrap_mode ~= wrap_mode, 'wrap mode not toggled')
  local view_whitespace = view.view_ws
  textadept.menu.menubar[_L['Buffer']][_L['Toggle View Whitespace']][2]()
  assert(view.view_ws ~= view_whitespace, 'view whitespace not toggled')
  view:split()
  ui.update()
  local size = view.size
  textadept.menu.menubar[_L['View']][_L['Grow View']][2]()
  assert(view.size > size, 'view shrunk')
  textadept.menu.menubar[_L['View']][_L['Shrink View']][2]()
  assert_equal(view.size, size)
  view:unsplit()
  buffer:set_text('if foo then\n  bar\nend')
  buffer:colourise(POS(1), -1)
  textadept.menu.menubar[_L['View']][_L['Toggle Current Fold']][2]()
  assert_equal(view.fold_expanded[buffer:line_from_position(buffer.current_pos)], false)
  local indentation_guides = view.indentation_guides
  textadept.menu.menubar[_L['View']][_L['Toggle Show Indent Guides']][2]()
  assert(view.indentation_guides ~= indentation_guides, 'indentation guides not toggled')
  local virtual_space = buffer.virtual_space_options
  textadept.menu.menubar[_L['View']][_L['Toggle Virtual Space']][2]()
  assert(buffer.virtual_space_options ~= virtual_space, 'virtual space not toggled')
  buffer:close(true)
end

function test_menu_functions_interactive()
  buffer.new()
  buffer.filename = '/tmp/test.lua'
  textadept.menu.menubar[_L['Tools']][_L['Set Arguments...']][2]()
  textadept.menu.menubar[_L['Help']][_L['About']][2]()
  buffer:close(true)
end

-- TODO: test set arguments more thoroughly.

function test_menu_select_command_interactive()
  local num_buffers = #_BUFFERS
  textadept.menu.select_command()
  assert(#_BUFFERS > num_buffers, 'new buffer not created')
  buffer:close()
end

function test_run_compile_run()
  textadept.run.compile() -- should not do anything
  textadept.run.run() -- should not do anything
  assert_equal(#_BUFFERS, 1)
  assert(not buffer.modify, 'a command was run')

  local compile_file = _HOME .. '/test/modules/textadept/run/compile.lua'
  textadept.run.compile(compile_file)
  assert_equal(#_BUFFERS, 2)
  assert_equal(buffer._type, _L['[Message Buffer]'])
  ui.update() -- process output
  assert(buffer:get_text():find("'end' expected"), 'no compile error')
  assert(buffer:get_text():find('> exit status: 256'), 'no compile error')
  if #_VIEWS > 1 then view:unsplit() end
  textadept.run.goto_error(nil, true) -- wraps
  assert_equal(#_VIEWS, 2)
  assert_equal(buffer.filename, compile_file)
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(3))
  assert(buffer.annotation_text[LINE(3)]:find("'end' expected"), 'annotation not visible')
  ui.goto_view(1) -- message buffer
  assert_equal(buffer._type, _L['[Message Buffer]'])
  assert(buffer:get_sel_text():find("'end' expected"), 'compile error not selected')
  assert(buffer:marker_get(buffer:line_from_position(buffer.current_pos)) & 1 << textadept.run.MARK_ERROR - 1 > 0)
  events.emit(events.KEYPRESS, not CURSES and 0xFF0D or 343) -- \n
  assert_equal(buffer.filename, compile_file)
  ui.goto_view(1) -- message buffer
  events.emit(events.DOUBLE_CLICK, nil, buffer:line_from_position(buffer.current_pos))
  assert_equal(buffer.filename, compile_file)
  local compile_command = textadept.run.compile_commands.lua
  textadept.run.compile() -- clears annotation
  ui.update() -- process output
  view:goto_buffer(1)
  assert(not buffer.annotation_text[LINE(3)]:find("'end' expected"), 'annotation visible')
  buffer:close() -- compile_file

  local run_file = _HOME .. '/test/modules/textadept/run/run.lua'
  textadept.run.run_commands[run_file] = function()
    return textadept.run.run_commands.lua, run_file:match('^(.+[/\\])') -- intentional trailing '/'
  end
  io.open_file(run_file)
  textadept.run.run()
  assert_equal(buffer._type, _L['[Message Buffer]'])
  ui.update() -- process output
  assert(buffer:get_text():find('attempt to call a nil value'), 'no run error')
  textadept.run.goto_error(nil, false)
  assert_equal(buffer.filename, run_file)
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(2))
  textadept.run.goto_error(nil, false)
  assert_equal(buffer.filename, run_file)
  assert_equal(buffer:line_from_position(buffer.current_pos), LINE(1))
  ui.goto_view(1)
  assert(buffer:marker_get(buffer:line_from_position(buffer.current_pos)) & 1 << textadept.run.MARK_WARNING - 1 > 0)
  ui.goto_view(-1)
  textadept.run.goto_error(nil, false)
  assert_equal(buffer.filename, compile_file)
  if #_VIEWS > 1 then view:unsplit() end
  buffer:close() -- compile_file
  buffer:close() -- run_file
  assert_raises(function() textadept.run.goto_error(true) end, 'number/nil expected, got boolean')
  buffer:close() -- message buffer

  assert_raises(function() textadept.run.compile({}) end, 'string/nil expected, got table')
  assert_raises(function() textadept.run.run({}) end, 'string/nil expected, got table')
end

function test_run_build()
  textadept.run.build_commands[_HOME] = function()
    return 'lua modules/textadept/run/build.lua', _HOME .. '/test/' -- intentional trailing '/'
  end
  textadept.run.stop() -- should not do anything
  textadept.run.build(_HOME)
  if #_VIEWS > 1 then view:unsplit() end
  assert_equal(buffer._type, _L['[Message Buffer]'])
  os.execute('sleep 0.1') -- ensure process is running
  buffer:add_text('foo')
  buffer:new_line() -- should send previous line as stdin
  os.execute('sleep 0.1') -- ensure process processed stdin
  textadept.run.stop()
  ui.update() -- process output
  assert(buffer:get_text():find('> cd '), 'did not change directory')
  assert(buffer:get_text():find('build%.lua'), 'did not run build command')
  assert(buffer:get_text():find('read "foo"'), 'did not send stdin')
  assert(buffer:get_text():find('> exit status: 9'), 'build not stopped')
  textadept.run.stop() -- should not do anything
  buffer:close()
  -- TODO: chdir(_HOME) and textadept.run.build() -- no param.
  -- TODO: project whose makefile is autodetected.
end
unstable(test_run_build)

function test_run_goto_internal_lua_error()
  xpcall(error, function(message) events.emit(events.ERROR, debug.traceback(message)) end, 'internal error', 2)
  if #_VIEWS > 1 then view:unsplit() end
  textadept.run.goto_error(LINE(1))
  assert(buffer.filename:find('/test/test%.lua$'), 'did not detect internal Lua error')
  view:unsplit()
  buffer:close()
  buffer:close()
end

-- TODO: test textadept.run.run_in_background

function test_session_save()
  local handler = function(session)
    session.baz = true
    session.quux = assert
    session.foobar = buffer.doc_pointer
    session.foobaz = coroutine.create(function() end)
  end
  events.connect(events.SESSION_SAVE, handler)
  buffer.new()
  buffer.filename = 'foo.lua'
  textadept.bookmarks.toggle()
  view:split()
  buffer.new()
  buffer.filename = 'bar.lua'
  local session_file = os.tmpname()
  textadept.session.save(session_file)
  local session = assert(loadfile(session_file, 't', {}))()
  assert_equal(session.buffers[#session.buffers - 1].filename, 'foo.lua')
  assert_equal(session.buffers[#session.buffers - 1].bookmarks, {1})
  assert_equal(session.buffers[#session.buffers].filename, 'bar.lua')
  assert_equal(session.ui.maximized, false)
  assert_equal(type(session.views[1]), 'table')
  assert_equal(session.views[1][1], #_BUFFERS - 1)
  assert_equal(session.views[1][2], #_BUFFERS)
  assert(not session.views[1].vertical, 'split vertical')
  assert(session.views[1].size > 1, 'split size not set properly')
  assert_equal(session.views.current, #_VIEWS)
  assert_equal(session.baz, true)
  assert(not session.quux, 'function serialized')
  assert(not session.foobar, 'userdata serialized')
  assert(not session.foobaz, 'thread serialized')
  view:unsplit()
  buffer:close()
  buffer:close()
  os.remove(session_file)
  events.disconnect(events.SESSION_SAVE, handler)
end

function test_snippets_find_snippet()
  snippets.foo = 'bar'
  textadept.snippets.paths[1] = _HOME .. '/test/modules/textadept/snippets'

  buffer.new()
  buffer:add_text('foo')
  assert(textadept.snippets.insert() == nil, 'snippet not inserted')
  assert_equal(buffer:get_text(), 'bar') -- from snippets
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'baz\n') -- from bar file
  buffer:delete_back()
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'quux\n') -- from baz.txt file
  buffer:delete_back()
  assert(not textadept.snippets.insert(), 'snippet inserted')
  assert_equal(buffer:get_text(), 'quux')
  buffer:clear_all()
  buffer:set_lexer('lua') -- prefer lexer-specific snippets
  snippets.lua = {foo = 'baz'} -- overwrite language module
  buffer:add_text('foo')
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'baz') -- from snippets.lua
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'bar\n') -- from lua.baz.lua file
  buffer:delete_back()
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'quux\n') -- from lua.bar file
  buffer:close(true)

  snippets.foo = nil
  table.remove(textadept.snippets.paths, 1)
end

function test_snippets_match_indentation()
  local snippet = '\t    foo'
  local multiline_snippet = table.concat({
    'foo',
    '\tbar',
    '\t    baz',
    'quux'
  }, '\n')
  buffer.new()

  buffer.use_tabs, buffer.tab_width, buffer.eol_mode = true, 4, buffer.EOL_CRLF
  textadept.snippets.insert(snippet)
  assert_equal(buffer:get_text(), '\t\tfoo')
  buffer:clear_all()
  buffer:add_text('\t')
  textadept.snippets.insert(snippet)
  assert_equal(buffer:get_text(), '\t\t\tfoo')
  buffer:clear_all()
  buffer:add_text('\t')
  textadept.snippets.insert(multiline_snippet)
  assert_equal(buffer:get_text(), table.concat({
    '\tfoo',
    '\t\tbar',
    '\t\t\tbaz',
    '\tquux'
  }, '\r\n'))
  buffer:clear_all()

  buffer.use_tabs, buffer.tab_width, buffer.eol_mode = false, 2, buffer.EOL_LF
  textadept.snippets.insert(snippet)
  assert_equal(buffer:get_text(), '      foo')
  buffer:clear_all()
  buffer:add_text('  ')
  textadept.snippets.insert(snippet)
  assert_equal(buffer:get_text(), '        foo')
  buffer:clear_all()
  buffer:add_text('  ')
  textadept.snippets.insert(multiline_snippet)
  assert_equal(buffer:get_text(), table.concat({
    '  foo',
    '    bar',
    '        baz',
    '  quux'
  }, '\n'))
  buffer:close(true)

  assert_raises(function() textadept.snippets.insert(true) end, 'string/nil expected, got boolean')
end

function test_snippets_placeholders()
  buffer.new()
  local lua_date = os.date()
  local p = io.popen('date')
  local shell_date = p:read()
  p:close()
  textadept.snippets.insert(table.concat({
    '%0placeholder: %1(foo) %2(bar)',
    'choice: %3{baz,quux}',
    'mirror: %2%3',
    'Lua: %<os.date()> %1<text:upper()>',
    'Shell: %[date] %1[echo %]',
    'escape: %%1 %4%( %4%{',
  }, '\n'))
  assert_equal(buffer.selections, 1)
  assert_equal(buffer.selection_start, POS(1) + 14)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  assert_equal(buffer:get_sel_text(), 'foo')
  buffer:replace_sel('baz')
  events.emit(events.UPDATE_UI, buffer.UPDATE_CONTENT + buffer.UPDATE_SELECTION) -- simulate typing
  assert_equal(buffer:get_text(), string.format(table.concat({
    ' placeholder: baz bar', -- placeholders to visit have 1 empty space
    'choice:  ', -- placeholder choices are initially empty
    'mirror:   ', -- placeholder mirrors are initially empty
    'Lua: %s BAZ', -- verify real-time transforms
    'Shell: %s baz', -- verify real-time transforms
    'escape: %%1  (  { ' -- trailing space for snippet sentinel
  }, '\n'), lua_date, shell_date))
  textadept.snippets.insert()
  assert_equal(buffer.selections, 2)
  assert_equal(buffer.selection_start, POS(1) + 18)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  for i = INDEX(1), INDEX(buffer.selections) do
    assert_equal(buffer.selection_n_end[i], buffer.selection_n_start[i] + 3)
    assert_equal(buffer:text_range(buffer.selection_n_start[i], buffer.selection_n_end[i]), 'bar')
  end
  assert(buffer:get_text():find('mirror: bar'), 'mirror not updated')
  textadept.snippets.insert()
  assert_equal(buffer.selections, 2)
  assert(buffer:auto_c_active(), 'no choice')
  buffer:auto_c_select('quux')
  buffer:auto_c_complete()
  assert(buffer:get_text():find('\nmirror: barquux\n'), 'choice mirror not updated')
  textadept.snippets.insert()
  assert_equal(buffer.selection_start, buffer.selection_end) -- no default placeholder (escaped)
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), string.format(table.concat({
    'placeholder: baz bar',
    'choice: quux',
    'mirror: barquux',
    'Lua: %s BAZ',
    'Shell: %s baz',
    'escape: %%1 ( {'
  }, '\n'), lua_date, shell_date))
  assert_equal(buffer.selection_start, POS(1))
  assert_equal(buffer.selection_start, POS(1))
  buffer:close(true)
end

function test_snippets_irregular_placeholders()
  buffer.new()
  textadept.snippets.insert('%1(foo %2(bar))%5(quux)')
  assert_equal(buffer:get_sel_text(), 'foo bar')
  buffer:delete_back()
  textadept.snippets.insert()
  assert_equal(buffer:get_sel_text(), 'quux')
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'quux')
  buffer:close(true)
end

function test_snippets_previous_cancel()
  buffer.new()
  textadept.snippets.insert('%1(foo) %2(bar) %3(baz)')
  assert_equal(buffer:get_text(), 'foo bar baz ') -- trailing space for snippet sentinel
  buffer:delete_back()
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), ' bar baz ')
  buffer:delete_back()
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), '  baz ')
  textadept.snippets.previous()
  textadept.snippets.previous()
  assert_equal(buffer:get_text(), 'foo bar baz ')
  assert_equal(buffer:get_sel_text(), 'foo')
  textadept.snippets.insert()
  textadept.snippets.cancel_current()
  assert_equal(buffer.length, 0)
  buffer:close(true)
end

function test_snippets_nested()
  snippets.foo = '%1(foo)%2(bar)%3(baz)'
  buffer.new()

  buffer:add_text('foo')
  textadept.snippets.insert()
  buffer:char_right()
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'foobarbaz barbaz ') -- trailing spaces for snippet sentinels
  assert_equal(buffer:get_sel_text(), 'foo')
  assert_equal(buffer.selection_start, POS(1))
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  buffer:replace_sel('quux')
  textadept.snippets.insert()
  assert_equal(buffer:get_sel_text(), 'bar')
  assert_equal(buffer.selection_start, POS(1) + 4)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  textadept.snippets.insert()
  assert_equal(buffer:get_sel_text(), 'baz')
  assert_equal(buffer.selection_start, POS(1) + 7)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  textadept.snippets.insert()
  assert_equal(buffer.current_pos, POS(1) + 10)
  assert_equal(buffer.selection_start, buffer.selection_end)
  assert_equal(buffer:get_text(), 'quuxbarbazbarbaz ')
  textadept.snippets.insert()
  assert_equal(buffer:get_sel_text(), 'bar')
  assert_equal(buffer.selection_start, POS(1) + 10)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  textadept.snippets.insert()
  assert_equal(buffer:get_sel_text(), 'baz')
  assert_equal(buffer.selection_start, POS(1) + 13)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'quuxbarbazbarbaz')
  buffer:clear_all()

  buffer:add_text('foo')
  textadept.snippets.insert()
  buffer:char_right()
  textadept.snippets.insert()
  textadept.snippets.cancel_current()
  assert_equal(buffer.current_pos, POS(1) + 3)
  assert_equal(buffer.selection_start, buffer.selection_end)
  assert_equal(buffer:get_text(), 'foobarbaz ')
  buffer:add_text('quux')
  assert_equal(buffer:get_text(), 'fooquuxbarbaz ')
  textadept.snippets.insert()
  assert_equal(buffer:get_sel_text(), 'bar')
  assert_equal(buffer.selection_start, POS(1) + 7)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  textadept.snippets.insert()
  assert_equal(buffer:get_sel_text(), 'baz')
  assert_equal(buffer.selection_start, POS(1) + 10)
  assert_equal(buffer.selection_end, buffer.selection_start + 3)
  textadept.snippets.insert()
  assert_equal(buffer.current_pos, buffer.line_end_position[LINE(1)])
  assert_equal(buffer.selection_start, buffer.selection_end)
  assert_equal(buffer:get_text(), 'fooquuxbarbaz')

  buffer:close(true)
  snippets.foo = nil
end

function test_snippets_select_interactive()
  snippets.foo = 'bar'
  buffer.new()
  textadept.snippets.select()
  assert(buffer.length > 0, 'no snippet inserted')
  buffer:close(true)
  snippets.foo = nil
end

function test_snippets_autocomplete()
  snippets.bar = 'baz'
  snippets.baz = 'quux'
  buffer.new()
  buffer:add_text('ba')
  textadept.editing.autocomplete('snippet')
  assert(buffer:auto_c_active(), 'snippet autocompletion list not shown')
  buffer:auto_c_complete()
  textadept.snippets.insert()
  assert_equal(buffer:get_text(), 'baz')
  buffer:close(true)
  snippets.bar = nil
  snippets.baz = nil
end

function test_lua_autocomplete()
  buffer.new()
  buffer:set_lexer('lua')

  buffer:add_text('raw')
  textadept.editing.autocomplete('lua')
  assert(buffer:auto_c_active(), 'no autocompletions')
  assert_equal(buffer.auto_c_current_text, 'rawequal')
  buffer:auto_c_cancel()
  buffer:clear_all()

  buffer:add_text('string.')
  textadept.editing.autocomplete('lua')
  assert(buffer:auto_c_active(), 'no autocompletions')
  assert_equal(buffer.auto_c_current_text, 'byte')
  buffer:auto_c_cancel()
  buffer:clear_all()

  buffer:add_text('s = "foo"\ns:')
  textadept.editing.autocomplete('lua')
  assert(buffer:auto_c_active(), 'no autocompletions')
  assert_equal(buffer.auto_c_current_text, 'byte')
  buffer:auto_c_cancel()
  buffer:clear_all()

  buffer:add_text('f = io.open("path")\nf:')
  textadept.editing.autocomplete('lua')
  assert(buffer:auto_c_active(), 'no autocompletions')
  assert_equal(buffer.auto_c_current_text, 'close')
  buffer:auto_c_cancel()
  buffer:clear_all()

  buffer:add_text('buffer:auto_c')
  textadept.editing.autocomplete('lua')
  assert(not buffer:auto_c_active(), 'autocompletions available')
  buffer.filename = _HOME .. '/test/autocomplete_lua.lua'
  textadept.editing.autocomplete('lua')
  assert(buffer:auto_c_active(), 'no autocompletions')
  assert_equal(buffer.auto_c_current_text, 'auto_c_active')
  buffer:auto_c_cancel()
  buffer:clear_all()

  local autocomplete_snippets = _M.lua.autocomplete_snippets
  _M.lua.autocomplete_snippets = false
  buffer:add_text('for')
  textadept.editing.autocomplete('lua')
  assert(not buffer:auto_c_active(), 'autocompletions available')
  _M.lua.autocomplete_snippets = true
  textadept.editing.autocomplete('lua')
  assert(buffer:auto_c_active(), 'no autocompletions')
  buffer:auto_c_cancel()
  buffer:clear_all()
  _M.lua.autocomplete_snippets = autocomplete_snippets -- restore

  buffer:close(true)
end

function test_ansi_c_autocomplete()
  buffer.new()
  buffer:set_lexer('ansi_c')

  buffer:add_text('str');
  textadept.editing.autocomplete('ansi_c')
  assert(buffer:auto_c_active(), 'no autocompletions')
  assert_equal(buffer.auto_c_current_text, 'strcat')
  buffer:auto_c_cancel()
  buffer:clear_all()

  buffer:add_text('div_t d;\nd->')
  textadept.editing.autocomplete('ansi_c')
  assert(buffer:auto_c_active(), 'no autocompletions')
  assert_equal(buffer.auto_c_current_text, 'quot')
  buffer:auto_c_cancel()
  buffer:clear_all()

  local autocomplete_snippets = _M.ansi_c.autocomplete_snippets
  _M.ansi_c.autocomplete_snippets = false
  buffer:add_text('for')
  textadept.editing.autocomplete('ansi_c')
  assert(not buffer:auto_c_active(), 'autocompletions available')
  _M.ansi_c.autocomplete_snippets = true
  textadept.editing.autocomplete('ansi_c')
  assert(buffer:auto_c_active(), 'no autocompletions')
  buffer:auto_c_cancel()
  buffer:clear_all()
  _M.ansi_c.autocomplete_snippets = autocomplete_snippets -- restore

  -- TODO: typeref and rescan

  buffer:close(true)
end

function test_lexer_api()
  buffer.new()
  buffer.use_tabs, buffer.tab_width = true, 4
  buffer:set_text(table.concat({
    'if foo then',
    '\tbar',
    '',
    'end',
    'baz'
  }, '\n'))
  buffer:set_lexer('lua')
  buffer:colourise(POS(1), -1)
  local lexer = require('lexer')
  assert(lexer.fold_level[LINE(1)] & lexer.FOLD_HEADER > 0, 'not a fold header')
  assert_equal(lexer.fold_level[LINE(2)], lexer.fold_level[LINE(3)])
  assert(lexer.fold_level[LINE(4)] > lexer.fold_level[LINE(5)], 'incorrect fold levels')
  assert(lexer.indent_amount[LINE(1)] < lexer.indent_amount[LINE(2)], 'incorrect indent level')
  assert(lexer.indent_amount[LINE(2)] > lexer.indent_amount[LINE(3)], 'incorrect indent level')
  lexer.line_state[LINE(1)] = 2
  assert_equal(lexer.line_state[LINE(1)], 2)
  assert_equal(lexer.property['foo'], '')
  lexer.property['foo'] = 'bar'
  assert_equal(lexer.property['foo'], 'bar')
  lexer.property['bar'] = '$(foo),$(foo)'
  assert_equal(lexer.property_expanded['bar'], 'bar,bar')
  lexer.property['baz'] = '1'
  assert_equal(lexer.property_int['baz'], 1)
  lexer.property['baz'] = ''
  assert_equal(lexer.property_int['baz'], 0)
  assert_equal(lexer.property_int['quux'], 0)
  assert_equal(lexer.style_at[2], 'keyword')
  assert_equal(lexer.line_from_position(15), LINE(2))
  buffer:close(true)

  assert_raises(function() lexer.fold_level = nil end, 'read-only')
  assert_raises(function() lexer.fold_level[LINE(1)] = 0 end, 'read-only')
  assert_raises(function() lexer.indent_amount = nil end, 'read-only')
  assert_raises(function() lexer.indent_amount[LINE(1)] = 0 end, 'read-only')
  assert_raises(function() lexer.property = nil end, 'read-only')
  assert_raises(function() lexer.property_int = nil end, 'read-only')
  assert_raises(function() lexer.property_int['foo'] = 1 end, 'read-only')
  --TODO: assert_raises(function() lexer.property_expanded = nil end, 'read-only')
  assert_raises(function() lexer.property_expanded['foo'] = 'bar' end, 'read-only')
  assert_raises(function() lexer.style_at = nil end, 'read-only')
  assert_raises(function() lexer.style_at[1] = 0 end, 'read-only')
  assert_raises(function() lexer.line_state = nil end, 'read-only')
  assert_raises(function() lexer.line_from_position = nil end, 'read-only')
end

function test_ui_size()
  local size = ui.size
  ui.size = {size[1] - 50, size[2] + 50}
  assert_equal(ui.size, size)
  ui.size = size
end

function test_ui_maximized()
  local maximized = ui.maximized
  ui.maximized = not maximized
  local not_maximized = ui.maximized
  ui.maximized = maximized -- reset
  -- For some reason, the following fails, even though the window maximized
  -- status is toggled. `ui.update()` does not seem to help.
  assert_equal(not_maximized, not maximized)
end
expected_failure(test_ui_maximized)

function test_reset()
  local _persist
  _G.foo = 'bar'
  reset()
  assert(not _G.foo, 'Lua not reset')
  _G.foo = 'bar'
  events.connect(events.RESET_BEFORE, function(persist)
    persist.foo = _G.foo
    _persist = persist -- store
  end)
  reset()
  -- events.RESET_AFTER has already been run, but there was no opportunity to
  -- connect to it in this test, so connect and simulate the event again.
  events.connect(events.RESET_AFTER, function(persist) _G.foo = persist.foo end)
  events.emit(events.RESET_AFTER, _persist)
  assert_equal(_G.foo, 'bar')
end

function test_timeout()
  if CURSES then
    assert_raises(function() timeout(1, function() end) end, 'not implemented')
    return
  end

  local count = 0
  local function f()
    count = count + 1
    return count < 2
  end
  timeout(0.4, f)
  assert_equal(count, 0)
  os.execute('sleep 0.5')
  ui.update()
  assert_equal(count, 1)
  os.execute('sleep 0.5')
  ui.update()
  assert_equal(count, 2)
  os.execute('sleep 0.5')
  ui.update()
  assert_equal(count, 2)
end

function test_view_split_resize_unsplit()
  view:split()
  local size = view.size
  view.size = view.size - 1
  assert_equal(view.size, size - 1)
  assert_equal(#_VIEWS, 2)
  view:split(true)
  size = view.size
  view.size = view.size + 1
  assert_equal(view.size, size + 1)
  assert_equal(#_VIEWS, 3)
  view:unsplit()
  assert_equal(#_VIEWS, 2)
  view:split(true)
  ui.goto_view(_VIEWS[1])
  view:unsplit() -- unsplits split view, leaving single view
  assert_equal(#_VIEWS, 1)
end

function test_buffer_read_write_only_properties()
  assert_raises(function() view.all_lines_visible = false end, 'read-only property')
  assert_raises(function() return buffer.auto_c_fill_ups end, 'write-only property')
  assert_raises(function() buffer.annotation_text = {} end, 'read-only property')
  assert_raises(function() buffer.char_at[POS(1)] = string.byte(' ') end, 'read-only property')
  assert_raises(function() return view.marker_alpha[INDEX(1)] end, 'write-only property')
end

-- TODO: test init.lua's buffer settings

-- Load buffer and view API from their respective LuaDoc files.
local function load_buffer_view_props()
  local buffer_props, view_props = {}, {}
  for name, props in pairs{buffer = buffer_props, view = view_props} do
    for line in io.lines(string.format('%s/core/.%s.luadoc', _HOME, name)) do
      if line:find('@field') then
        props[line:match('@field ([%w_]+)')] = true
      elseif line:find('^function') then
        props[line:match('^function ([%w_]+)')] = true
      end
    end
  end
  return buffer_props, view_props
end

local function check_property_usage(filename, buffer_props, view_props)
  print(string.format('Processing file "%s"', filename:gsub(_HOME, '')))
  local line_num, count = 1, 0
  for line in io.lines(filename) do
    for pos, id, prop in line:gmatch('()([%w_]+)[.:]([%w_]+)') do
      if id == 'M' or id == 'f' or id == 'p' or id == 'lexer' or id == 'spawn_proc' then goto continue end
      if id == 'textadept' and prop == 'MARK_BOOKMARK' then goto continue end
      if (id == 'ui' or id == 'split') and prop == 'size' then goto continue end
      if id == 'keys' and prop == 'home' then goto continue end
      if id == 'Rout' and prop == 'save' then goto continue end
      if id == 'detail' and (prop == 'filename' or prop == 'column') then goto continue end
      if (id == 'placeholder' or id == 'ph') and prop == 'length' then goto continue end
      if id == 'client' and prop == 'close' then goto continue end
      if (id == 'Foo' or id == 'Array' or id == 'Server') and prop == 'new' then goto continue end
      if buffer_props[prop] then
        assert(id == 'buffer' or id == 'buf' or id == 'buffer1' or id == 'buffer2', 'line %d:%d: "%s" should be a buffer property', line_num, pos, prop)
        count = count + 1
      elseif view_props[prop] then
        assert(id == 'view', 'line %d:%d: "%s" should be a view property', line_num, pos, prop)
        count = count + 1
      end
      ::continue::
    end
    line_num = line_num + 1
  end
  print(string.format('Checked %d buffer/view property usages.', count))
end

function test_buffer_view_usage()
  local buffer_props, view_props = load_buffer_view_props()
  lfs.dir_foreach(_HOME, function(filename)
    check_property_usage(filename, buffer_props, view_props)
  end, {'.lua', '.luadoc', '!/lexers', '!/modules/lsp/dkjson.lua', '!/modules/lua/lua.luadoc', '!/modules/debugger/lua/mobdebug.lua', '!/modules/yaml/lyaml.lua', '!/scripts', '!/src'})
end

--------------------------------------------------------------------------------

assert(not WIN32 and not OSX, 'Test suite currently only runs on Linux')

local TEST_OUTPUT_BUFFER = '[Test Output]'
function print(...) ui._print(TEST_OUTPUT_BUFFER, ...) end
-- Clean up after a previously failed test.
local function cleanup()
  while #_BUFFERS > 1 do
    if buffer._type == TEST_OUTPUT_BUFFER then view:goto_buffer(1) end
    buffer:close(true)
  end
  while view:unsplit() do end
end

-- Determines whether or not to run the test whose name is string *name*.
-- If no arg patterns are provided, returns true.
-- If only inclusive arg patterns are provided, returns true if *name* matches
-- at least one of those patterns.
-- If only exclusive arg patterns are provided ('-' prefix), returns true if
-- *name* does not match any of them.
-- If both inclusive and exclusive arg patterns are provided, returns true if
-- *name* matches at least one of the inclusive ones, but not any of the
-- exclusive ones.
-- @param name Name of the test to check for inclusion.
-- @return true or false
local function include_test(name)
  if #arg == 0 then return true end
  local include, includes, excludes = false, false, false
  for _, patt in ipairs(arg) do
    if patt:find('^%-') then
      if name:find(patt:sub(2)) then return false end
      excludes = true
    else
      if name:find(patt) then include = true end
      includes = true
    end
  end
  return include or not includes and excludes
end

local tests = {}
for k in pairs(_ENV) do
  if k:find('^test_') and include_test(k) then
    tests[#tests + 1] = k
  end
end
table.sort(tests)

print('Starting test suite')

local tests_run, tests_failed, tests_failed_expected = 0, 0, 0

for i = 1, #tests do
  cleanup()
  assert_equal(#_BUFFERS, 1)
  assert_equal(#_VIEWS, 1)

  _ENV = setmetatable({}, {__index = _ENV})
  local name, f, attempts = tests[i], _ENV[tests[i]], 1
  ::retry::
  print(string.format('Running %s', name))
  ui.update()
  local ok, errmsg = xpcall(f, function(errmsg)
    local fail = not expected_failures[f] and 'Failed!' or 'Expected failure.'
    return string.format('%s %s', fail, debug.traceback(errmsg, 3))
  end)
  ui.update()
  if not ok and unstable_tests[f] and attempts < 3 then
    cleanup()
    print('Failed, but unstable. Trying again.')
    attempts = attempts + 1
    goto retry
  elseif not errmsg then
    if #_BUFFERS > 1 then
      ok, errmsg = false, 'Failed! Test did not close the buffer(s) it created'
    elseif #_VIEWS > 1 then
      ok, errmsg = false, 'Failed! Test did not unsplit the view(s) it created'
    elseif expected_failures[f] then
      ok, errmsg = false, 'Failed! Test should have failed'
      expected_failures[f] = nil
    end
  end
  print(ok and 'Passed.' or errmsg)

  tests_run = tests_run + 1
  if not ok then
    tests_failed = tests_failed + 1
    if expected_failures[f] then
      tests_failed_expected = tests_failed_expected + 1
    end
  end
end

print(string.format('%d tests run, %d unexpected failures, %d expected failures', tests_run, tests_failed - tests_failed_expected, tests_failed_expected))

--if package.loaded['luacov'] then
--  require('luacov').save_stats() -- TODO: this crashes every other run
--  os.execute('luacov')
--  local f = assert(io.open('luacov.report.out'))
--  buffer:append_text(f:read('a'):match('\nSummary.+$'))
--  f:close()
--else
--  buffer:new_line()
--  buffer:append_text('No LuaCov coverage to report.')
--end
--buffer:set_save_point()