smep 0.1.8

A Simple Markdown Editor & Previewer, written in Rust
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
//! The root view: a Markdown editor on the left, its live preview on the right.

use std::path::{Path, PathBuf};
use std::time::Duration;

// The preview uses gpui-base's `TextView` directly: the component wrapper
// folds its own style onto the app theme and offers no colour overrides,
// while the base one takes a full `TextViewStyle`, which the preview themes
// need. Without a style it renders with the defaults the component theme
// installs, so the "System" theme looks exactly as before.
use gpui_kit::base::input::{InputBaseState, MultiLineMode};
use gpui_kit::base::text::TextView;
use gpui_kit::base::{ElementExt as _, POPUP_PRIORITY};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{
    Copy, Cut, Editor, EditorState, InputEvent, Paste, Redo, Replace, RopeExt as _, Search,
    SelectAll, TextareaState, Undo,
};
use gpui_kit::component::menu::{DropdownMenu as _, PopupMenu, PopupMenuItem};
use gpui_kit::component::text::TextViewState;
use gpui_kit::component::{
    ActiveTheme as _, Sizable as _, Theme, TitleBar, h_flex, h_resizable, resizable_panel, v_flex,
    window_border,
};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;

use crate::convert;
use crate::defaults;
use crate::export;
use crate::highlight;
use crate::insert;
use crate::io::{self, Document};
use crate::keymap::{
    self, ExportHtml, ExportPdf, Import, MakeDefault, Open, Quit, Save, SaveAs, ToggleEditing,
    ToggleFullscreen, ToggleMenuBar, ViewRendered, ViewSource, ViewSplit,
};
use crate::rendered::{RenderedEvent, RenderedView};
use crate::settings::{Settings, ViewMode};
use crate::theme::{self, PreviewTheme};

/// How long typing has to pause before the preview re-parses.
pub const PREVIEW_DEBOUNCE: Duration = Duration::from_millis(80);

/// How the preview interprets the source.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PreviewFormat {
    Markdown,
    Html,
}

impl PreviewFormat {
    pub fn for_path(path: &Path) -> Self {
        match path.extension().and_then(|ext| ext.to_str()) {
            Some(ext) if ext.eq_ignore_ascii_case("html") || ext.eq_ignore_ascii_case("htm") => {
                Self::Html
            }
            _ => Self::Markdown,
        }
    }
}

/// Whichever popup menu is open (insert, editor context, preview theme).
struct InsertMenu {
    menu: Entity<PopupMenu>,
    position: Point<Pixels>,
    _dismiss: Subscription,
}

/// The input the user is typing in: the source editor, or the block being
/// edited in the rendered view. Menus and the "+" work on whichever it is.
#[derive(Clone)]
enum ActiveEditor {
    Source(Entity<EditorState>),
    Block(Entity<TextareaState>),
}

impl ActiveEditor {
    /// Run `f` on the state, whichever kind it is.
    fn read<R>(&self, cx: &App, f: impl FnOnce(&dyn LineInput) -> R) -> R {
        match self {
            Self::Source(editor) => f(editor.read(cx)),
            Self::Block(editor) => f(editor.read(cx)),
        }
    }

    fn focus_handle(&self, cx: &App) -> FocusHandle {
        match self {
            Self::Source(editor) => editor.focus_handle(cx),
            Self::Block(editor) => editor.focus_handle(cx),
        }
    }

    /// Window-space bounds of the cursor's line, once the input has laid out.
    fn cursor_line_bounds(&self, cx: &App) -> Option<Bounds<Pixels>> {
        self.read(cx, |state| state.cursor_line_bounds())
    }

    fn cursor_line_is_blank(&self, cx: &App) -> bool {
        self.read(cx, |state| state.cursor_line_trimmed().is_empty())
    }

    /// Put a block's skeleton at the cursor.
    fn insert(&self, kind: insert::BlockKind, window: &mut Window, cx: &mut App) {
        match self {
            Self::Source(editor) => editor.update(cx, |state, cx| {
                insert::insert_block(state, kind, window, cx);
            }),
            Self::Block(editor) => editor.update(cx, |state, cx| {
                insert::insert_block(state, kind, window, cx);
            }),
        }
    }
}

/// What [`ActiveEditor`] needs from either kind of input state.
trait LineInput {
    fn cursor_line_bounds(&self) -> Option<Bounds<Pixels>>;
    fn cursor_line_trimmed(&self) -> String;
}

impl<M: MultiLineMode> LineInput for InputBaseState<M> {
    fn cursor_line_bounds(&self) -> Option<Bounds<Pixels>> {
        let line = insert::cursor_line_range(self);
        self.range_to_bounds(&(line.start..line.start))
    }

    fn cursor_line_trimmed(&self) -> String {
        insert::cursor_line_trimmed(self)
    }
}

/// The editor pane and the preview pane, kept in sync.
///
/// The editor state owns the text. Every change it emits is copied into
/// `source` at once (that drives the dirty marker) and handed to the preview
/// after a short pause in typing (`previewed` is what the preview has).
/// `saved` is the text as it last was on disk; the document is dirty while
/// `source` differs from it.
pub struct Smep {
    editor: Entity<EditorState>,
    preview: Entity<TextViewState>,
    /// The rendered view, editable block by block; shares `editor`'s text.
    rendered: Entity<RenderedView>,
    path: Option<PathBuf>,
    /// The file a converted document came from; names it and places its
    /// first save while it has no path of its own.
    origin: Option<PathBuf>,
    format: PreviewFormat,
    source: SharedString,
    previewed: SharedString,
    saved: SharedString,
    preview_refresh: Option<Task<()>>,
    /// Start line of each top-level block in `previewed`; one preview item each.
    blocks: Vec<usize>,
    /// The editor's top line last pushed to the preview.
    scroll_sync: Option<usize>,
    insert_menu: Option<InsertMenu>,
    settings: Settings,
    /// Editing, or reading: the document rendered and untouchable. Every
    /// launch starts reading; this is not remembered.
    editing: bool,
    /// Focus for the window when no editor is shown (rendered mode), so the
    /// shortcuts bound on the root keep working.
    focus_handle: FocusHandle,
    _subscriptions: Vec<Subscription>,
}

fn preview_state(
    format: PreviewFormat,
    text: &str,
    cx: &mut Context<TextViewState>,
) -> TextViewState {
    match format {
        PreviewFormat::Markdown => TextViewState::markdown(text, cx),
        PreviewFormat::Html => TextViewState::html(text, cx),
    }
}

/// The first buffer line the editor currently renders, once it has laid
/// out. `None` before the first layout.
///
/// The editor lays out only the rows on screen. `range_to_bounds` maps every
/// offset above them to the first rendered line, the rendered lines to
/// increasing tops, and everything below to `None`. So the first rendered
/// line is the last one that still reports the same top as line 0, found by
/// binary search. This holds with soft wrap, where display rows and buffer
/// lines differ.
fn top_visible_line(state: &EditorState) -> Option<usize> {
    let text = state.text();
    let lines = text.lines_len();
    if lines == 0 {
        return Some(0);
    }
    let top_of = |row: usize| {
        let offset = text.line_start_offset(row);
        state.range_to_bounds(&(offset..offset)).map(|b| b.top())
    };
    let first_top = top_of(0)?;
    let (mut last_same, mut beyond) = (0, lines);
    while last_same + 1 < beyond {
        let mid = (last_same + beyond) / 2;
        if top_of(mid) == Some(first_top) {
            last_same = mid;
        } else {
            beyond = mid;
        }
    }
    Some(last_same)
}

impl Smep {
    pub fn new(
        document: Document,
        settings: Settings,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        Theme::sync_system_appearance(Some(window), cx);

        let editor = cx.new(|cx| {
            EditorState::new(window, cx)
                .default_value(document.text.clone())
                .language(highlight::LANGUAGE)
                .soft_wrap(true)
                .line_number(false)
                .searchable(true)
                .placeholder("Write here. Type / on an empty line to insert a block.")
        });
        editor.update(cx, |state, cx| {
            state.set_highlighter_factory(highlight::factory(), cx);
            state.focus(window, cx);
        });
        let preview = cx.new(|cx| preview_state(document.format, &document.text, cx));
        let rendered = cx.new(|cx| RenderedView::new(editor.clone(), document.format, window, cx));

        let subscriptions = vec![
            cx.subscribe_in(
                &rendered,
                window,
                |this, _, event: &RenderedEvent, window, cx| match event {
                    RenderedEvent::SlashTyped => this.open_insert_menu(window, cx),
                },
            ),
            cx.subscribe_in(
                &editor,
                window,
                |this, editor, event: &InputEvent, window, cx| {
                    if let InputEvent::Change = event {
                        let was_dirty = this.is_dirty();
                        this.source = editor.read(cx).value();
                        if this.is_dirty() != was_dirty {
                            this.refresh_title(window);
                        }
                        this.schedule_preview_refresh(window, cx);
                        if Self::slash_typed(editor.read(cx)) {
                            this.open_insert_menu(window, cx);
                        }
                        cx.notify();
                    }
                },
            ),
            // Cursor moves do not emit events; observe so the "+" follows the cursor.
            cx.observe(&editor, |_, _, cx| cx.notify()),
            // A block starting or ending its edit changes where menus send
            // their actions; the menus are rebuilt on render.
            cx.observe(&rendered, |_, _, cx| cx.notify()),
            window.observe_window_appearance(|window, cx| {
                Theme::sync_system_appearance(Some(window), cx);
            }),
        ];

        // Closing with unsaved changes asks first. The platform close is
        // vetoed here and redone once the prompt resolves.
        window.on_window_should_close(cx, {
            let this = cx.weak_entity();
            move |window, cx| {
                let Some(smep) = this.upgrade() else {
                    return true;
                };
                if !smep.read(cx).is_dirty() {
                    return true;
                }
                let proceed = smep.update(cx, |this, cx| this.confirm_discard(window, cx));
                let handle = window.window_handle();
                cx.spawn(async move |cx| {
                    if proceed.await {
                        let _ = handle.update(cx, |_, window, _| window.remove_window());
                    }
                })
                .detach();
                false
            }
        });

        let source: SharedString = document.text.into();
        // A converted document is new and unsaved; a read one is as on disk.
        let saved = if document.origin.is_some() {
            SharedString::default()
        } else {
            source.clone()
        };
        let mut this = Self {
            editor,
            preview,
            rendered,
            path: document.path,
            origin: document.origin,
            format: document.format,
            source: source.clone(),
            previewed: source,
            saved,
            preview_refresh: None,
            blocks: Vec::new(),
            scroll_sync: None,
            insert_menu: None,
            focus_handle: cx.focus_handle(),
            settings,
            editing: false,
            _subscriptions: subscriptions,
        };
        this.schedule_block_table(window, cx);
        this.refresh_title(window);
        // Reading mode: the rendered view, read-only, holds the focus so
        // the root's shortcuts work.
        this.rendered
            .update(cx, |rendered, cx| rendered.set_read_only(true, window, cx));
        this.rendered
            .read(cx)
            .focus_handle()
            .clone()
            .focus(window, cx);
        this
    }

    #[cfg(test)]
    pub fn is_editing(&self) -> bool {
        self.editing
    }

    /// What the window shows: the chosen view mode while editing, the
    /// rendered document while reading.
    pub fn layout(&self) -> ViewMode {
        if self.editing {
            self.settings.view_mode
        } else {
            ViewMode::Rendered
        }
    }

    /// Switch between editing (the remembered view mode) and reading.
    pub fn set_editing(&mut self, editing: bool, window: &mut Window, cx: &mut Context<Self>) {
        if editing {
            self.set_view_mode(self.settings.view_mode, window, cx);
            return;
        }
        if !self.editing {
            return;
        }
        self.editing = false;
        self.insert_menu = None;
        self.rendered
            .update(cx, |rendered, cx| rendered.set_read_only(true, window, cx));
        self.rendered
            .read(cx)
            .focus_handle()
            .clone()
            .focus(window, cx);
        cx.notify();
    }

    pub fn preview_theme(&self) -> PreviewTheme {
        self.settings.preview_theme
    }

    /// Switch the preview theme and remember it. A failed write only warns:
    /// the theme still applies for this session.
    pub fn set_preview_theme(&mut self, theme: PreviewTheme, cx: &mut Context<Self>) {
        if self.settings.preview_theme == theme {
            return;
        }
        self.settings.preview_theme = theme;
        self.save_settings();
        cx.notify();
    }

    pub fn view_mode(&self) -> ViewMode {
        self.settings.view_mode
    }

    /// Show source, split, or rendered; remembered across runs. Choosing a
    /// view mode means editing, so reading mode ends.
    pub fn set_view_mode(&mut self, mode: ViewMode, window: &mut Window, cx: &mut Context<Self>) {
        if self.settings.view_mode != mode {
            self.settings.view_mode = mode;
            self.save_settings();
        }
        self.editing = true;
        self.rendered
            .update(cx, |rendered, cx| rendered.set_read_only(false, window, cx));
        if mode == ViewMode::Rendered {
            // The rendered view takes focus (its active block, if any, takes
            // it from there), so the root's shortcuts keep working.
            match self.rendered.read(cx).active_editor() {
                Some(block) => block.update(cx, |state, cx| state.focus(window, cx)),
                None => self
                    .rendered
                    .read(cx)
                    .focus_handle()
                    .clone()
                    .focus(window, cx),
            }
        } else {
            self.editor.update(cx, |state, cx| state.focus(window, cx));
        }
        cx.notify();
    }

    pub fn menu_bar_shown(&self) -> bool {
        self.settings.menu_bar
    }

    fn save_settings(&self) {
        if let Err(err) = self.settings.save() {
            eprintln!("smep: could not save settings: {err}");
        }
    }

    fn view_source(&mut self, _: &ViewSource, window: &mut Window, cx: &mut Context<Self>) {
        self.set_view_mode(ViewMode::Source, window, cx);
    }

    fn view_split(&mut self, _: &ViewSplit, window: &mut Window, cx: &mut Context<Self>) {
        self.set_view_mode(ViewMode::Split, window, cx);
    }

    fn view_rendered(&mut self, _: &ViewRendered, window: &mut Window, cx: &mut Context<Self>) {
        self.set_view_mode(ViewMode::Rendered, window, cx);
    }

    fn toggle_editing(&mut self, _: &ToggleEditing, window: &mut Window, cx: &mut Context<Self>) {
        self.set_editing(!self.editing, window, cx);
    }

    fn toggle_menu_bar(&mut self, _: &ToggleMenuBar, _: &mut Window, cx: &mut Context<Self>) {
        self.settings.menu_bar = !self.settings.menu_bar;
        self.save_settings();
        cx.notify();
    }

    fn toggle_fullscreen(
        &mut self,
        _: &ToggleFullscreen,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        window.toggle_fullscreen();
        cx.notify();
    }

    /// Quit after the unsaved-changes prompt, if any.
    fn quit(&mut self, _: &Quit, window: &mut Window, cx: &mut Context<Self>) {
        let proceed = self.confirm_discard(window, cx);
        cx.spawn(async move |_, cx| {
            if proceed.await {
                cx.update(|cx| cx.quit());
            }
        })
        .detach();
    }

    /// The File / Edit / View menus for the title bar. Every menu returns
    /// focus to the editor being typed in, so the editing actions land there.
    fn render_menu_bar(&self, cx: &mut Context<Self>) -> AnyElement {
        let editor_focus = self.menu_focus(cx);
        let mode = self.view_mode();
        let editing = self.editing;
        let menu_bar = self.menu_bar_shown();
        let current_theme = self.preview_theme();
        let this = cx.weak_entity();

        let button = |id: &'static str, label: &'static str| {
            Button::new(id)
                .label(label)
                .ghost()
                .xsmall()
                .tab_stop(false)
        };

        h_flex()
            .id("menu-bar")
            .h_full()
            .items_center()
            .gap_0p5()
            .child(button("menu-file", "File").dropdown_menu({
                let focus = editor_focus.clone();
                move |menu, _, _| {
                    menu.menu("Open…", Box::new(Open))
                        .menu("Import as Markdown…", Box::new(Import))
                        .menu("Save", Box::new(Save))
                        .menu("Save As…", Box::new(SaveAs))
                        .separator()
                        .menu("Export as PDF…", Box::new(ExportPdf))
                        .menu("Export as HTML…", Box::new(ExportHtml))
                        .separator()
                        .menu("Open Markdown Files with smep", Box::new(MakeDefault))
                        .separator()
                        .menu("Quit", Box::new(Quit))
                        .action_context(focus.clone())
                }
            }))
            .child(button("menu-edit", "Edit").dropdown_menu({
                let focus = editor_focus.clone();
                move |menu, _, _| {
                    menu.menu("Undo", Box::new(Undo))
                        .menu("Redo", Box::new(Redo))
                        .separator()
                        .menu("Cut", Box::new(Cut))
                        .menu("Copy", Box::new(Copy))
                        .menu("Paste", Box::new(Paste))
                        .menu("Select All", Box::new(SelectAll))
                        .separator()
                        .menu("Find", Box::new(Search))
                        .menu("Replace", Box::new(Replace))
                        .action_context(focus.clone())
                }
            }))
            .child(button("menu-view", "View").dropdown_menu({
                let focus = editor_focus;
                move |mut menu, window, cx| {
                    menu = menu
                        .item(
                            PopupMenuItem::new("Editing")
                                .checked(editing)
                                .action(Box::new(ToggleEditing)),
                        )
                        .separator();
                    for candidate in [ViewMode::Source, ViewMode::Split, ViewMode::Rendered] {
                        let action: Box<dyn Action> = match candidate {
                            ViewMode::Source => Box::new(ViewSource),
                            ViewMode::Split => Box::new(ViewSplit),
                            ViewMode::Rendered => Box::new(ViewRendered),
                        };
                        menu = menu.item(
                            PopupMenuItem::new(candidate.label())
                                .checked(candidate == mode)
                                .action(action),
                        );
                    }
                    let themes = PopupMenu::build(window, cx, |mut submenu, _, _| {
                        for candidate in theme::ALL {
                            let this = this.clone();
                            submenu = submenu.item(
                                PopupMenuItem::new(candidate.label())
                                    .checked(candidate == current_theme)
                                    .on_click(move |_, _, cx| {
                                        let _ = this.update(cx, |this, cx| {
                                            this.set_preview_theme(candidate, cx)
                                        });
                                    }),
                            );
                        }
                        submenu
                    });
                    menu.separator()
                        .item(PopupMenuItem::submenu("Preview Theme", themes))
                        .separator()
                        .item(
                            PopupMenuItem::new("Menu Bar")
                                .checked(menu_bar)
                                .action(Box::new(ToggleMenuBar)),
                        )
                        .menu("Full Screen", Box::new(ToggleFullscreen))
                        .action_context(focus.clone())
                }
            }))
            .into_any_element()
    }

    /// The title bar: menus on the left (when shown), the document in the
    /// middle, the window controls on the right (added by `TitleBar`).
    fn render_title_bar(&self, cx: &mut Context<Self>) -> AnyElement {
        let title = format!(
            "{}{}",
            if self.is_dirty() { "● " } else { "" },
            Document::display_name(self.named_path().as_deref())
        );
        let muted = cx.theme().muted_foreground;
        let menu_bar = self.menu_bar_shown().then(|| self.render_menu_bar(cx));
        // The one switch between reading and editing that needs no key.
        let mode_button = Button::new("edit-toggle")
            .label(if self.editing { "Read" } else { "Edit" })
            .ghost()
            .xsmall()
            .tab_stop(false)
            .on_click(cx.listener(|this, _, window, cx| {
                this.set_editing(!this.editing, window, cx);
            }));
        TitleBar::new()
            .child(
                h_flex()
                    .id("chrome")
                    .flex_1()
                    .h_full()
                    .items_center()
                    .children(menu_bar)
                    .child(div().flex_1())
                    .child(div().text_sm().text_color(muted).child(title))
                    .child(div().flex_1())
                    .child(
                        div()
                            .pr_2()
                            // The title bar starts a window move on mouse
                            // down plus any movement, and the move swallows
                            // the mouse up a click needs; the press stays here.
                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
                            .child(mode_button),
                    ),
            )
            .into_any_element()
    }

    /// Re-parse the preview once typing pauses. Each call restarts the wait.
    fn schedule_preview_refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.preview_refresh = Some(cx.spawn_in(window, async move |this, cx| {
            cx.background_executor().timer(PREVIEW_DEBOUNCE).await;
            let Ok(Some(text)) = this.update(cx, |this, _| {
                (this.previewed != this.source).then(|| this.source.clone())
            }) else {
                return;
            };
            // The block table is a whole-document parse, as costly as the
            // preview's own (which the preview runs off the UI thread too).
            let blocks = cx
                .background_spawn({
                    let text = text.clone();
                    async move { highlight::block_start_lines(&text) }
                })
                .await;
            let _ = this.update(cx, |this, cx| this.show_preview(text, blocks, cx));
        }));
    }

    /// Hand `text` to the preview, with `blocks` its block table.
    fn show_preview(&mut self, text: SharedString, blocks: Vec<usize>, cx: &mut Context<Self>) {
        self.previewed = text.clone();
        self.blocks = blocks;
        self.preview
            .update(cx, |state, cx| state.set_text(&text, cx));
        self.scroll_sync = None;
        cx.notify();
    }

    /// Point the preview and the rendered view at the current source in
    /// `format`, right away. The block table follows a moment later; until
    /// then the scroll sync goes by proportion.
    fn set_preview(&mut self, format: PreviewFormat, window: &mut Window, cx: &mut Context<Self>) {
        self.preview_refresh = None;
        let text = self.source.clone();
        if format != self.format {
            self.format = format;
            self.preview = cx.new(|cx| preview_state(format, &text, cx));
            self.rendered
                .update(cx, |rendered, cx| rendered.set_format(format, window, cx));
        }
        self.show_preview(text, Vec::new(), cx);
        self.schedule_block_table(window, cx);
    }

    /// Compute the block table for what the preview shows, off the UI
    /// thread, and adopt it if the preview still shows that text.
    fn schedule_block_table(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let text = self.previewed.clone();
        self.preview_refresh = Some(cx.spawn_in(window, async move |this, cx| {
            let blocks = cx
                .background_spawn({
                    let text = text.clone();
                    async move { highlight::block_start_lines(&text) }
                })
                .await;
            let _ = this.update(cx, |this, cx| {
                if this.previewed == text {
                    this.blocks = blocks;
                    this.scroll_sync = None;
                    cx.notify();
                }
            });
        }));
    }

    /// Scroll the preview to the block that holds the editor's top line.
    /// Editor scrolling drives the preview; the preview never drives the editor.
    fn sync_preview_scroll(&mut self, cx: &mut Context<Self>) {
        let Some(top) = top_visible_line(self.editor.read(cx)) else {
            return;
        };
        if self.scroll_sync == Some(top) {
            return;
        }
        self.scroll_sync = Some(top);

        let list = self.preview.read(cx).list_state().clone();
        let count = list.item_count();
        if count == 0 {
            return;
        }
        let item_ix = if count == self.blocks.len() {
            // One preview item per block: the last block starting at or above `top`.
            self.blocks
                .partition_point(|&start| start <= top)
                .saturating_sub(1)
        } else {
            // The preview is mid-parse or split blocks differently; go proportional.
            let lines = self.editor.read(cx).text().lines_len().max(1);
            (count * top / lines).min(count - 1)
        };
        list.scroll_to(ListOffset {
            item_ix,
            offset_in_item: px(0.),
        });
    }

    /// The window title for a document: `● name — smep` while dirty.
    pub fn title_for(path: Option<&Path>, dirty: bool) -> String {
        let marker = if dirty { "● " } else { "" };
        format!("{marker}{} — smep", Document::display_name(path))
    }

    pub fn is_dirty(&self) -> bool {
        self.source != self.saved
    }

    /// The document's path, or the one it would suggest: the original's
    /// with `.md` for a converted document. `None` for a blank one.
    fn named_path(&self) -> Option<PathBuf> {
        self.path
            .clone()
            .or_else(|| self.origin.as_deref().map(convert::markdown_path_for))
    }

    fn refresh_title(&self, window: &mut Window) {
        window.set_window_title(&Self::title_for(
            self.named_path().as_deref(),
            self.is_dirty(),
        ));
    }

    /// Replace the buffer with `document`, as after Open or Import.
    fn load(&mut self, document: Document, window: &mut Window, cx: &mut Context<Self>) {
        self.path = document.path;
        self.origin = document.origin;
        self.source = document.text.clone().into();
        self.saved = if self.origin.is_some() {
            SharedString::default()
        } else {
            self.source.clone()
        };
        // `set_value` emits no change event, so `source` is set by hand above
        // and the rendered view is told that its block is gone.
        self.rendered
            .update(cx, |rendered, cx| rendered.deactivate(window, cx));
        self.editor
            .update(cx, |state, cx| state.set_value(document.text, window, cx));
        self.set_preview(document.format, window, cx);
        self.refresh_title(window);
    }

    /// Write the buffer to `path` and adopt it as the document's path.
    fn write_to(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) -> bool {
        let text = self.editor.read(cx).value();
        match io::write(&path, &text) {
            Ok(()) => {
                self.saved = text.clone();
                self.source = text;
                let format = PreviewFormat::for_path(&path);
                self.path = Some(path);
                if format != self.format {
                    self.set_preview(format, window, cx);
                }
                self.refresh_title(window);
                cx.notify();
                true
            }
            Err(err) => {
                self.report(
                    &format!("Could not save {}", path.display()),
                    &err.to_string(),
                    window,
                    cx,
                );
                false
            }
        }
    }

    fn report(&self, what: &str, detail: &str, window: &mut Window, cx: &mut Context<Self>) {
        let answered = window.prompt(PromptLevel::Critical, what, Some(detail), &["OK"], cx);
        cx.spawn(async move |_, _| {
            let _ = answered.await;
        })
        .detach();
    }

    /// Save to the current path, or ask for one. Resolves to whether it saved.
    fn save_task(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<bool> {
        match self.path.clone() {
            Some(path) => Task::ready(self.write_to(path, window, cx)),
            None => self.save_as_task(window, cx),
        }
    }

    /// Ask for a path, then save there. Resolves to whether it saved.
    fn save_as_task(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<bool> {
        let named = self.named_path();
        let directory = named
            .as_deref()
            .and_then(Path::parent)
            .filter(|dir| !dir.as_os_str().is_empty())
            .map(Path::to_path_buf)
            .or_else(|| std::env::current_dir().ok())
            .unwrap_or_default();
        let suggested = named
            .as_deref()
            .map(|path| Document::display_name(Some(path)))
            .unwrap_or_else(|| "untitled.md".to_string());
        let chosen = cx.prompt_for_new_path(&directory, Some(&suggested));

        cx.spawn_in(window, async move |this, cx| {
            let Ok(Ok(Some(path))) = chosen.await else {
                return false;
            };
            this.update_in(cx, |this, window, cx| this.write_to(path, window, cx))
                .unwrap_or(false)
        })
    }

    /// Ask before discarding unsaved changes. Resolves to whether to proceed.
    fn confirm_discard(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<bool> {
        if !self.is_dirty() {
            return Task::ready(true);
        }
        let detail = format!(
            "{} has unsaved changes.",
            Document::display_name(self.named_path().as_deref())
        );
        let answer = window.prompt(
            PromptLevel::Warning,
            "Save changes?",
            Some(&detail),
            &["Save", "Don't Save", "Cancel"],
            cx,
        );

        cx.spawn_in(window, async move |this, cx| match answer.await {
            Ok(0) => match this.update_in(cx, |this, window, cx| this.save_task(window, cx)) {
                Ok(saved) => saved.await,
                Err(_) => false,
            },
            Ok(1) => true,
            _ => false,
        })
    }

    fn open(&mut self, _: &Open, window: &mut Window, cx: &mut Context<Self>) {
        let proceed = self.confirm_discard(window, cx);
        cx.spawn_in(window, async move |this, cx| {
            if !proceed.await {
                return;
            }
            let Ok(chosen) = this.update(cx, |_, cx| {
                cx.prompt_for_paths(PathPromptOptions {
                    files: true,
                    directories: false,
                    multiple: false,
                    prompt: None,
                })
            }) else {
                return;
            };
            let Ok(Ok(Some(paths))) = chosen.await else {
                return;
            };
            let Some(path) = paths.into_iter().next() else {
                return;
            };
            let _ = this.update_in(cx, |this, window, cx| this.load_path(path, window, cx));
        })
        .detach();
    }

    /// Open the file at `path` in this window, asking about unsaved changes
    /// first. This is what a double-click in the file manager ends up in.
    pub fn open_document_at(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
        let proceed = self.confirm_discard(window, cx);
        cx.spawn_in(window, async move |this, cx| {
            if proceed.await {
                let _ = this.update_in(cx, |this, window, cx| this.load_path(path, window, cx));
            }
        })
        .detach();
    }

    /// Read `path` into the buffer, or report why not. A PDF, Word or text
    /// file is converted into a new Markdown document instead.
    fn load_path(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(format) = convert::Format::for_import(&path) {
            self.import_path(path, format, window, cx);
            return;
        }
        match Document::read(path.clone()) {
            Ok(document) => self.load(document, window, cx),
            Err(err) => self.report(
                &format!("Could not open {}", path.display()),
                &err.to_string(),
                window,
                cx,
            ),
        }
    }

    /// Convert `path` off the UI thread (a PDF can take a while), then
    /// load the Markdown as a new, unsaved document.
    fn import_path(
        &mut self,
        path: PathBuf,
        format: convert::Format,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        cx.spawn_in(window, async move |this, cx| {
            let converted = cx
                .background_spawn({
                    let path = path.clone();
                    async move { Document::import(path, format) }
                })
                .await;
            let _ = this.update_in(cx, |this, window, cx| match converted {
                Ok(document) => this.load(document, window, cx),
                Err(err) => this.report(
                    &format!("Could not import {}", path.display()),
                    &format!("{err:#}"),
                    window,
                    cx,
                ),
            });
        })
        .detach();
    }

    /// Pick a file to convert to Markdown: PDF, Word, HTML or text.
    fn import(&mut self, _: &Import, window: &mut Window, cx: &mut Context<Self>) {
        let proceed = self.confirm_discard(window, cx);
        cx.spawn_in(window, async move |this, cx| {
            if !proceed.await {
                return;
            }
            let Ok(chosen) = this.update(cx, |_, cx| {
                cx.prompt_for_paths(PathPromptOptions {
                    files: true,
                    directories: false,
                    multiple: false,
                    prompt: Some("Import".into()),
                })
            }) else {
                return;
            };
            let Ok(Ok(Some(paths))) = chosen.await else {
                return;
            };
            let Some(path) = paths.into_iter().next() else {
                return;
            };
            let _ = this.update_in(cx, |this, window, cx| {
                match convert::Format::for_explicit_import(&path) {
                    Some(format) => this.import_path(path, format, window, cx),
                    None => this.report(
                        &format!("Cannot import {}", path.display()),
                        "smep converts PDF (.pdf), Word (.docx), HTML (.html) and text (.txt) files.",
                        window,
                        cx,
                    ),
                }
            });
        })
        .detach();
    }

    /// Ask where to put an export of the document with `extension`: next to
    /// it, named after it. Resolves to the chosen path.
    fn ask_export_path(&self, extension: &str, cx: &mut Context<Self>) -> Task<Option<PathBuf>> {
        let named = self.named_path();
        let directory = named
            .as_deref()
            .and_then(Path::parent)
            .filter(|dir| !dir.as_os_str().is_empty())
            .map(Path::to_path_buf)
            .or_else(|| std::env::current_dir().ok())
            .unwrap_or_default();
        let stem = named
            .as_deref()
            .and_then(Path::file_stem)
            .map(|stem| stem.to_string_lossy().into_owned())
            .unwrap_or_else(|| "untitled".to_string());
        let chosen = cx.prompt_for_new_path(&directory, Some(&format!("{stem}.{extension}")));
        cx.background_spawn(async move {
            match chosen.await {
                Ok(Ok(Some(path))) => Some(path),
                _ => None,
            }
        })
    }

    /// Typeset the document as a PDF (off the UI thread; Typst takes a
    /// moment) and write it where the user asks.
    fn export_pdf(&mut self, _: &ExportPdf, window: &mut Window, cx: &mut Context<Self>) {
        let chosen = self.ask_export_path("pdf", cx);
        let text = self.editor.read(cx).value();
        let base = self
            .named_path()
            .as_deref()
            .and_then(Path::parent)
            .filter(|dir| !dir.as_os_str().is_empty())
            .map(Path::to_path_buf);
        cx.spawn_in(window, async move |this, cx| {
            let Some(path) = chosen.await else {
                return;
            };
            let written = cx
                .background_spawn({
                    let path = path.clone();
                    async move {
                        let pdf = export::to_pdf(&text, base.as_deref())?;
                        std::fs::write(&path, pdf)?;
                        anyhow::Ok(())
                    }
                })
                .await;
            if let Err(err) = written {
                let _ = this.update_in(cx, |this, window, cx| {
                    this.report(
                        &format!("Could not export {}", path.display()),
                        &format!("{err:#}"),
                        window,
                        cx,
                    )
                });
            }
        })
        .detach();
    }

    /// The document as a standalone HTML page, written where the user asks.
    fn export_html(&mut self, _: &ExportHtml, window: &mut Window, cx: &mut Context<Self>) {
        let chosen = self.ask_export_path("html", cx);
        let text = self.editor.read(cx).value();
        let title = export::first_heading(&text)
            .unwrap_or_else(|| Document::display_name(self.named_path().as_deref()));
        cx.spawn_in(window, async move |this, cx| {
            let Some(path) = chosen.await else {
                return;
            };
            if let Err(err) = std::fs::write(&path, export::to_html(&text, &title)) {
                let _ = this.update_in(cx, |this, window, cx| {
                    this.report(
                        &format!("Could not export {}", path.display()),
                        &err.to_string(),
                        window,
                        cx,
                    )
                });
            }
        })
        .detach();
    }

    /// Become the system's program for Markdown files, as far as it allows,
    /// and say what happened (or what is left to do).
    fn make_default(&mut self, _: &MakeDefault, window: &mut Window, cx: &mut Context<Self>) {
        cx.spawn_in(window, async move |this, cx| {
            let outcome = cx
                .background_spawn(async { defaults::make_default() })
                .await;
            let _ = this.update_in(cx, |this, window, cx| match outcome {
                Ok(outcome) => {
                    let title = if outcome.done {
                        "smep is the default for Markdown"
                    } else {
                        "One step left"
                    };
                    let answered = window.prompt(
                        PromptLevel::Info,
                        title,
                        Some(&outcome.message),
                        &["OK"],
                        cx,
                    );
                    cx.spawn(async move |_, _| {
                        let _ = answered.await;
                    })
                    .detach();
                }
                Err(err) => this.report(
                    "Could not make smep the default for Markdown",
                    &format!("{err:#}"),
                    window,
                    cx,
                ),
            });
        })
        .detach();
    }

    /// Files dropped on the window: the first one opens (or, for a PDF,
    /// Word or text file, is converted), after the unsaved-changes prompt.
    fn on_drop(&mut self, paths: &ExternalPaths, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(path) = paths.paths().first() {
            self.open_document_at(path.clone(), window, cx);
        }
    }

    fn save(&mut self, _: &Save, window: &mut Window, cx: &mut Context<Self>) {
        self.save_task(window, cx).detach();
    }

    fn save_as(&mut self, _: &SaveAs, window: &mut Window, cx: &mut Context<Self>) {
        self.save_as_task(window, cx).detach();
    }

    /// A lone `/` on the cursor's line, with the cursor after it.
    fn slash_typed(state: &EditorState) -> bool {
        insert::cursor_line_trimmed(state) == "/"
            && state.cursor() == insert::cursor_line_range(state).end
    }

    /// The editor the user is typing in: the active block in the rendered
    /// view, otherwise the source editor.
    fn active_editor(&self, cx: &App) -> ActiveEditor {
        if self.layout() == ViewMode::Rendered
            && let Some(editor) = self.rendered.read(cx).active_editor()
        {
            return ActiveEditor::Block(editor);
        }
        ActiveEditor::Source(self.editor.clone())
    }

    /// Window-space bounds of the cursor's line, once the editor has laid out.
    fn cursor_line_bounds(&self, cx: &App) -> Option<Bounds<Pixels>> {
        self.active_editor(cx).cursor_line_bounds(cx)
    }

    /// Where a menu's actions are dispatched from, and where focus returns
    /// when it closes: the editor being typed in, or the rendered view while
    /// no block is being edited (the source editor is not on screen then,
    /// and an action sent through its focus handle would go nowhere).
    fn menu_focus(&self, cx: &App) -> FocusHandle {
        match self.active_editor(cx) {
            ActiveEditor::Source(_) if self.layout() == ViewMode::Rendered => {
                self.rendered.read(cx).focus_handle().clone()
            }
            editor => editor.focus_handle(cx),
        }
    }

    /// Open a popup menu at `position`, replacing any menu already open.
    /// Actions in it dispatch from the editor, and focus returns there.
    fn open_menu(
        &mut self,
        position: Point<Pixels>,
        build: impl FnOnce(PopupMenu) -> PopupMenu,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let editor_focus = self.menu_focus(cx);
        let menu = PopupMenu::build(window, cx, |menu, _, _| {
            build(menu).action_context(editor_focus)
        });
        let dismiss = cx.subscribe_in(&menu, window, |this, _, _: &DismissEvent, _, cx| {
            this.insert_menu = None;
            cx.notify();
        });
        self.insert_menu = Some(InsertMenu {
            menu,
            position,
            _dismiss: dismiss,
        });
        cx.notify();
    }

    /// The block entries, one per snippet, inserting at the editor's cursor.
    fn insert_items(editor: &ActiveEditor, mut menu: PopupMenu) -> PopupMenu {
        for entry in insert::MENU {
            menu = match entry {
                Some(kind) => {
                    let kind = *kind;
                    let editor = editor.clone();
                    menu.item(
                        PopupMenuItem::new(kind.label())
                            .on_click(move |_, window, cx| editor.insert(kind, window, cx)),
                    )
                }
                None => menu.separator(),
            };
        }
        menu
    }

    /// Open the block menu under the cursor's line.
    pub fn open_insert_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.insert_menu.is_some() {
            return;
        }
        let Some(bounds) = self.cursor_line_bounds(cx) else {
            return;
        };
        let editor = self.active_editor(cx);
        self.open_menu(
            bounds.bottom_left(),
            move |menu| Self::insert_items(&editor, menu),
            window,
            cx,
        );
    }

    /// The editor's right-click menu: clipboard, then the blocks. The editor
    /// has already moved the cursor to the click, so blocks land there.
    pub fn open_context_menu(
        &mut self,
        position: Point<Pixels>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let editor = self.active_editor(cx);
        self.open_menu(
            position,
            move |menu| {
                let menu = menu
                    .menu("Cut", Box::new(Cut))
                    .menu("Copy", Box::new(Copy))
                    .menu("Paste", Box::new(Paste))
                    .separator();
                Self::insert_items(&editor, menu)
            },
            window,
            cx,
        );
    }

    /// The preview's right-click menu: pick a theme.
    pub fn open_theme_menu(
        &mut self,
        position: Point<Pixels>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let current = self.preview_theme();
        let this = cx.weak_entity();
        self.open_menu(
            position,
            move |mut menu| {
                for theme in theme::ALL {
                    let this = this.clone();
                    menu = menu.item(
                        PopupMenuItem::new(theme.label())
                            .checked(theme == current)
                            .on_click(move |_, _, cx| {
                                let _ =
                                    this.update(cx, |this, cx| this.set_preview_theme(theme, cx));
                            }),
                    );
                }
                menu
            },
            window,
            cx,
        );
    }

    /// A click in the editor below its last line: the Feishu gesture for
    /// "add something at the end". The editor handles the click first (it
    /// moves the cursor); the menu opens on the deferred pass, at the end.
    fn on_editor_mouse_down(
        &mut self,
        event: &MouseDownEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if event.button != MouseButton::Left || !self.is_below_text(event.position, cx) {
            return;
        }
        let this = cx.entity();
        window.defer(cx, move |window, cx| {
            this.update(cx, |this, cx| {
                this.editor.update(cx, |state, cx| {
                    let end = state.text().len();
                    state.set_selected_range(end..end, cx);
                });
                this.open_insert_menu(window, cx);
            });
        });
    }

    /// Whether `position` is inside the editor but under its last line.
    /// The last line answers `None` while it is scrolled out of view, and
    /// then nothing is "below the text".
    fn is_below_text(&self, position: Point<Pixels>, cx: &App) -> bool {
        let state = self.editor.read(cx);
        if !state.input_bounds().contains(&position) {
            return false;
        }
        let len = state.text().len();
        match state.range_to_bounds(&(len..len)) {
            Some(last) => position.y > last.bottom(),
            None => false,
        }
    }

    /// The "+" beside an empty line while the editor has focus.
    fn render_plus(&self, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
        if self.insert_menu.is_some() {
            return None;
        }
        let editor = self.active_editor(cx);
        if !editor.focus_handle(cx).is_focused(window) || !editor.cursor_line_is_blank(cx) {
            return None;
        }
        let bounds = editor.cursor_line_bounds(cx)?;

        let size = px(18.);
        let origin = point(
            bounds.left() - px(24.),
            bounds.top() + (bounds.size.height - size) / 2.,
        );
        let border = cx.theme().border;
        let color = cx.theme().muted_foreground;
        let hover = cx.theme().muted;

        let plus = div()
            .id("insert-plus")
            .size(size)
            .flex()
            .items_center()
            .justify_center()
            .rounded_full()
            .border_1()
            .border_color(border)
            .text_color(color)
            .text_sm()
            .cursor_pointer()
            .hover(move |style| style.bg(hover))
            .child("+")
            .on_click(cx.listener(|this, _, window, cx| this.open_insert_menu(window, cx)));

        Some(
            deferred(anchored().position(origin).child(plus))
                .with_priority(1)
                .into_any_element(),
        )
    }

    /// The open insert menu, focused so the keyboard drives it.
    fn render_insert_menu(
        &self,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Option<AnyElement> {
        let open = self.insert_menu.as_ref()?;
        let focus = open.menu.focus_handle(cx);
        if !focus.contains_focused(window, cx) {
            focus.focus(window, cx);
        }
        Some(
            deferred(
                anchored()
                    .position(open.position)
                    .anchor(Anchor::TopLeft)
                    .snap_to_window_with_margin(px(8.))
                    .child(open.menu.clone()),
            )
            .with_priority(POPUP_PRIORITY)
            .into_any_element(),
        )
    }
}

impl Render for Smep {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        // The editor lays out before the preview (it comes first in the
        // split), so by the preview's prepaint the editor's rows for this
        // frame are known and the preview can follow them in the same frame.
        let follow_editor = {
            let this = cx.weak_entity();
            move |_, _: &mut Window, cx: &mut App| {
                let _ = this.update(cx, |this, cx| this.sync_preview_scroll(cx));
            }
        };
        let palette = self.preview_theme().palette();
        let background = palette.map_or(cx.theme().background, |p| p.background);
        let foreground = palette.map_or(cx.theme().foreground, |p| p.foreground);
        let preview = div()
            .id("preview")
            .size_full()
            .overflow_hidden()
            .bg(background)
            .text_color(foreground)
            .when_some(palette.and_then(|p| p.font_family()), |this, family| {
                this.font_family(family)
            })
            .px_6()
            .py_4()
            .on_mouse_down(
                MouseButton::Right,
                cx.listener(|this, event: &MouseDownEvent, window, cx| {
                    this.open_theme_menu(event.position, window, cx);
                }),
            )
            .on_prepaint(follow_editor)
            .child(
                TextView::new(&self.preview)
                    .scrollable(true)
                    .when_some(palette, |view, p| view.style(p.text_view_style())),
            );

        // Right-click: the editor moves the cursor to the click, then hands
        // over here while it is still borrowed, so the menu opens one step
        // later. An empty native menu is returned, so none shows.
        let context_menu = {
            let this = cx.weak_entity();
            move |menu, window: &mut Window, cx: &mut App| {
                let position = window.mouse_position();
                let this = this.clone();
                window.defer(cx, move |window, cx| {
                    let _ =
                        this.update(cx, |this, cx| this.open_context_menu(position, window, cx));
                });
                menu
            }
        };
        let editor = div()
            .id("editor")
            .size_full()
            .on_mouse_down(MouseButton::Left, cx.listener(Self::on_editor_mouse_down))
            .child(
                Editor::new(&self.editor)
                    .bordered(false)
                    .size_full()
                    .pl(px(28.))
                    .context_menu(context_menu),
            );

        let plus = self.render_plus(window, cx);
        let menu = self.render_insert_menu(window, cx);
        let title_bar = self.render_title_bar(cx);

        let content = match self.layout() {
            ViewMode::Source => editor.into_any_element(),
            ViewMode::Rendered => {
                self.rendered
                    .update(cx, |rendered, cx| rendered.set_palette(palette, cx));
                // Right-click picks the theme here as on the split preview
                // (an open block keeps its own menu and stops the event).
                div()
                    .id("rendered-pane")
                    .size_full()
                    .on_mouse_down(
                        MouseButton::Right,
                        cx.listener(|this, event: &MouseDownEvent, window, cx| {
                            this.open_theme_menu(event.position, window, cx);
                        }),
                    )
                    .child(self.rendered.clone())
                    .into_any_element()
            }
            ViewMode::Split => h_resizable("smep-split")
                .child(resizable_panel().child(editor.into_any_element()))
                .child(resizable_panel().child(preview.into_any_element()))
                .into_any_element(),
        };

        let drop_highlight = cx.theme().ring;
        window_border().child(
            v_flex()
                .size_full()
                .key_context(keymap::CONTEXT)
                .track_focus(&self.focus_handle)
                // Files from the desktop: a border while they hover, open on drop.
                .drag_over::<ExternalPaths>(move |style, _, _, _| {
                    style.border_2().border_color(drop_highlight)
                })
                .on_drop(cx.listener(Self::on_drop))
                .on_action(cx.listener(Self::open))
                .on_action(cx.listener(Self::import))
                .on_action(cx.listener(Self::export_pdf))
                .on_action(cx.listener(Self::export_html))
                .on_action(cx.listener(Self::make_default))
                .on_action(cx.listener(Self::save))
                .on_action(cx.listener(Self::save_as))
                .on_action(cx.listener(Self::quit))
                .on_action(cx.listener(Self::view_source))
                .on_action(cx.listener(Self::view_split))
                .on_action(cx.listener(Self::view_rendered))
                .on_action(cx.listener(Self::toggle_editing))
                .on_action(cx.listener(Self::toggle_menu_bar))
                .on_action(cx.listener(Self::toggle_fullscreen))
                .child(title_bar)
                .child(div().flex_1().min_h_0().w_full().child(content))
                .children(plus)
                .children(menu),
        )
    }
}

#[cfg(test)]
mod tests {
    // Not `use gpui_kit::*`: with `test-support` on, the glob would also pull
    // in GPUI's `test` attribute and shadow the built-in `#[test]`.
    use std::path::{Path, PathBuf};

    use gpui_kit::base::input::{InputBaseState, InputModeKind};
    use gpui_kit::component::input::{EditorState, Position, TextareaState};
    use gpui_kit::{
        Entity, Focusable as _, MouseButton, MouseDownEvent, TestAppContext, VisualTestContext,
        point, px,
    };

    use super::{PREVIEW_DEBOUNCE, PreviewFormat, Smep};
    use crate::insert::{self, BlockKind};
    use crate::io::Document;
    use crate::keymap::{Open, Save};
    use crate::settings::{Settings, ViewMode};
    use crate::theme::PreviewTheme;

    /// `cmd-…` on macOS, `ctrl-…` elsewhere, as in the key bindings.
    fn primary(keys: &str) -> String {
        format!(
            "{}-{keys}",
            if cfg!(target_os = "macos") {
                "cmd"
            } else {
                "ctrl"
            }
        )
    }

    fn open<'a>(
        cx: &'a mut TestAppContext,
        text: &str,
    ) -> (Entity<Smep>, &'a mut VisualTestContext) {
        open_document(
            cx,
            Document {
                path: None,
                text: text.to_string(),
                format: PreviewFormat::Markdown,
                origin: None,
            },
        )
    }

    fn open_document(
        cx: &mut TestAppContext,
        document: Document,
    ) -> (Entity<Smep>, &mut VisualTestContext) {
        open_with(cx, document, Settings::default())
    }

    /// A window in editing mode (what most tests exercise); smep itself
    /// starts reading, see `open_reading`.
    fn open_with(
        cx: &mut TestAppContext,
        document: Document,
        settings: Settings,
    ) -> (Entity<Smep>, &mut VisualTestContext) {
        let (smep, cx) = open_reading(cx, document, settings);
        cx.update(|window, cx| {
            smep.update(cx, |this, cx| this.set_editing(true, window, cx));
        });
        (smep, cx)
    }

    /// A window as smep opens it: reading.
    fn open_reading(
        cx: &mut TestAppContext,
        document: Document,
        settings: Settings,
    ) -> (Entity<Smep>, &mut VisualTestContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            crate::theme::install(cx);
            crate::keymap::init(cx);
        });
        cx.add_window_view(|window, cx| Smep::new(document, settings, window, cx))
    }

    fn mouse_down(cx: &mut VisualTestContext, button: MouseButton, x: f32, y: f32) {
        cx.simulate_event(MouseDownEvent {
            button,
            position: point(px(x), px(y)),
            modifiers: Default::default(),
            click_count: 1,
            first_mouse: false,
        });
        cx.run_until_parked();
    }

    fn editor(smep: &Entity<Smep>, cx: &VisualTestContext) -> Entity<EditorState> {
        cx.read(|cx| smep.read(cx).editor.clone())
    }

    fn draw(cx: &mut VisualTestContext) {
        cx.run_until_parked();
        cx.update(|window, cx| {
            _ = window.draw(cx);
        });
    }

    fn value<M: InputModeKind>(
        editor: &Entity<InputBaseState<M>>,
        cx: &VisualTestContext,
    ) -> String {
        cx.read(|cx| editor.read(cx).value().to_string())
    }

    fn menu_open(smep: &Entity<Smep>, cx: &VisualTestContext) -> bool {
        cx.read(|cx| smep.read(cx).insert_menu.is_some())
    }

    fn dirty(smep: &Entity<Smep>, cx: &VisualTestContext) -> bool {
        cx.read(|cx| smep.read(cx).is_dirty())
    }

    fn type_text<M: InputModeKind>(
        editor: &Entity<InputBaseState<M>>,
        text: &str,
        cx: &mut VisualTestContext,
    ) {
        cx.update(|window, cx| {
            editor.update(cx, |state, cx| state.replace_all(text, window, cx));
        });
    }

    /// A fresh directory under the system temp dir, removed on drop.
    struct TempDir(PathBuf);

    impl TempDir {
        fn new(tag: &str) -> Self {
            let dir = std::env::temp_dir().join(format!("smep-{tag}-{}", std::process::id()));
            std::fs::create_dir_all(&dir).unwrap();
            Self(dir)
        }

        fn path(&self, name: &str) -> PathBuf {
            self.0.join(name)
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[gpui_kit::test]
    fn an_edit_in_the_editor_reaches_the_preview(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);

        type_text(&editor, "# Hello", cx);

        assert_eq!(cx.read(|cx| smep.read(cx).source.to_string()), "# Hello");
    }

    #[gpui_kit::test]
    fn the_preview_follows_after_a_pause_in_typing(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);

        type_text(&editor, "# One", cx);
        type_text(&editor, "# One two", cx);
        assert_eq!(cx.read(|cx| smep.read(cx).previewed.to_string()), "");

        cx.executor().advance_clock(PREVIEW_DEBOUNCE);
        cx.run_until_parked();
        assert_eq!(
            cx.read(|cx| smep.read(cx).previewed.to_string()),
            "# One two"
        );
    }

    #[gpui_kit::test]
    fn scrolling_the_editor_scrolls_the_preview(cx: &mut TestAppContext) {
        let text: String = (1..=400).map(|n| format!("Paragraph {n}\n\n")).collect();
        let (smep, cx) = open(cx, &text);
        let editor = editor(&smep, cx);
        draw(cx);
        let list = cx.read(|cx| smep.read(cx).preview.read(cx).list_state().clone());
        assert_eq!(list.logical_scroll_top().item_ix, 0);
        assert!(list.item_count() > 100, "one item per paragraph");

        cx.update(|_, cx| {
            editor.update(cx, |state, cx| {
                state.set_scroll_offset(gpui_kit::point(gpui_kit::px(0.), gpui_kit::px(-5000.)), cx)
            });
        });
        draw(cx);
        draw(cx);

        // 5000 px at the editor's row height lands well past line 100; each
        // paragraph is two buffer lines, so the preview item is about half that.
        // No soft wrap kicks in for these short lines, so the display row the
        // editor reports is also the buffer line.
        let display_row = cx.read(|cx| editor.read(cx).visible_row_range().unwrap().start);
        let top_line = cx.read(|cx| smep.read(cx).scroll_sync);
        let top_line = top_line.expect("the editor has laid out");
        assert!(top_line > 100, "editor top line {top_line}");
        assert_eq!(top_line, display_row);
        let item = list.logical_scroll_top().item_ix;
        assert_eq!(item, top_line / 2, "preview item for line {top_line}");
    }

    #[gpui_kit::test]
    fn the_initial_text_is_the_preview_source(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "- one\n- two");
        let editor = editor(&smep, cx);

        assert_eq!(
            cx.read(|cx| smep.read(cx).source.to_string()),
            "- one\n- two"
        );
        assert_eq!(value(&editor, cx), "- one\n- two");
        assert!(!dirty(&smep, cx));
    }

    #[gpui_kit::test]
    fn editing_marks_the_document_dirty_and_saving_clears_it(cx: &mut TestAppContext) {
        let dir = TempDir::new("save");
        let path = dir.path("notes.md");
        std::fs::write(&path, "before").unwrap();
        let (smep, cx) = open_document(cx, Document::read(path.clone()).unwrap());
        let editor = editor(&smep, cx);
        assert!(!dirty(&smep, cx));

        type_text(&editor, "after\r\n", cx);
        assert!(dirty(&smep, cx));
        assert_eq!(
            cx.read(|cx| Smep::title_for(smep.read(cx).path.as_deref(), true)),
            "● notes.md — smep"
        );

        cx.update(|window, cx| smep.update(cx, |this, cx| this.save(&Save, window, cx)));
        cx.run_until_parked();

        assert!(!dirty(&smep, cx));
        assert_eq!(std::fs::read(&path).unwrap(), b"after\r\n");
        // Undoing back to the saved text is clean again; one more edit is not.
        type_text(&editor, "before", cx);
        assert!(dirty(&smep, cx));
    }

    #[gpui_kit::test]
    async fn saving_an_untitled_document_asks_for_a_path(cx: &mut TestAppContext) {
        let dir = TempDir::new("save-as");
        let target = dir.path("chosen.md");
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);
        type_text(&editor, "fresh", cx);

        // The dialog is pending only once the task has asked for it.
        let saved = cx.update(|window, cx| smep.update(cx, |this, cx| this.save_task(window, cx)));
        cx.simulate_new_path_selection({
            let target = target.clone();
            move |_| Some(target)
        });

        assert!(saved.await);
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "fresh");
        assert!(!dirty(&smep, cx));
        assert_eq!(cx.read(|cx| smep.read(cx).path.clone()), Some(target));
    }

    #[gpui_kit::test]
    async fn cancelling_save_as_leaves_the_document_dirty(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);
        type_text(&editor, "fresh", cx);

        let saved = cx.update(|window, cx| smep.update(cx, |this, cx| this.save_task(window, cx)));
        cx.simulate_new_path_selection(|_| None);

        assert!(!saved.await);
        assert!(dirty(&smep, cx));
        assert_eq!(cx.read(|cx| smep.read(cx).path.clone()), None);
    }

    #[gpui_kit::test]
    async fn discarding_asks_only_while_dirty(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);

        let clean =
            cx.update(|window, cx| smep.update(cx, |this, cx| this.confirm_discard(window, cx)));
        assert!(clean.await, "a clean document needs no prompt");
        assert!(!cx.has_pending_prompt());

        type_text(&editor, "unsaved", cx);
        let proceed =
            cx.update(|window, cx| smep.update(cx, |this, cx| this.confirm_discard(window, cx)));
        assert!(cx.has_pending_prompt());
        cx.simulate_prompt_answer("Cancel");
        assert!(!proceed.await, "cancel keeps the document");

        let proceed =
            cx.update(|window, cx| smep.update(cx, |this, cx| this.confirm_discard(window, cx)));
        cx.simulate_prompt_answer("Don't Save");
        assert!(proceed.await, "don't save proceeds without writing");
        assert!(dirty(&smep, cx));
    }

    #[gpui_kit::test]
    fn open_replaces_the_buffer_and_resets_dirty(cx: &mut TestAppContext) {
        let dir = TempDir::new("open");
        let path = dir.path("other.html");
        std::fs::write(&path, "<b>bold</b>").unwrap();
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);

        cx.update(|window, cx| smep.update(cx, |this, cx| this.open(&Open, window, cx)));
        // The task asks for the file only after the (clean) discard check resolves.
        cx.run_until_parked();
        assert!(cx.did_prompt_for_paths());
        cx.simulate_path_prompt_response({
            let path = path.clone();
            move |_| Some(vec![path])
        });
        cx.run_until_parked();

        assert_eq!(value(&editor, cx), "<b>bold</b>");
        assert_eq!(
            cx.read(|cx| smep.read(cx).previewed.to_string()),
            "<b>bold</b>",
            "open refreshes the preview at once, no debounce"
        );
        assert_eq!(
            cx.read(|cx| smep.read(cx).source.to_string()),
            "<b>bold</b>"
        );
        assert_eq!(cx.read(|cx| smep.read(cx).format), PreviewFormat::Html);
        assert_eq!(cx.read(|cx| smep.read(cx).path.clone()), Some(path));
        assert!(!dirty(&smep, cx));
    }

    #[gpui_kit::test]
    fn view_modes_switch_by_keyboard_and_are_remembered(cx: &mut TestAppContext) {
        let dir = TempDir::new("view-mode");
        let settings = Settings {
            path: Some(dir.path("settings.toml")),
            ..Settings::default()
        };
        let document = Document {
            path: None,
            text: "# T".into(),
            format: PreviewFormat::Markdown,
            origin: None,
        };
        let (smep, cx) = open_with(cx, document, settings);
        let editor = editor(&smep, cx);
        cx.update(|window, cx| editor.update(cx, |state, cx| state.focus(window, cx)));
        draw(cx);
        assert_eq!(cx.read(|cx| smep.read(cx).view_mode()), ViewMode::Split);

        cx.simulate_keystrokes(&primary("1"));
        cx.run_until_parked();
        assert_eq!(cx.read(|cx| smep.read(cx).view_mode()), ViewMode::Source);
        assert!(
            std::fs::read_to_string(dir.path("settings.toml"))
                .unwrap()
                .contains("view_mode = \"source\"")
        );

        cx.simulate_keystrokes(&primary("3"));
        cx.run_until_parked();
        draw(cx);
        assert_eq!(cx.read(|cx| smep.read(cx).view_mode()), ViewMode::Rendered);

        // Back to split: keystrokes still reach the root even though the
        // editor was not rendered in the rendered mode.
        cx.simulate_keystrokes(&primary("2"));
        cx.run_until_parked();
        assert_eq!(cx.read(|cx| smep.read(cx).view_mode()), ViewMode::Split);
    }

    #[gpui_kit::test]
    fn opens_reading_and_a_key_or_the_view_menu_starts_editing(cx: &mut TestAppContext) {
        let dir = TempDir::new("reading");
        let settings = Settings {
            path: Some(dir.path("settings.toml")),
            ..Settings::default()
        };
        let document = Document {
            path: None,
            text: "# Title\n\npara".into(),
            format: PreviewFormat::Markdown,
            origin: None,
        };
        let (smep, cx) = open_reading(cx, document, settings);
        draw(cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        let reading = |cx: &VisualTestContext| {
            cx.read(|cx| {
                let this = smep.read(cx);
                (
                    !this.is_editing(),
                    this.layout(),
                    this.rendered.read(cx).is_read_only(),
                )
            })
        };
        assert_eq!(reading(cx), (true, ViewMode::Rendered, true));
        assert_eq!(cx.read(|cx| smep.read(cx).view_mode()), ViewMode::Split);
        assert!(
            cx.update(|window, cx| rendered.read(cx).focus_handle().is_focused(window)),
            "the rendered view holds the focus while reading"
        );

        // A click on a block does nothing while reading.
        activate_block(&smep, 9..13, cx);
        assert!(cx.read(|cx| rendered.read(cx).active_editor()).is_none());

        // The editing key brings the remembered view mode (split) back.
        cx.simulate_keystrokes(&primary("e"));
        cx.run_until_parked();
        draw(cx);
        assert_eq!(reading(cx), (false, ViewMode::Split, false));
        let source = editor(&smep, cx);
        assert!(
            cx.update(|window, cx| source.read(cx).focus_handle(cx).is_focused(window)),
            "the source editor takes the focus for editing"
        );

        // And back to reading: an edit in progress ends.
        rendered_mode(&smep, cx);
        activate_block(&smep, 9..13, cx);
        assert!(cx.read(|cx| rendered.read(cx).active_editor()).is_some());
        cx.simulate_keystrokes(&primary("e"));
        cx.run_until_parked();
        draw(cx);
        assert_eq!(reading(cx), (true, ViewMode::Rendered, true));
        assert!(cx.read(|cx| rendered.read(cx).active_editor()).is_none());

        // A view-mode key while reading means editing in that mode.
        cx.simulate_keystrokes(&primary("1"));
        cx.run_until_parked();
        assert_eq!(reading(cx), (false, ViewMode::Source, false));

        // Reading is not a setting: the file knows the view mode only.
        let saved = std::fs::read_to_string(dir.path("settings.toml")).unwrap();
        assert!(saved.contains("view_mode = \"source\""), "{saved}");
        assert!(!saved.contains("editing"), "{saved}");
    }

    #[gpui_kit::test]
    fn an_html_document_is_one_html_block_in_the_rendered_view(cx: &mut TestAppContext) {
        let dir = TempDir::new("html-rendered");
        let page = dir.path("page.html");
        let html = "<h1>Title</h1>\n<p>Some <b>bold</b> text.</p>\n\n<ul><li>one</li></ul>\n";
        std::fs::write(&page, html).unwrap();
        let document = Document::read(page.clone()).unwrap();
        let settings = Settings::default();
        let (smep, cx) = open_reading(cx, document, settings);
        draw(cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());

        // Reading an .html file: the whole page is one block, rendered as
        // HTML, not Markdown's reading of the tags (which would be several).
        assert_eq!(
            cx.read(|cx| rendered.read(cx).format()),
            PreviewFormat::Html
        );
        assert_eq!(
            cx.read(|cx| rendered.read(cx).block_ranges()),
            vec![0..html.trim_end().len()]
        );
        assert!(
            crate::highlight::block_ranges(html).len() > 1,
            "Markdown would split it"
        );

        // Opening a Markdown document switches the view back to blocks.
        let notes = dir.path("notes.md");
        std::fs::write(&notes, "# T\n\npara\n").unwrap();
        cx.update(|window, cx| {
            smep.update(cx, |this, cx| this.load_path(notes.clone(), window, cx))
        });
        draw(cx);
        assert_eq!(
            cx.read(|cx| rendered.read(cx).format()),
            PreviewFormat::Markdown
        );
        assert_eq!(
            cx.read(|cx| rendered.read(cx).block_ranges()),
            vec![0..3, 5..9]
        );

        // Save As to .html while a block is open: the edit ends, one block again.
        rendered_mode(&smep, cx);
        activate_block(&smep, 5..9, cx);
        let saved =
            cx.update(|window, cx| smep.update(cx, |this, cx| this.save_as_task(window, cx)));
        let target = dir.path("notes.html");
        cx.simulate_new_path_selection({
            let target = target.clone();
            move |_| Some(target)
        });
        cx.run_until_parked();
        assert!(cx.read(|cx| rendered.read(cx).active_editor()).is_none());
        assert_eq!(
            cx.read(|cx| rendered.read(cx).format()),
            PreviewFormat::Html
        );
        assert_eq!(cx.read(|cx| rendered.read(cx).block_ranges()), vec![0..9]);
        drop(saved);
    }

    #[gpui_kit::test]
    fn keys_scroll_the_rendered_view_while_reading(cx: &mut TestAppContext) {
        let text: String = (1..=200).map(|n| format!("Paragraph {n}\n\n")).collect();
        let document = Document {
            path: None,
            text,
            format: PreviewFormat::Markdown,
            origin: None,
        };
        let (smep, cx) = open_reading(cx, document, Settings::default());
        draw(cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        let scroll =
            |cx: &VisualTestContext| cx.read(|cx| rendered.read(cx).scroll_handle().clone());
        let offset = |cx: &mut VisualTestContext| {
            draw(cx);
            f32::from(scroll(cx).offset().y)
        };
        let viewport = f32::from(scroll(cx).bounds().size.height);
        let max = f32::from(scroll(cx).max_offset().y);
        assert!(
            max > 2. * viewport,
            "the document must overflow: {max} vs {viewport}"
        );
        assert_eq!(offset(cx), 0.);

        cx.simulate_keystrokes("pagedown");
        let after_page = offset(cx);
        assert_eq!(after_page, -(viewport - 40.), "a page less a line");
        cx.simulate_keystrokes("space");
        assert_eq!(offset(cx), 2. * after_page);
        cx.simulate_keystrokes("shift-space pageup");
        assert_eq!(offset(cx), 0.);
        cx.simulate_keystrokes("down down up");
        assert_eq!(offset(cx), -40.);
        cx.simulate_keystrokes("end");
        assert_eq!(offset(cx), -max);
        cx.simulate_keystrokes("pagedown");
        assert_eq!(offset(cx), -max, "clamped at the end");
        cx.simulate_keystrokes("home");
        assert_eq!(offset(cx), 0.);
        cx.simulate_keystrokes("up");
        assert_eq!(offset(cx), 0., "clamped at the top");

        // A block editor keeps its keys: Space types a space, the view stays.
        rendered_mode(&smep, cx);
        activate_block(&smep, 0..11, cx);
        let block = active_block(&smep, cx);
        cx.simulate_keystrokes("space end");
        cx.run_until_parked();
        assert_eq!(value(&block, cx), "Paragraph 1 ");
        assert_eq!(offset(cx), 0.);
    }

    #[gpui_kit::test]
    fn right_click_on_the_rendered_view_opens_the_theme_menu(cx: &mut TestAppContext) {
        let document = Document {
            path: None,
            text: "# T\n\npara".into(),
            format: PreviewFormat::Markdown,
            origin: None,
        };
        // Reading, as smep opens: the one place a right-click reaches a theme.
        let (smep, cx) = open_reading(cx, document, Settings::default());
        draw(cx);
        assert_eq!(
            cx.read(|cx| smep.read(cx).preview_theme()),
            PreviewTheme::System
        );

        mouse_down(cx, MouseButton::Right, 300., 300.);
        assert!(
            menu_open(&smep, cx),
            "the theme menu opens over the document"
        );
        draw(cx);
        // As on the split preview: the first `down` is System, the second Paper.
        cx.simulate_keystrokes("down down enter");
        cx.run_until_parked();
        assert_eq!(
            cx.read(|cx| smep.read(cx).preview_theme()),
            PreviewTheme::Paper
        );
        assert!(!menu_open(&smep, cx));

        // Over an open block the right-click is the block editor's own.
        rendered_mode(&smep, cx);
        activate_block(&smep, 5..9, cx);
        let block = active_block(&smep, cx);
        draw(cx);
        let bounds = cx.read(|cx| block.read(cx).input_bounds());
        mouse_down(
            cx,
            MouseButton::Right,
            f32::from(bounds.left()) + 4.,
            f32::from(bounds.top()) + 4.,
        );
        assert!(!menu_open(&smep, cx), "no theme menu over the block");
    }

    fn rendered_mode(smep: &Entity<Smep>, cx: &mut VisualTestContext) {
        cx.update(|window, cx| {
            smep.update(cx, |this, cx| {
                this.set_view_mode(ViewMode::Rendered, window, cx)
            })
        });
        draw(cx);
    }

    fn activate_block(
        smep: &Entity<Smep>,
        range: std::ops::Range<usize>,
        cx: &mut VisualTestContext,
    ) {
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        cx.update(|window, cx| {
            rendered.update(cx, |rendered, cx| rendered.activate(range, window, cx))
        });
        draw(cx);
    }

    fn active_block(smep: &Entity<Smep>, cx: &VisualTestContext) -> Entity<TextareaState> {
        cx.read(|cx| smep.read(cx).rendered.read(cx).active_editor())
            .expect("a block is being edited")
    }

    #[gpui_kit::test]
    fn editing_a_block_in_the_rendered_view_writes_through(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title\n\npara\n\n- x");
        let document = editor(&smep, cx);
        rendered_mode(&smep, cx);

        activate_block(&smep, 9..13, cx);
        let block = active_block(&smep, cx);
        assert_eq!(value(&block, cx), "para");
        assert_eq!(
            cx.read(|cx| block.read(cx).cursor()),
            4,
            "cursor at the block's end"
        );

        type_text(&block, "para two", cx);
        assert_eq!(value(&document, cx), "# Title\n\npara two\n\n- x");
        assert!(dirty(&smep, cx));

        // Grow the block into two paragraphs; the document follows exactly.
        type_text(&block, "para two\n\nthree", cx);
        assert_eq!(value(&document, cx), "# Title\n\npara two\n\nthree\n\n- x");

        // Moving to another block keeps everything and edits that one.
        activate_block(&smep, 0..7, cx);
        let block = active_block(&smep, cx);
        assert_eq!(value(&block, cx), "# Title");
        type_text(&block, "# Big Title", cx);
        assert_eq!(
            value(&document, cx),
            "# Big Title\n\npara two\n\nthree\n\n- x"
        );
    }

    #[gpui_kit::test]
    fn a_new_block_at_the_end_gets_its_blank_line(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title");
        let document = editor(&smep, cx);
        rendered_mode(&smep, cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());

        cx.update(|window, cx| {
            rendered.update(cx, |rendered, cx| rendered.activate_at_end(window, cx))
        });
        draw(cx);
        let block = active_block(&smep, cx);
        type_text(&block, "new", cx);
        assert_eq!(value(&document, cx), "# Title\n\nnew");
        type_text(&block, "new text", cx);
        assert_eq!(
            value(&document, cx),
            "# Title\n\nnew text",
            "the gap is added once"
        );

        // CRLF documents get a CRLF gap.
        let (smep, cx) = open(cx, "a\r\nb");
        let document = cx.read(|cx| smep.read(cx).editor.clone());
        rendered_mode(&smep, cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        cx.update(|window, cx| {
            rendered.update(cx, |rendered, cx| rendered.activate_at_end(window, cx))
        });
        draw(cx);
        let block = active_block(&smep, cx);
        type_text(&block, "c", cx);
        assert_eq!(value(&document, cx), "a\r\nb\r\n\r\nc");
    }

    #[gpui_kit::test]
    fn a_slash_in_a_block_opens_the_menu_and_inserts_there(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title");
        let document = editor(&smep, cx);
        rendered_mode(&smep, cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        cx.update(|window, cx| {
            rendered.update(cx, |rendered, cx| rendered.activate_at_end(window, cx))
        });
        draw(cx);

        cx.simulate_input("/");
        assert!(menu_open(&smep, cx), "the slash in a block opens the menu");
        draw(cx);
        cx.simulate_keystrokes("down down enter");
        cx.run_until_parked();

        let block = active_block(&smep, cx);
        assert_eq!(value(&block, cx), "## ");
        assert_eq!(value(&document, cx), "# Title\n\n## ");
        assert!(!menu_open(&smep, cx));
    }

    #[gpui_kit::test]
    fn saving_from_a_block_editor_writes_the_whole_document(cx: &mut TestAppContext) {
        let dir = TempDir::new("block-save");
        let path = dir.path("blocks.md");
        std::fs::write(&path, "# Title\n\npara\n").unwrap();
        let (smep, cx) = open_document(cx, Document::read(path.clone()).unwrap());
        rendered_mode(&smep, cx);

        // Activating a block focuses its editor; the shortcut must still
        // reach the root from there.
        activate_block(&smep, 9..13, cx);
        let block = active_block(&smep, cx);
        assert!(cx.update(|window, cx| block.focus_handle(cx).is_focused(window)));
        type_text(&block, "para (edited)", cx);
        assert!(dirty(&smep, cx));

        cx.simulate_keystrokes(&primary("s"));
        cx.run_until_parked();

        assert!(!dirty(&smep, cx));
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "# Title\n\npara (edited)\n"
        );
    }

    #[gpui_kit::test]
    fn a_click_below_the_blocks_starts_a_focused_block_at_the_end(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title");
        rendered_mode(&smep, cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());

        // Well under the one heading, inside the view.
        mouse_down(cx, MouseButton::Left, 300., 500.);
        draw(cx);

        let block = active_block(&smep, cx);
        assert!(
            cx.update(|window, cx| block.focus_handle(cx).is_focused(window)),
            "the new block keeps focus after the view's own click handling"
        );
        assert!(!cx.update(|window, cx| rendered.read(cx).focus_handle().is_focused(window)));
        type_text(&block, "tail", cx);
        assert_eq!(value(&editor(&smep, cx), cx), "# Title\n\ntail");
    }

    #[gpui_kit::test]
    async fn importing_a_file_makes_a_new_unsaved_markdown_document(cx: &mut TestAppContext) {
        let dir = TempDir::new("import");
        let source = dir.path("notes.txt");
        std::fs::write(&source, "plain notes\r\n\r\n\r\nmore\r\n").unwrap();
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);

        cx.update(|window, cx| {
            smep.update(cx, |this, cx| this.load_path(source.clone(), window, cx))
        });
        cx.run_until_parked();

        assert_eq!(value(&editor, cx), "plain notes\n\nmore\n");
        assert!(dirty(&smep, cx), "converted text is not on disk yet");
        assert_eq!(cx.read(|cx| smep.read(cx).path.clone()), None);
        assert_eq!(
            cx.read(|cx| Smep::title_for(smep.read(cx).named_path().as_deref(), true)),
            "● notes.md — smep"
        );

        // Save As suggests notes.md next to the original; saving there
        // makes it the document's own path.
        let saved = cx.update(|window, cx| smep.update(cx, |this, cx| this.save_task(window, cx)));
        let target = dir.path("notes.md");
        cx.simulate_new_path_selection({
            let target = target.clone();
            let expected_dir = dir.0.clone();
            move |directory| {
                assert_eq!(
                    directory, expected_dir,
                    "the dialog opens next to the original"
                );
                Some(target)
            }
        });
        assert!(saved.await);
        assert_eq!(
            std::fs::read_to_string(&target).unwrap(),
            "plain notes\n\nmore\n"
        );
        assert!(!dirty(&smep, cx));
        assert_eq!(cx.read(|cx| smep.read(cx).path.clone()), Some(target));
    }

    #[gpui_kit::test]
    fn a_dropped_file_opens_after_the_unsaved_changes_prompt(cx: &mut TestAppContext) {
        use gpui_kit::{ExternalPaths, FileDropEvent};

        let dir = TempDir::new("drop");
        let dropped = dir.path("dropped.md");
        std::fs::write(&dropped, "# Dropped").unwrap();
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);
        type_text(&editor, "unsaved", cx);
        draw(cx);

        let position = point(px(300.), px(300.));
        let paths = ExternalPaths([dropped.clone()].into_iter().collect());
        cx.simulate_event(FileDropEvent::Entered { position, paths });
        cx.simulate_event(FileDropEvent::Submit { position });
        cx.run_until_parked();

        assert!(cx.has_pending_prompt(), "the unsaved edit is asked about");
        cx.simulate_prompt_answer("Don't Save");
        cx.run_until_parked();
        assert_eq!(value(&editor, cx), "# Dropped");
        assert_eq!(cx.read(|cx| smep.read(cx).path.clone()), Some(dropped));
    }

    #[gpui_kit::test]
    fn importing_something_unreadable_reports_instead_of_loading(cx: &mut TestAppContext) {
        let dir = TempDir::new("import-bad");
        let bad = dir.path("scan.pdf");
        std::fs::write(&bad, b"not a pdf").unwrap();
        let (smep, cx) = open(cx, "kept");
        let editor = editor(&smep, cx);

        cx.update(|window, cx| smep.update(cx, |this, cx| this.load_path(bad, window, cx)));
        cx.run_until_parked();

        assert!(cx.has_pending_prompt(), "an error dialog is shown");
        cx.simulate_prompt_answer("OK");
        assert_eq!(value(&editor, cx), "kept");
        assert!(!dirty(&smep, cx));
    }

    #[cfg(all(feature = "pdf-export", feature = "pdf-import"))]
    #[gpui_kit::test]
    fn exporting_writes_a_pdf_and_an_html_page_next_to_the_document(cx: &mut TestAppContext) {
        use crate::keymap::ExportHtml;

        let dir = TempDir::new("export");
        let path = dir.path("report.md");
        std::fs::write(&path, "# Report\n\nBody *text*.\n").unwrap();
        let (smep, cx) = open_document(cx, Document::read(path.clone()).unwrap());
        let editor = editor(&smep, cx);
        cx.update(|window, cx| editor.update(cx, |state, cx| state.focus(window, cx)));
        draw(cx);

        // The dialog opens next to the document, suggesting report.pdf.
        cx.simulate_keystrokes(&primary("shift-e"));
        let pdf_path = dir.path("out.pdf");
        cx.simulate_new_path_selection({
            let pdf_path = pdf_path.clone();
            let expected_dir = dir.0.clone();
            move |directory| {
                assert_eq!(directory, expected_dir);
                Some(pdf_path)
            }
        });
        cx.run_until_parked();
        let pdf = std::fs::read(&pdf_path).expect("the PDF was written");
        assert!(pdf.starts_with(b"%PDF-"));
        let text = crate::convert::from_bytes(&pdf, crate::convert::Format::Pdf).unwrap();
        assert!(text.contains("Report") && text.contains("Body"), "{text:?}");

        cx.update(|window, cx| {
            smep.update(cx, |this, cx| this.export_html(&ExportHtml, window, cx))
        });
        let html_path = dir.path("out.html");
        cx.simulate_new_path_selection({
            let html_path = html_path.clone();
            move |_| Some(html_path)
        });
        cx.run_until_parked();
        let html = std::fs::read_to_string(&html_path).expect("the HTML was written");
        assert!(html.contains("<title>Report</title>"));
        assert!(html.contains("<em>text</em>"));
        assert!(!dirty(&smep, cx), "exporting is not saving");
    }

    #[gpui_kit::test]
    fn menus_dispatch_from_whatever_is_on_screen(cx: &mut TestAppContext) {
        let dir = TempDir::new("menu-focus");
        let path = dir.path("menu.md");
        std::fs::write(&path, "# T\n\npara").unwrap();
        let (smep, cx) = open_document(cx, Document::read(path.clone()).unwrap());
        let editor = editor(&smep, cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        let focus = |cx: &VisualTestContext| cx.read(|cx| smep.read(cx).menu_focus(cx));

        assert_eq!(
            focus(cx),
            cx.read(|cx| editor.focus_handle(cx)),
            "split: the editor"
        );
        rendered_mode(&smep, cx);
        assert_eq!(
            focus(cx),
            cx.read(|cx| rendered.read(cx).focus_handle().clone()),
            "rendered, no block: the view itself"
        );
        activate_block(&smep, 5..9, cx);
        let block = active_block(&smep, cx);
        assert_eq!(focus(cx), cx.read(|cx| block.focus_handle(cx)), "the block");

        // What a menu does: focus its context, dispatch. With no block on
        // screen the action must still arrive (here: at the root's Save).
        type_text(&block, "para!", cx);
        cx.simulate_keystrokes("escape");
        cx.run_until_parked();
        assert!(dirty(&smep, cx));
        cx.update(|window, cx| {
            let handle = smep.read(cx).menu_focus(cx);
            handle.focus(window, cx);
            window.dispatch_action(Box::new(Save), cx);
        });
        cx.run_until_parked();
        assert!(!dirty(&smep, cx));
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "# T\n\npara!");
    }

    #[gpui_kit::test]
    fn a_large_document_is_highlighted_after_the_pause_not_on_the_keystroke(
        cx: &mut TestAppContext,
    ) {
        use crate::highlight::{self, MarkdownHighlighter};
        use gpui_kit::HighlightStyle;
        use gpui_kit::component::input::{HighlightStyleResolver, InputHighlighter};

        struct Faded;
        impl HighlightStyleResolver for Faded {
            fn style(&self, _: &str) -> Option<HighlightStyle> {
                Some(HighlightStyle {
                    fade_out: Some(0.5),
                    ..Default::default()
                })
            }
        }
        let styled = |highlighter: &MarkdownHighlighter| {
            highlighter
                .styles(&(0..9), &Faded)
                .iter()
                .any(|(_, style)| style.fade_out.is_some())
        };
        let update = |highlighter: &mut MarkdownHighlighter,
                      editor: &Entity<EditorState>,
                      cx: &mut VisualTestContext| {
            cx.update(|window, cx| {
                editor.update(cx, |state, cx| {
                    highlighter.update(None, state.text(), false, window, cx)
                })
            });
        };

        let big = "# Heading\n\ntext\n\n".repeat(highlight::SYNC_LIMIT / 16 + 1);
        assert!(big.len() > highlight::SYNC_LIMIT);
        let (smep, cx) = open(cx, &big);
        let source = editor(&smep, cx);
        let mut highlighter = MarkdownHighlighter::default();
        update(&mut highlighter, &source, cx);
        assert!(!styled(&highlighter), "nothing is parsed on the keystroke");
        cx.executor().advance_clock(highlight::DEBOUNCE);
        cx.run_until_parked();
        assert!(styled(&highlighter), "parsed once typing paused");

        // A small document is parsed on the spot.
        let (smep, cx) = open(cx, "# Heading");
        let source = editor(&smep, cx);
        let mut highlighter = MarkdownHighlighter::default();
        update(&mut highlighter, &source, cx);
        assert!(styled(&highlighter));
    }

    #[gpui_kit::test]
    fn block_edits_keep_the_block_list_equal_to_a_fresh_parse(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title\n\npara\n\n- x\n- y\n\n> quote");
        let document = editor(&smep, cx);
        rendered_mode(&smep, cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        let check = |cx: &mut VisualTestContext, when: &str| {
            draw(cx);
            let text = value(&document, cx);
            assert_eq!(
                cx.read(|cx| rendered.read(cx).block_ranges()),
                crate::highlight::block_ranges(&text),
                "{when}: {text:?}"
            );
        };

        // A middle block: grown, split in two, emptied, refilled.
        activate_block(&smep, 9..13, cx);
        let block = active_block(&smep, cx);
        for typed in ["para longer", "para\n\nsecond", "", "back"] {
            type_text(&block, typed, cx);
            check(cx, typed);
        }

        // The first block, then a new one at the end (with its gap).
        activate_block(&smep, 0..7, cx);
        type_text(&active_block(&smep, cx), "## Small", cx);
        check(cx, "first block");
        cx.update(|window, cx| {
            rendered.update(cx, |rendered, cx| rendered.activate_at_end(window, cx))
        });
        type_text(&active_block(&smep, cx), "tail", cx);
        check(cx, "new block at the end");

        // A change made elsewhere ends the edit and is parsed afresh.
        type_text(&document, "# Other\n\nthing", cx);
        check(cx, "source edit");

        // From nothing, and with CRLF line endings.
        for start in ["", "a\r\n\r\nb\r\n"] {
            let (smep, cx) = open(cx, start);
            let document = editor(&smep, cx);
            rendered_mode(&smep, cx);
            let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
            cx.update(|window, cx| {
                rendered.update(cx, |rendered, cx| rendered.activate_at_end(window, cx))
            });
            for typed in ["x", "x\r\n\r\ny", ""] {
                type_text(&active_block(&smep, cx), typed, cx);
                draw(cx);
                let text = value(&document, cx);
                assert_eq!(
                    cx.read(|cx| rendered.read(cx).block_ranges()),
                    crate::highlight::block_ranges(&text),
                    "{start:?} then {typed:?}: {text:?}"
                );
            }
        }
    }

    #[gpui_kit::test]
    fn an_emptied_block_stays_on_screen_and_takes_typing(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title\n\npara\n\n- x");
        let document = editor(&smep, cx);
        rendered_mode(&smep, cx);
        activate_block(&smep, 9..13, cx);
        let block = active_block(&smep, cx);

        type_text(&block, "", cx);
        assert_eq!(value(&document, cx), "# Title\n\n\n\n- x");
        draw(cx);

        // Keys reach the editor only while it is painted.
        cx.simulate_input("n");
        cx.run_until_parked();
        assert_eq!(value(&block, cx), "n");
        assert_eq!(value(&document, cx), "# Title\n\nn\n\n- x");
    }

    #[gpui_kit::test]
    fn a_change_from_elsewhere_ends_the_block_edit(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title\n\npara");
        let document = editor(&smep, cx);
        rendered_mode(&smep, cx);
        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        let active = |cx: &VisualTestContext| cx.read(|cx| rendered.read(cx).active_editor());

        // Typing in the source view moves the block.
        activate_block(&smep, 9..13, cx);
        type_text(&document, "# Longer Title\n\npara", cx);
        assert!(active(cx).is_none(), "the block's offsets went stale");

        // Opening another document.
        activate_block(&smep, 9..13, cx);
        assert!(active(cx).is_some());
        cx.update(|window, cx| {
            smep.update(cx, |this, cx| {
                this.load(
                    Document {
                        path: None,
                        text: "new".into(),
                        format: PreviewFormat::Markdown,
                        origin: None,
                    },
                    window,
                    cx,
                )
            })
        });
        assert!(active(cx).is_none());

        // The block's own commits do not end the edit.
        activate_block(&smep, 0..3, cx);
        let block = active_block(&smep, cx);
        type_text(&block, "newer", cx);
        type_text(&block, "newest", cx);
        assert!(active(cx).is_some());
        assert_eq!(value(&document, cx), "newest");
    }

    #[gpui_kit::test]
    fn escape_ends_the_block_edit_and_keeps_the_text(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title\n\npara");
        let document = editor(&smep, cx);
        rendered_mode(&smep, cx);
        activate_block(&smep, 9..13, cx);
        let block = active_block(&smep, cx);
        type_text(&block, "para!", cx);

        cx.simulate_keystrokes("escape");
        cx.run_until_parked();

        let rendered = cx.read(|cx| smep.read(cx).rendered.clone());
        assert!(cx.read(|cx| rendered.read(cx).active_editor().is_none()));
        assert_eq!(value(&document, cx), "# Title\n\npara!");
        assert!(
            cx.update(|window, cx| rendered.read(cx).focus_handle().is_focused(window)),
            "focus returns to the view so shortcuts keep working"
        );
    }

    #[gpui_kit::test]
    fn a_block_editor_grows_with_its_text(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "# Title\n\n- a\n- b\n- c\n- d");
        rendered_mode(&smep, cx);
        activate_block(&smep, 9..24, cx);
        let block = active_block(&smep, cx);
        draw(cx);

        let line_height = cx
            .read(|cx| block.read(cx).line_height())
            .expect("laid out");
        let height = cx.read(|cx| block.read(cx).input_bounds().size.height);
        assert!(
            height >= line_height * 4.,
            "four lines need four rows: {height:?} < 4 × {line_height:?}"
        );
    }

    #[gpui_kit::test]
    fn the_menu_bar_and_fullscreen_toggle_by_keyboard(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| editor.update(cx, |state, cx| state.focus(window, cx)));
        draw(cx);
        assert!(cx.read(|cx| smep.read(cx).menu_bar_shown()));

        cx.simulate_keystrokes(&primary("shift-m"));
        cx.run_until_parked();
        assert!(!cx.read(|cx| smep.read(cx).menu_bar_shown()));
        cx.simulate_keystrokes(&primary("shift-m"));
        cx.run_until_parked();
        assert!(cx.read(|cx| smep.read(cx).menu_bar_shown()));

        let fullscreen = if cfg!(target_os = "macos") {
            "ctrl-cmd-f"
        } else {
            "f11"
        };
        assert!(!cx.update(|window, _| window.is_fullscreen()));
        cx.simulate_keystrokes(fullscreen);
        cx.run_until_parked();
        assert!(cx.update(|window, _| window.is_fullscreen()));
        cx.simulate_keystrokes(fullscreen);
        cx.run_until_parked();
        assert!(!cx.update(|window, _| window.is_fullscreen()));
    }

    #[gpui_kit::test]
    fn opening_a_path_from_the_os_asks_about_unsaved_changes_first(cx: &mut TestAppContext) {
        let dir = TempDir::new("os-open");
        let path = dir.path("incoming.md");
        std::fs::write(&path, "# From Finder").unwrap();
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);

        // Clean buffer: opens right away.
        cx.update(|window, cx| {
            smep.update(cx, |this, cx| {
                this.open_document_at(path.clone(), window, cx)
            })
        });
        cx.run_until_parked();
        assert_eq!(value(&editor, cx), "# From Finder");
        assert_eq!(cx.read(|cx| smep.read(cx).path.clone()), Some(path.clone()));

        // Dirty buffer: the prompt comes first; "Cancel" keeps the edits.
        type_text(&editor, "edited", cx);
        let other = dir.path("other.md");
        std::fs::write(&other, "other").unwrap();
        cx.update(|window, cx| {
            smep.update(cx, |this, cx| {
                this.open_document_at(other.clone(), window, cx)
            })
        });
        assert!(cx.has_pending_prompt());
        cx.simulate_prompt_answer("Cancel");
        cx.run_until_parked();
        assert_eq!(value(&editor, cx), "edited");

        // "Don't Save" lets the new file in.
        cx.update(|window, cx| {
            smep.update(cx, |this, cx| {
                this.open_document_at(other.clone(), window, cx)
            })
        });
        cx.simulate_prompt_answer("Don't Save");
        cx.run_until_parked();
        assert_eq!(value(&editor, cx), "other");
        assert!(!dirty(&smep, cx));

        // A missing file reports instead of failing silently.
        cx.update(|window, cx| {
            smep.update(cx, |this, cx| {
                this.open_document_at(dir.path("missing.md"), window, cx)
            })
        });
        cx.run_until_parked();
        assert!(cx.has_pending_prompt(), "an error dialog is shown");
        cx.simulate_prompt_answer("OK");
        assert_eq!(value(&editor, cx), "other");
    }

    #[gpui_kit::test]
    fn ctrl_s_reaches_the_save_action(cx: &mut TestAppContext) {
        let dir = TempDir::new("keys");
        let path = dir.path("keys.md");
        std::fs::write(&path, "").unwrap();
        let (smep, cx) = open_document(cx, Document::read(path.clone()).unwrap());
        let editor = editor(&smep, cx);
        cx.update(|window, cx| editor.update(cx, |state, cx| state.focus(window, cx)));
        draw(cx);
        type_text(&editor, "typed", cx);
        assert!(dirty(&smep, cx));

        let save = if cfg!(target_os = "macos") {
            "cmd-s"
        } else {
            "ctrl-s"
        };
        cx.simulate_keystrokes(save);
        cx.run_until_parked();

        assert!(!dirty(&smep, cx));
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "typed");
    }

    #[cfg(not(target_os = "macos"))]
    #[gpui_kit::test]
    fn ctrl_end_and_ctrl_home_jump_across_the_document(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "first\nsecond\nthird");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| editor.update(cx, |state, cx| state.focus(window, cx)));
        draw(cx);

        cx.simulate_keystrokes("ctrl-end");
        cx.run_until_parked();
        assert_eq!(
            cx.read(|cx| editor.read(cx).cursor()),
            "first\nsecond\nthird".len()
        );

        cx.simulate_keystrokes("ctrl-home");
        cx.run_until_parked();
        assert_eq!(cx.read(|cx| editor.read(cx).cursor()), 0);

        cx.simulate_keystrokes("ctrl-shift-end");
        cx.run_until_parked();
        assert_eq!(
            cx.read(|cx| editor.read(cx).selected_range()),
            0.."first\nsecond\nthird".len()
        );
    }

    #[gpui_kit::test]
    fn a_slash_on_an_empty_line_opens_the_menu_and_escape_closes_it(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| editor.update(cx, |state, cx| state.focus(window, cx)));
        draw(cx);

        cx.simulate_input("/");
        assert!(
            menu_open(&smep, cx),
            "typing / on an empty line opens the menu"
        );

        draw(cx);
        cx.simulate_keystrokes("escape");
        cx.run_until_parked();
        assert!(!menu_open(&smep, cx), "escape closes the menu");
        assert_eq!(value(&editor, cx), "/", "escape keeps what was typed");
    }

    #[gpui_kit::test]
    fn a_slash_inside_text_does_not_open_the_menu(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "a");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| {
            editor.update(cx, |state, cx| {
                state.focus(window, cx);
                state.set_cursor_position(Position::new(0, 1), window, cx);
            });
        });
        draw(cx);

        cx.simulate_input("/");
        assert_eq!(value(&editor, cx), "a/");
        assert!(!menu_open(&smep, cx));
    }

    #[gpui_kit::test]
    fn choosing_the_first_entry_replaces_the_line(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "intro\n\nend");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| {
            editor.update(cx, |state, cx| {
                state.focus(window, cx);
                state.set_cursor_position(Position::new(1, 0), window, cx);
            });
        });
        draw(cx);

        cx.update(|window, cx| smep.update(cx, |this, cx| this.open_insert_menu(window, cx)));
        assert!(menu_open(&smep, cx));
        draw(cx);

        cx.simulate_keystrokes("down enter");
        cx.run_until_parked();

        assert_eq!(value(&editor, cx), "intro\n# \nend");
        assert_eq!(cx.read(|cx| editor.read(cx).cursor()), "intro\n# ".len());
        assert!(!menu_open(&smep, cx), "the menu closes after a choice");
        assert_eq!(
            cx.read(|cx| smep.read(cx).source.to_string()),
            "intro\n# \nend",
            "the preview sees the inserted block"
        );
    }

    #[gpui_kit::test]
    fn a_click_below_the_text_opens_the_menu_at_the_end(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "one\ntwo");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| {
            editor.update(cx, |state, cx| {
                state.focus(window, cx);
                state.set_cursor_position(Position::new(0, 0), window, cx);
            });
        });
        draw(cx);
        let (input, last) = cx.read(|cx| {
            let state = editor.read(cx);
            let len = state.text().len();
            (
                state.input_bounds(),
                state
                    .range_to_bounds(&(len..len))
                    .expect("the last line is on screen"),
            )
        });
        assert!(
            input.bottom() > last.bottom() + px(40.),
            "room below the text"
        );

        // On the text: the editor's own click, no menu.
        mouse_down(
            cx,
            MouseButton::Left,
            f32::from(last.left()) + 4.,
            f32::from(last.top()) + 4.,
        );
        assert!(!menu_open(&smep, cx));

        // Well below it: cursor to the end, menu open.
        mouse_down(
            cx,
            MouseButton::Left,
            f32::from(last.left()) + 4.,
            f32::from(input.bottom()) - 10.,
        );
        assert!(
            menu_open(&smep, cx),
            "a click below the text opens the menu"
        );
        assert_eq!(cx.read(|cx| editor.read(cx).cursor()), "one\ntwo".len());
    }

    #[gpui_kit::test]
    fn right_click_in_the_editor_opens_the_context_menu(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "one\ntwo");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| editor.update(cx, |state, cx| state.focus(window, cx)));
        draw(cx);
        let first = cx.read(|cx| editor.read(cx).range_to_bounds(&(0..0)).unwrap());

        // Down then up: the editor opens its context menu on release.
        let (x, y) = (f32::from(first.left()) + 4., f32::from(first.top()) + 4.);
        mouse_down(cx, MouseButton::Right, x, y);
        cx.simulate_event(gpui_kit::MouseUpEvent {
            button: MouseButton::Right,
            position: point(px(x), px(y)),
            modifiers: Default::default(),
            click_count: 1,
        });
        cx.run_until_parked();
        draw(cx);
        cx.run_until_parked();

        assert!(menu_open(&smep, cx), "right-click opens smep's menu");
        assert!(!cx.read(|cx| {
            smep.read(cx)
                .insert_menu
                .as_ref()
                .unwrap()
                .menu
                .read(cx)
                .is_empty()
        }));
    }

    #[gpui_kit::test]
    fn right_click_on_the_preview_picks_a_theme_and_saves_it(cx: &mut TestAppContext) {
        let dir = TempDir::new("theme");
        let settings = Settings {
            preview_theme: PreviewTheme::System,
            path: Some(dir.path("settings.toml")),
            ..Settings::default()
        };
        let document = Document {
            path: None,
            text: "# T".into(),
            format: PreviewFormat::Markdown,
            origin: None,
        };
        let (smep, cx) = open_with(cx, document, settings);
        draw(cx);
        let editor = editor(&smep, cx);
        let preview_x = f32::from(cx.read(|cx| editor.read(cx).input_bounds().right())) + 60.;

        mouse_down(cx, MouseButton::Right, preview_x, 200.);
        assert!(
            menu_open(&smep, cx),
            "right-click on the preview opens the theme menu"
        );
        draw(cx);

        // First `down` selects System (the current one), the second Paper.
        cx.simulate_keystrokes("down down enter");
        cx.run_until_parked();

        assert_eq!(
            cx.read(|cx| smep.read(cx).preview_theme()),
            PreviewTheme::Paper
        );
        assert!(!menu_open(&smep, cx));
        assert!(
            std::fs::read_to_string(dir.path("settings.toml"))
                .unwrap()
                .contains("preview_theme = \"paper\"")
        );
    }

    #[gpui_kit::test]
    fn inserting_on_a_line_with_text_adds_a_line_below(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "text\nnext");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| {
            editor.update(cx, |state, cx| {
                state.set_cursor_position(Position::new(0, 2), window, cx);
                insert::insert_block(state, BlockKind::Heading1, window, cx);
            });
        });
        assert_eq!(value(&editor, cx), "text\n# \nnext");
        assert_eq!(cx.read(|cx| editor.read(cx).cursor()), "text\n# ".len());

        let (smep, cx) = open(cx, "a\r\nb");
        let crlf_editor = cx.read(|cx| smep.read(cx).editor.clone());
        cx.update(|window, cx| {
            crlf_editor.update(cx, |state, cx| {
                state.set_cursor_position(Position::new(0, 1), window, cx);
                insert::insert_block(state, BlockKind::Quote, window, cx);
            });
        });
        assert_eq!(value(&crlf_editor, cx), "a\r\n> \r\nb");
        assert_eq!(cx.read(|cx| crlf_editor.read(cx).cursor()), "a\r\n> ".len());
    }

    #[gpui_kit::test]
    fn insert_block_keeps_crlf_line_endings(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "a\r\n\r\nb");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| {
            editor.update(cx, |state, cx| {
                state.set_cursor_position(Position::new(1, 0), window, cx);
                insert::insert_block(state, BlockKind::Heading2, window, cx);
            });
        });

        assert_eq!(value(&editor, cx), "a\r\n## \r\nb");
        assert_eq!(cx.read(|cx| editor.read(cx).cursor()), "a\r\n## ".len());
    }

    #[gpui_kit::test]
    fn multi_line_snippets_put_the_cursor_inside(cx: &mut TestAppContext) {
        let (smep, cx) = open(cx, "/");
        let editor = editor(&smep, cx);
        cx.update(|window, cx| {
            editor.update(cx, |state, cx| {
                state.set_cursor_position(Position::new(0, 1), window, cx);
                insert::insert_block(state, BlockKind::CodeBlock, window, cx);
            });
        });

        assert_eq!(value(&editor, cx), "```\n\n```");
        assert_eq!(cx.read(|cx| editor.read(cx).cursor()), "```\n".len());
    }

    #[test]
    fn html_files_get_the_html_preview() {
        assert_eq!(
            PreviewFormat::for_path(Path::new("a.html")),
            PreviewFormat::Html
        );
        assert_eq!(
            PreviewFormat::for_path(Path::new("a.HTM")),
            PreviewFormat::Html
        );
        assert_eq!(
            PreviewFormat::for_path(Path::new("a.md")),
            PreviewFormat::Markdown
        );
        assert_eq!(
            PreviewFormat::for_path(Path::new("README")),
            PreviewFormat::Markdown
        );
    }

    #[test]
    fn titles_show_the_name_and_a_dirty_marker() {
        assert_eq!(Smep::title_for(None, false), "Untitled — smep");
        assert_eq!(
            Smep::title_for(Some(Path::new("/x/a.md")), true),
            "● a.md — smep"
        );
    }
}