floem 0.2.0

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

// TODO: This file is getting long. Possibly it should be broken out into multiple files.
// Especially as it will only grow with more utility functions.

// TODO(minor): We use a lot of `impl TextLayoutProvider`.
// This has the desired benefit of inlining the functions, so that the compiler can optimize the
// logic better than a naive for-loop or whatnot.
// However it does have the issue that it overuses generics, and we sometimes end up instantiating
// multiple versions of the same function. `T: TextLayoutProvider`, `&T`...
// - It would be better to standardize on one way of doing that, probably `&impl TextLayoutProvider`

use std::{
    cell::{Cell, RefCell},
    cmp::Ordering,
    collections::HashMap,
    rc::Rc,
    sync::Arc,
};

use floem_editor_core::{
    buffer::rope_text::{RopeText, RopeTextVal},
    cursor::CursorAffinity,
    word::WordCursor,
};
use floem_reactive::Scope;
use floem_renderer::text::{HitPosition, LayoutGlyph, TextLayout};
use lapce_xi_rope::{Interval, Rope};
use peniko::kurbo::Point;

use super::{layout::TextLayoutLine, listener::Listener};

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ResolvedWrap {
    None,
    Column(usize),
    Width(f32),
}
impl ResolvedWrap {
    pub fn is_different_kind(self, other: ResolvedWrap) -> bool {
        !matches!(
            (self, other),
            (ResolvedWrap::None, ResolvedWrap::None)
                | (ResolvedWrap::Column(_), ResolvedWrap::Column(_))
                | (ResolvedWrap::Width(_), ResolvedWrap::Width(_))
        )
    }
}

/// A line within the editor view.
///
/// This gives the absolute position of the visual line.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VLine(pub usize);
impl VLine {
    pub fn get(&self) -> usize {
        self.0
    }
}

/// A visual line relative to some other line within the editor view.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RVLine {
    /// The buffer line this is for
    pub line: usize,
    /// The index of the actual visual line's layout
    pub line_index: usize,
}
impl RVLine {
    pub fn new(line: usize, line_index: usize) -> RVLine {
        RVLine { line, line_index }
    }

    /// Is this the first visual line for the buffer line?
    pub fn is_first(&self) -> bool {
        self.line_index == 0
    }
}

/// (Font Size -> (Buffer Line Number -> Text Layout))
pub type Layouts = HashMap<usize, HashMap<usize, Arc<TextLayoutLine>>>;

#[derive(Debug, Default, PartialEq, Clone, Copy)]
pub struct ConfigId {
    editor_style_id: u64,
    floem_style_id: u64,
}
impl ConfigId {
    pub fn new(editor_style_id: u64, floem_style_id: u64) -> Self {
        Self {
            editor_style_id,
            floem_style_id,
        }
    }
}

#[derive(Default)]
pub struct TextLayoutCache {
    /// The id of the last config so that we can clear when the config changes
    /// the first is the styling id and the second is an id for changes from Floem style
    config_id: ConfigId,
    /// The most recent cache revision of the document.
    cache_rev: u64,
    /// (Font Size -> (Buffer Line Number -> Text Layout))
    ///
    /// Different font-sizes are cached separately, which is useful for features like code lens
    /// where the font-size can rapidly change.
    ///
    /// It would also be useful for a prospective minimap feature.
    pub layouts: Layouts,
    /// The maximum width seen so far, used to determine if we need to show horizontal scrollbar
    pub max_width: f64,
}
impl TextLayoutCache {
    pub fn clear(&mut self, cache_rev: u64, config_id: Option<ConfigId>) {
        self.layouts.clear();
        if let Some(config_id) = config_id {
            self.config_id = config_id;
        }
        self.cache_rev = cache_rev;
        self.max_width = 0.0;
    }

    /// Clear the layouts without changing the document cache revision.
    ///
    /// Ex: Wrapping width changed, which does not change what the document holds.
    pub fn clear_unchanged(&mut self) {
        self.layouts.clear();
        self.max_width = 0.0;
    }

    pub fn get(&self, font_size: usize, line: usize) -> Option<&Arc<TextLayoutLine>> {
        self.layouts.get(&font_size).and_then(|c| c.get(&line))
    }

    pub fn get_mut(&mut self, font_size: usize, line: usize) -> Option<&mut Arc<TextLayoutLine>> {
        self.layouts
            .get_mut(&font_size)
            .and_then(|c| c.get_mut(&line))
    }

    /// Get the (start, end) columns of the (line, line_index)
    pub fn get_layout_col(
        &self,
        text_prov: &impl TextLayoutProvider,
        font_size: usize,
        line: usize,
        line_index: usize,
    ) -> Option<(usize, usize)> {
        self.get(font_size, line)
            .and_then(|l| l.layout_cols(text_prov, line).nth(line_index))
    }
}

// TODO(minor): Should we rename this? It does more than just providing the text layout. It provides the text, text layouts, phantom text, and whether it has multiline phantom text. It is more of an outside state.
/// The [`TextLayoutProvider`] serves two primary roles:
/// - Providing the [`Rope`] text of the underlying file
/// - Constructing the text layout for a given line
///
/// Note: `text` does not necessarily include every piece of text. The obvious example is phantom
/// text, which is not in the underlying buffer.
///
/// Using this trait rather than passing around something like [Document](super::text::Document) allows the backend to
/// be swapped out if needed. This would be useful if we ever wanted to reuse it across different
/// views that did not naturally fit into our 'document' model. As well as when we want to extract
/// the editor view code int a separate crate for Floem.
pub trait TextLayoutProvider {
    fn text(&self) -> Rope;

    /// Shorthand for getting a rope text version of `text`.
    ///
    /// This MUST hold the same rope that `text` would return.
    fn rope_text(&self) -> RopeTextVal {
        RopeTextVal::new(self.text())
    }

    // TODO(minor): Do we really need to pass font size to this? The outer-api is providing line
    // font size provider already, so it should be able to just use that.
    fn new_text_layout(
        &self,
        line: usize,
        font_size: usize,
        wrap: ResolvedWrap,
    ) -> Arc<TextLayoutLine>;

    /// Translate a column position into the position it would be before combining with the phantom
    /// text
    fn before_phantom_col(&self, line: usize, col: usize) -> usize;

    /// Whether the text has *any* multiline phantom text.
    ///
    /// This is used to determine whether we can use the fast route where the lines are linear,
    /// which also requires no wrapping.
    ///
    /// This should be a conservative estimate, so if you aren't bothering to check all of your
    /// phantom text then just return true.
    fn has_multiline_phantom(&self) -> bool;
}
impl<T: TextLayoutProvider> TextLayoutProvider for &T {
    fn text(&self) -> Rope {
        (**self).text()
    }

    fn new_text_layout(
        &self,
        line: usize,
        font_size: usize,
        wrap: ResolvedWrap,
    ) -> Arc<TextLayoutLine> {
        (**self).new_text_layout(line, font_size, wrap)
    }

    fn before_phantom_col(&self, line: usize, col: usize) -> usize {
        (**self).before_phantom_col(line, col)
    }

    fn has_multiline_phantom(&self) -> bool {
        (**self).has_multiline_phantom()
    }
}

pub type FontSizeCacheId = u64;
pub trait LineFontSizeProvider {
    /// Get the 'general' font size for a specific buffer line.
    ///
    /// This is typically the editor font size.
    ///
    /// There might be alternate font-sizes within the line, like for phantom text, but those are
    /// not considered here.
    fn font_size(&self, line: usize) -> usize;

    /// An identifier used to mark when the font size info has changed.
    ///
    /// This lets us update information.
    fn cache_id(&self) -> FontSizeCacheId;
}

/// Layout events
///
/// This is primarily needed for logic which tracks visual lines intelligently, like
/// `ScreenLines` in Lapce.
///
/// This is currently limited to only a `CreatedLayout` event, as changed to the cache rev would
/// capture the idea of all the layouts being cleared. In the future it could be expanded to more
/// events, especially if cache rev gets more specific than clearing everything.
#[derive(Debug, Clone, PartialEq)]
pub enum LayoutEvent {
    CreatedLayout { font_size: usize, line: usize },
}

/// The main structure for tracking visual line information.
pub struct Lines {
    /// This is inside out from the usual way of writing Arc-RefCells due to sometimes wanting to
    /// swap out font sizes, while also grabbing an `Arc` to hold.
    ///
    /// An `Arc<RefCell<_>>` has the issue that with a `dyn` it can't know they're the same size
    /// if you were to assign. So this allows us to swap out the `Arc`, though it does mean that
    /// the other holders of the `Arc` don't get the new version. That is fine currently.
    pub font_sizes: RefCell<Rc<dyn LineFontSizeProvider>>,
    text_layouts: Rc<RefCell<TextLayoutCache>>,
    wrap: Cell<ResolvedWrap>,
    font_size_cache_id: Cell<FontSizeCacheId>,
    last_vline: Rc<Cell<Option<VLine>>>,
    pub layout_event: Listener<LayoutEvent>,
}
impl Lines {
    pub fn new(cx: Scope, font_sizes: RefCell<Rc<dyn LineFontSizeProvider>>) -> Lines {
        let id = font_sizes.borrow().cache_id();
        Lines {
            font_sizes,
            text_layouts: Rc::new(RefCell::new(TextLayoutCache::default())),
            wrap: Cell::new(ResolvedWrap::None),
            font_size_cache_id: Cell::new(id),
            last_vline: Rc::new(Cell::new(None)),
            layout_event: Listener::new_empty(cx),
        }
    }

    /// The current wrapping style
    pub fn wrap(&self) -> ResolvedWrap {
        self.wrap.get()
    }

    /// Set the wrapping style
    ///
    /// Does nothing if the wrapping style is the same as the current one.
    /// Will trigger a clear of the text layouts if the wrapping style is different.
    pub fn set_wrap(&self, wrap: ResolvedWrap) {
        if wrap == self.wrap.get() {
            return;
        }

        // TODO(perf): We could improve this by only clearing the lines that would actually change
        // Ex: Single vline lines don't need to be cleared if the wrapping changes from
        // some width to None, or from some width to some larger width.
        self.clear_unchanged();

        self.wrap.set(wrap);
    }

    /// The max width of the text layouts displayed
    pub fn max_width(&self) -> f64 {
        self.text_layouts.borrow().max_width
    }

    /// Check if the lines can be modelled as a purely linear file.
    ///
    /// If `true` this makes various operations simpler because there is a one-to-one
    /// correspondence between visual lines and buffer lines.
    ///
    /// However, if there is wrapping or any multiline phantom text, then we can't rely on that.
    ///
    /// TODO:?
    /// We could be smarter about various pieces.
    ///
    /// - If there was no lines that exceeded the wrap width then we could do the fast path
    ///    - Would require tracking that but might not be too hard to do it whenever we create a
    ///      text layout
    /// - `is_linear` could be up to some line, which allows us to make at least the earliest parts
    ///    before any wrapping were faster. However, early lines are faster to calculate anyways.
    pub fn is_linear(&self, text_prov: impl TextLayoutProvider) -> bool {
        self.wrap.get() == ResolvedWrap::None && !text_prov.has_multiline_phantom()
    }

    /// Get the font size that [`Self::font_sizes`] provides
    pub fn font_size(&self, line: usize) -> usize {
        self.font_sizes.borrow().font_size(line)
    }

    /// Get the last visual line of the file.
    ///
    /// Cached.
    pub fn last_vline(&self, text_prov: impl TextLayoutProvider) -> VLine {
        let current_id = self.font_sizes.borrow().cache_id();
        if current_id != self.font_size_cache_id.get() {
            self.last_vline.set(None);
            self.font_size_cache_id.set(current_id);
        }

        if let Some(last_vline) = self.last_vline.get() {
            last_vline
        } else {
            // For most files this should easily be fast enough.
            // Though it could still be improved.
            let rope_text = text_prov.rope_text();
            let hard_line_count = rope_text.num_lines();

            let line_count = if self.is_linear(text_prov) {
                hard_line_count
            } else {
                let mut soft_line_count = 0;

                let layouts = self.text_layouts.borrow();
                for i in 0..hard_line_count {
                    let font_size = self.font_size(i);
                    if let Some(text_layout) = layouts.get(font_size, i) {
                        let line_count = text_layout.line_count();
                        soft_line_count += line_count;
                    } else {
                        soft_line_count += 1;
                    }
                }

                soft_line_count
            };

            let last_vline = line_count.saturating_sub(1);
            self.last_vline.set(Some(VLine(last_vline)));
            VLine(last_vline)
        }
    }

    /// Clear the cache for the last vline
    pub fn clear_last_vline(&self) {
        self.last_vline.set(None);
    }

    /// The last relative visual line.
    ///
    /// Cheap, so not cached
    pub fn last_rvline(&self, text_prov: impl TextLayoutProvider) -> RVLine {
        let rope_text = text_prov.rope_text();
        let last_line = rope_text.last_line();
        let layouts = self.text_layouts.borrow();
        let font_size = self.font_size(last_line);

        if let Some(layout) = layouts.get(font_size, last_line) {
            let line_count = layout.line_count();

            RVLine::new(last_line, line_count - 1)
        } else {
            RVLine::new(last_line, 0)
        }
    }

    /// 'len' version of [`Lines::last_vline`]
    ///
    /// Cached.
    pub fn num_vlines(&self, text_prov: impl TextLayoutProvider) -> usize {
        self.last_vline(text_prov).get() + 1
    }

    /// Get the text layout for the given buffer line number.
    /// This will create the text layout if it doesn't exist.
    ///
    /// `trigger` (default to true) decides whether the creation of the text layout should trigger
    /// the [`LayoutEvent::CreatedLayout`] event.
    ///
    /// This will check the `config_id`, which decides whether it should clear out the text layout
    /// cache.
    pub fn get_init_text_layout(
        &self,
        cache_rev: u64,
        config_id: ConfigId,
        text_prov: impl TextLayoutProvider,
        line: usize,
        trigger: bool,
    ) -> Arc<TextLayoutLine> {
        self.check_cache(cache_rev, config_id);

        let font_size = self.font_size(line);
        get_init_text_layout(
            &self.text_layouts,
            trigger.then_some(self.layout_event),
            text_prov,
            line,
            font_size,
            self.wrap.get(),
            &self.last_vline,
        )
    }

    /// Try to get the text layout for the given line number.
    ///
    /// This will check the `config_id`, which decides whether it should clear out the text layout
    /// cache.
    pub fn try_get_text_layout(
        &self,
        cache_rev: u64,
        config_id: ConfigId,
        line: usize,
    ) -> Option<Arc<TextLayoutLine>> {
        self.check_cache(cache_rev, config_id);

        let font_size = self.font_size(line);

        self.text_layouts
            .borrow()
            .layouts
            .get(&font_size)
            .and_then(|f| f.get(&line))
            .cloned()
    }

    /// Initialize the text layout of every line in the real line interval.
    ///
    /// `trigger` (default to true) decides whether the creation of the text layout should trigger
    /// the [`LayoutEvent::CreatedLayout`] event.
    pub fn init_line_interval(
        &self,
        cache_rev: u64,
        config_id: ConfigId,
        text_prov: &impl TextLayoutProvider,
        lines: impl Iterator<Item = usize>,
        trigger: bool,
    ) {
        for line in lines {
            self.get_init_text_layout(cache_rev, config_id, text_prov, line, trigger);
        }
    }

    /// Initialize the text layout of every line in the file.
    /// This should typically not be used.
    ///
    /// `trigger` (default to true) decides whether the creation of the text layout should trigger
    /// the [`LayoutEvent::CreatedLayout`] event.
    pub fn init_all(
        &self,
        cache_rev: u64,
        config_id: ConfigId,
        text_prov: &impl TextLayoutProvider,
        trigger: bool,
    ) {
        let text = text_prov.text();
        let last_line = text.line_of_offset(text.len());
        self.init_line_interval(cache_rev, config_id, text_prov, 0..=last_line, trigger);
    }

    /// Iterator over [`VLineInfo`]s, starting at `start_line`.
    pub fn iter_vlines(
        &self,
        text_prov: impl TextLayoutProvider,
        backwards: bool,
        start: VLine,
    ) -> impl Iterator<Item = VLineInfo> {
        VisualLines::new(self, text_prov, backwards, start)
    }

    /// Iterator over [`VLineInfo`]s, starting at `start_line` and ending at `end_line`.
    ///
    /// `start_line..end_line`
    pub fn iter_vlines_over(
        &self,
        text_prov: impl TextLayoutProvider,
        backwards: bool,
        start: VLine,
        end: VLine,
    ) -> impl Iterator<Item = VLineInfo> {
        self.iter_vlines(text_prov, backwards, start)
            .take_while(move |info| info.vline < end)
    }

    /// Iterator over *relative* [`VLineInfo`]s, starting at the rvline, `start_line`.
    ///
    /// This is preferable over `iter_vlines` if you do not need to absolute visual line value and
    /// can provide the buffer line.
    pub fn iter_rvlines(
        &self,
        text_prov: impl TextLayoutProvider,
        backwards: bool,
        start: RVLine,
    ) -> impl Iterator<Item = VLineInfo<()>> {
        VisualLinesRelative::new(self, text_prov, backwards, start)
    }

    /// Iterator over *relative* [`VLineInfo`]s, starting at the rvline `start_line` and
    /// ending at the buffer line `end_line`.
    ///
    /// `start_line..end_line`
    ///
    /// This is preferable over `iter_vlines` if you do not need the absolute visual line value and
    /// you can provide the buffer line.
    pub fn iter_rvlines_over(
        &self,
        text_prov: impl TextLayoutProvider,
        backwards: bool,
        start: RVLine,
        end_line: usize,
    ) -> impl Iterator<Item = VLineInfo<()>> {
        self.iter_rvlines(text_prov, backwards, start)
            .take_while(move |info| info.rvline.line < end_line)
    }

    // TODO(minor): Get rid of the clone bound.
    /// Initialize the text layouts as you iterate over them.
    pub fn iter_vlines_init(
        &self,
        text_prov: impl TextLayoutProvider + Clone,
        cache_rev: u64,
        config_id: ConfigId,
        start: VLine,
        trigger: bool,
    ) -> impl Iterator<Item = VLineInfo> {
        self.check_cache(cache_rev, config_id);

        if start <= self.last_vline(&text_prov) {
            // We initialize the text layout for the line that start line is for
            let (_, rvline) = find_vline_init_info(self, &text_prov, start).unwrap();
            self.get_init_text_layout(cache_rev, config_id, &text_prov, rvline.line, trigger);
            // If the start line was past the last vline then we don't need to initialize anything
            // since it won't get anything.
        }

        let text_layouts = self.text_layouts.clone();
        let font_sizes = self.font_sizes.clone();
        let wrap = self.wrap.get();
        let last_vline = self.last_vline.clone();
        let layout_event = trigger.then_some(self.layout_event);
        self.iter_vlines(text_prov.clone(), false, start)
            .inspect(move |v| {
                if v.is_first() {
                    // For every (first) vline we initialize the next buffer line's text layout
                    // This ensures it is ready for when re reach it.
                    let next_line = v.rvline.line + 1;
                    let font_size = font_sizes.borrow().font_size(next_line);
                    // `init_iter_vlines` is the reason `get_init_text_layout` is split out.
                    // Being split out lets us avoid attaching lifetimes to the iterator, since it
                    // only uses Rc/Arcs it is given.
                    // This is useful since `Lines` would be in a
                    // `Rc<RefCell<_>>` which would make iterators with lifetimes referring to
                    // `Lines` a pain.
                    get_init_text_layout(
                        &text_layouts,
                        layout_event,
                        &text_prov,
                        next_line,
                        font_size,
                        wrap,
                        &last_vline,
                    );
                }
            })
    }

    /// Iterator over [`VLineInfo`]s, starting at `start_line` and ending at `end_line`.
    /// `start_line..end_line`
    ///
    /// Initializes the text layouts as you iterate over them.
    ///
    /// `trigger` (default to true) decides whether the creation of the text layout should trigger
    /// the [`LayoutEvent::CreatedLayout`] event.
    pub fn iter_vlines_init_over(
        &self,
        text_prov: impl TextLayoutProvider + Clone,
        cache_rev: u64,
        config_id: ConfigId,
        start: VLine,
        end: VLine,
        trigger: bool,
    ) -> impl Iterator<Item = VLineInfo> {
        self.iter_vlines_init(text_prov, cache_rev, config_id, start, trigger)
            .take_while(move |info| info.vline < end)
    }

    /// Iterator over *relative* [`VLineInfo`]s, starting at the rvline, `start_line` and
    /// ending at the buffer line `end_line`.
    ///
    /// `start_line..end_line`
    ///
    /// `trigger` (default to true) decides whether the creation of the text layout should trigger
    /// the [`LayoutEvent::CreatedLayout`] event.
    pub fn iter_rvlines_init(
        &self,
        text_prov: impl TextLayoutProvider + Clone,
        cache_rev: u64,
        config_id: ConfigId,
        start: RVLine,
        trigger: bool,
    ) -> impl Iterator<Item = VLineInfo<()>> {
        self.check_cache(cache_rev, config_id);

        if start.line <= text_prov.rope_text().last_line() {
            // Initialize the text layout for the line that start line is for
            self.get_init_text_layout(cache_rev, config_id, &text_prov, start.line, trigger);
        }

        let text_layouts = self.text_layouts.clone();
        let font_sizes = self.font_sizes.clone();
        let wrap = self.wrap.get();
        let last_vline = self.last_vline.clone();
        let layout_event = trigger.then_some(self.layout_event);
        self.iter_rvlines(text_prov.clone(), false, start)
            .inspect(move |v| {
                if v.is_first() {
                    // For every (first) vline we initialize the next buffer line's text layout
                    // This ensures it is ready for when re reach it.
                    let next_line = v.rvline.line + 1;
                    let font_size = font_sizes.borrow().font_size(next_line);
                    // `init_iter_lines` is the reason `get_init_text_layout` is split out.
                    // Being split out lets us avoid attaching lifetimes to the iterator, since it
                    // only uses Rc/Arcs that it. This is useful since `Lines` would be in a
                    // `Rc<RefCell<_>>` which would make iterators with lifetimes referring to
                    // `Lines` a pain.
                    get_init_text_layout(
                        &text_layouts,
                        layout_event,
                        &text_prov,
                        next_line,
                        font_size,
                        wrap,
                        &last_vline,
                    );
                }
            })
    }

    /// Get the visual line of the offset.
    ///
    /// `affinity` decides whether an offset at a soft line break is considered to be on the
    /// previous line or the next line.
    ///
    /// If `affinity` is `CursorAffinity::Forward` and is at the very end of the wrapped line, then
    /// the offset is considered to be on the next vline.
    pub fn vline_of_offset(
        &self,
        text_prov: &impl TextLayoutProvider,
        offset: usize,
        affinity: CursorAffinity,
    ) -> VLine {
        let text = text_prov.text();

        let offset = offset.min(text.len());

        if self.is_linear(text_prov) {
            let buffer_line = text.line_of_offset(offset);
            return VLine(buffer_line);
        }

        let Some((vline, _line_index)) = find_vline_of_offset(self, text_prov, offset, affinity)
        else {
            // We assume it is out of bounds
            return self.last_vline(text_prov);
        };

        vline
    }

    /// Get the visual line and column of the given offset.
    ///
    /// The column is before phantom text is applied and is into the overall line, not the
    /// individual visual line.
    pub fn vline_col_of_offset(
        &self,
        text_prov: &impl TextLayoutProvider,
        offset: usize,
        affinity: CursorAffinity,
    ) -> (VLine, usize) {
        let vline = self.vline_of_offset(text_prov, offset, affinity);
        let last_col = self
            .iter_vlines(text_prov, false, vline)
            .next()
            .map(|info| info.last_col(text_prov, true))
            .unwrap_or(0);

        let line = text_prov.text().line_of_offset(offset);
        let line_offset = text_prov.text().offset_of_line(line);

        let col = offset - line_offset;
        let col = col.min(last_col);

        (vline, col)
    }

    /// Get the nearest offset to the start of the visual line
    pub fn offset_of_vline(&self, text_prov: &impl TextLayoutProvider, vline: VLine) -> usize {
        find_vline_init_info(self, text_prov, vline)
            .map(|x| x.0)
            .unwrap_or_else(|| text_prov.text().len())
    }

    /// Get the first visual line of the buffer line.
    pub fn vline_of_line(&self, text_prov: &impl TextLayoutProvider, line: usize) -> VLine {
        if self.is_linear(text_prov) {
            return VLine(line);
        }

        find_vline_of_line(self, text_prov, line).unwrap_or_else(|| self.last_vline(text_prov))
    }

    /// Find the matching visual line for the given relative visual line.
    pub fn vline_of_rvline(&self, text_prov: &impl TextLayoutProvider, rvline: RVLine) -> VLine {
        if self.is_linear(text_prov) {
            debug_assert_eq!(
                rvline.line_index, 0,
                "Got a nonzero line index despite being linear, old RVLine was used."
            );
            return VLine(rvline.line);
        }

        let vline = self.vline_of_line(text_prov, rvline.line);

        // TODO(minor): There may be edge cases with this, like when you have a bunch of multiline
        // phantom text at the same offset
        VLine(vline.get() + rvline.line_index)
    }

    /// Get the relative visual line of the offset.
    ///
    /// `affinity` decides whether an offset at a soft line break is considered to be on the
    /// previous line or the next line.
    /// If `affinity` is `CursorAffinity::Forward` and is at the very end of the wrapped line, then
    /// the offset is considered to be on the next rvline.
    pub fn rvline_of_offset(
        &self,
        text_prov: &impl TextLayoutProvider,
        offset: usize,
        affinity: CursorAffinity,
    ) -> RVLine {
        let text = text_prov.text();

        let offset = offset.min(text.len());

        if self.is_linear(text_prov) {
            let buffer_line = text.line_of_offset(offset);
            return RVLine::new(buffer_line, 0);
        }

        find_rvline_of_offset(self, text_prov, offset, affinity)
            .unwrap_or_else(|| self.last_rvline(text_prov))
    }

    /// Get the relative visual line and column of the given offset
    ///
    /// The column is before phantom text is applied and is into the overall line, not the
    /// individual visual line.
    pub fn rvline_col_of_offset(
        &self,
        text_prov: &impl TextLayoutProvider,
        offset: usize,
        affinity: CursorAffinity,
    ) -> (RVLine, usize) {
        let rvline = self.rvline_of_offset(text_prov, offset, affinity);
        let info = self.iter_rvlines(text_prov, false, rvline).next().unwrap();
        let line_offset = text_prov.text().offset_of_line(rvline.line);

        let col = offset - line_offset;
        let col = col.min(info.last_col(text_prov, true));

        (rvline, col)
    }

    /// Get the offset of a relative visual line
    pub fn offset_of_rvline(
        &self,
        text_prov: &impl TextLayoutProvider,
        RVLine { line, line_index }: RVLine,
    ) -> usize {
        let rope_text = text_prov.rope_text();
        let font_size = self.font_size(line);
        let layouts = self.text_layouts.borrow();

        // We could remove the debug asserts and allow invalid line indices. However I think it is
        // desirable to avoid those since they are probably indicative of bugs.
        if let Some(text_layout) = layouts.get(font_size, line) {
            debug_assert!(
                line_index < text_layout.line_count(),
                "Line index was out of bounds. This likely indicates keeping an rvline past when it was valid."
            );

            let line_index = line_index.min(text_layout.line_count() - 1);

            let col = text_layout
                .start_layout_cols(text_prov, line)
                .nth(line_index)
                .unwrap_or(0);
            let col = text_prov.before_phantom_col(line, col);

            rope_text.offset_of_line_col(line, col)
        } else {
            // There was no text layout for this line, so we treat it like if line index is zero
            // even if it is not.

            debug_assert_eq!(line_index, 0, "Line index was zero. This likely indicates keeping an rvline past when it was valid.");

            rope_text.offset_of_line(line)
        }
    }

    /// Get the relative visual line of the buffer line
    pub fn rvline_of_line(&self, text_prov: &impl TextLayoutProvider, line: usize) -> RVLine {
        if self.is_linear(text_prov) {
            return RVLine::new(line, 0);
        }

        let offset = text_prov.rope_text().offset_of_line(line);

        find_rvline_of_offset(self, text_prov, offset, CursorAffinity::Backward)
            .unwrap_or_else(|| self.last_rvline(text_prov))
    }

    /// Check whether the cache rev or config id has changed, clearing the cache if it has.
    pub fn check_cache(&self, cache_rev: u64, config_id: ConfigId) {
        let (prev_cache_rev, prev_config_id) = {
            let l = self.text_layouts.borrow();
            (l.cache_rev, l.config_id)
        };

        if cache_rev != prev_cache_rev || config_id != prev_config_id {
            self.clear(cache_rev, Some(config_id));
        }
    }

    /// Check whether the text layout cache revision is different.
    ///
    /// Clears the layouts and updates the cache rev if it was different.
    pub fn check_cache_rev(&self, cache_rev: u64) {
        if cache_rev != self.text_layouts.borrow().cache_rev {
            self.clear(cache_rev, None);
        }
    }

    /// Clear the text layouts with a given cache revision
    pub fn clear(&self, cache_rev: u64, config_id: Option<ConfigId>) {
        self.text_layouts.borrow_mut().clear(cache_rev, config_id);
        self.last_vline.set(None);
    }

    /// Clear the layouts and vline without changing the cache rev or config id.
    pub fn clear_unchanged(&self) {
        self.text_layouts.borrow_mut().clear_unchanged();
        self.last_vline.set(None);
    }
}

/// This is a separate function as a hacky solution to lifetimes.
///
/// While it being on `Lines` makes the most sense, it being separate lets us only have
/// `text_layouts` and `wrap` from the original to then initialize a text layout. This simplifies
/// lifetime issues in some functions, since they can just have an `Arc`/`Rc`.
///
/// Note: This does not clear the cache or check via config id. That should be done outside this
/// as `Lines` does require knowing when the cache is invalidated.
fn get_init_text_layout(
    text_layouts: &RefCell<TextLayoutCache>,
    layout_event: Option<Listener<LayoutEvent>>,
    text_prov: impl TextLayoutProvider,
    line: usize,
    font_size: usize,
    wrap: ResolvedWrap,
    last_vline: &Cell<Option<VLine>>,
) -> Arc<TextLayoutLine> {
    // If we don't have a second layer of the hashmap initialized for this specific font size,
    // do it now
    if !text_layouts.borrow().layouts.contains_key(&font_size) {
        let mut cache = text_layouts.borrow_mut();
        cache.layouts.insert(font_size, HashMap::new());
    }

    // Get whether there's an entry for this specific font size and line
    let cache_exists = text_layouts
        .borrow()
        .layouts
        .get(&font_size)
        .unwrap()
        .get(&line)
        .is_some();
    // If there isn't an entry then we actually have to create it
    if !cache_exists {
        let text_layout = text_prov.new_text_layout(line, font_size, wrap);

        // Update last vline
        if let Some(vline) = last_vline.get() {
            let last_line = text_prov.rope_text().last_line();
            if line <= last_line {
                // We can get rid of the old line count and add our new count.
                // This lets us typically avoid having to calculate the last visual line.
                let vline = vline.get();
                let new_vline = vline + (text_layout.line_count() - 1);

                last_vline.set(Some(VLine(new_vline)));
            }
            // If the line is past the end of the file, then we don't need to update the last
            // visual line. It is garbage.
        }
        // Otherwise last vline was already None.

        {
            // Add the text layout to the cache.
            let mut cache = text_layouts.borrow_mut();
            let width = text_layout.text.size().width;
            if width > cache.max_width {
                cache.max_width = width;
            }
            cache
                .layouts
                .get_mut(&font_size)
                .unwrap()
                .insert(line, text_layout);
        }

        if let Some(layout_event) = layout_event {
            layout_event.send(LayoutEvent::CreatedLayout { font_size, line });
        }
    }

    // Just get the entry, assuming it has been created because we initialize it above.
    text_layouts
        .borrow()
        .layouts
        .get(&font_size)
        .unwrap()
        .get(&line)
        .cloned()
        .unwrap()
}

/// Returns (visual line, line_index)
fn find_vline_of_offset(
    lines: &Lines,
    text_prov: &impl TextLayoutProvider,
    offset: usize,
    affinity: CursorAffinity,
) -> Option<(VLine, usize)> {
    let layouts = lines.text_layouts.borrow();

    let rope_text = text_prov.rope_text();

    let buffer_line = rope_text.line_of_offset(offset);
    let line_start_offset = rope_text.offset_of_line(buffer_line);
    let vline = find_vline_of_line(lines, text_prov, buffer_line)?;

    let font_size = lines.font_size(buffer_line);
    let Some(text_layout) = layouts.get(font_size, buffer_line) else {
        // No text layout for this line, so the vline we found is definitely correct.
        // As well, there is no previous soft line to consider
        return Some((vline, 0));
    };

    let col = offset - line_start_offset;

    let (vline, line_index) = find_start_line_index(text_prov, text_layout, buffer_line, col)
        .map(|line_index| (VLine(vline.get() + line_index), line_index))?;

    // If the most recent line break was due to a soft line break,
    if line_index > 0 {
        if let CursorAffinity::Backward = affinity {
            // TODO: This can definitely be smarter. We're doing a vline search, and then this is
            // practically doing another!
            let line_end = lines.offset_of_vline(text_prov, vline);
            // then if we're right at that soft line break, a backwards affinity
            // means that we are on the previous visual line.
            if line_end == offset && vline.get() != 0 {
                return Some((VLine(vline.get() - 1), line_index - 1));
            }
        }
    }

    Some((vline, line_index))
}

fn find_rvline_of_offset(
    lines: &Lines,
    text_prov: &impl TextLayoutProvider,
    offset: usize,
    affinity: CursorAffinity,
) -> Option<RVLine> {
    let layouts = lines.text_layouts.borrow();

    let rope_text = text_prov.rope_text();

    let buffer_line = rope_text.line_of_offset(offset);
    let line_start_offset = rope_text.offset_of_line(buffer_line);

    let font_size = lines.font_size(buffer_line);
    let Some(text_layout) = layouts.get(font_size, buffer_line) else {
        // There is no text layout for this line so the line index is always zero.
        return Some(RVLine::new(buffer_line, 0));
    };

    let col = offset - line_start_offset;

    let rv = find_start_line_index(text_prov, text_layout, buffer_line, col)
        .map(|line_index| RVLine::new(buffer_line, line_index))?;

    // If the most recent line break was due to a soft line break,
    if rv.line_index > 0 {
        if let CursorAffinity::Backward = affinity {
            let line_end = lines.offset_of_rvline(text_prov, rv);
            // then if we're right at that soft line break, a backwards affinity
            // means that we are on the previous visual line.
            if line_end == offset {
                if rv.line_index > 0 {
                    return Some(RVLine::new(rv.line, rv.line_index - 1));
                } else if rv.line == 0 {
                    // There is no previous line, we do nothing.
                } else {
                    // We have to get rvline info for that rvline, so we can get the last line index
                    // This should always have at least one rvline in it.
                    let font_sizes = lines.font_sizes.borrow();
                    let (prev, _) = prev_rvline(&layouts, text_prov, &**font_sizes, rv)?;
                    return Some(prev);
                }
            }
        }
    }

    Some(rv)
}

// TODO: a lot of these just take lines, so should possibly just be put on it.

/// Find the line index which contains the column.
fn find_start_line_index(
    text_prov: &impl TextLayoutProvider,
    text_layout: &TextLayoutLine,
    line: usize,
    col: usize,
) -> Option<usize> {
    let mut starts = text_layout
        .layout_cols(text_prov, line)
        .enumerate()
        .peekable();

    while let Some((i, (layout_start, _))) = starts.next() {
        // TODO: we should just apply after_col to col to do this transformation once
        let layout_start = text_prov.before_phantom_col(line, layout_start);
        if layout_start >= col {
            return Some(i);
        }

        let next_start = starts
            .peek()
            .map(|(_, (next_start, _))| text_prov.before_phantom_col(line, *next_start));

        if let Some(next_start) = next_start {
            if next_start > col {
                // The next layout starts *past* our column, so we're on the previous line.
                return Some(i);
            }
        } else {
            // There was no next glyph, which implies that we are either on this line or not at all
            return Some(i);
        }
    }

    None
}

/// Get the first visual line of a buffer line.
fn find_vline_of_line(
    lines: &Lines,
    text_prov: &impl TextLayoutProvider,
    line: usize,
) -> Option<VLine> {
    let rope = text_prov.rope_text();

    let last_line = rope.last_line();

    if line > last_line / 2 {
        // Often the last vline will already be cached, which lets us half the search time.
        // The compiler may or may not be smart enough to combine the last vline calculation with
        // our calculation of the vline of the line we're looking for, but it might not.
        // If it doesn't, we could write a custom version easily.
        let last_vline = lines.last_vline(text_prov);
        let last_rvline = lines.last_rvline(text_prov);
        let last_start_vline = VLine(last_vline.get() - last_rvline.line_index);
        find_vline_of_line_backwards(lines, (last_start_vline, last_line), line)
    } else {
        find_vline_of_line_forwards(lines, (VLine(0), 0), line)
    }
}

/// Get the first visual line of a buffer line.
///
/// This searches backwards from `pivot`, so it should be *after* the given line.
/// This requires that the `pivot` is the first line index of the line it is for.
fn find_vline_of_line_backwards(
    lines: &Lines,
    (start, s_line): (VLine, usize),
    line: usize,
) -> Option<VLine> {
    if line > s_line {
        return None;
    } else if line == s_line {
        return Some(start);
    } else if line == 0 {
        return Some(VLine(0));
    }

    let layouts = lines.text_layouts.borrow();

    let mut cur_vline = start.get();

    for cur_line in line..s_line {
        let font_size = lines.font_size(cur_line);

        let Some(text_layout) = layouts.get(font_size, cur_line) else {
            // no text layout, so its just a normal line
            cur_vline -= 1;
            continue;
        };

        let line_count = text_layout.line_count();

        cur_vline -= line_count;
    }

    Some(VLine(cur_vline))
}

fn find_vline_of_line_forwards(
    lines: &Lines,
    (start, s_line): (VLine, usize),
    line: usize,
) -> Option<VLine> {
    match line.cmp(&s_line) {
        Ordering::Equal => return Some(start),
        Ordering::Less => return None,
        Ordering::Greater => (),
    }

    let layouts = lines.text_layouts.borrow();

    let mut cur_vline = start.get();

    for cur_line in s_line..line {
        let font_size = lines.font_size(cur_line);

        let Some(text_layout) = layouts.get(font_size, cur_line) else {
            // no text layout, so its just a normal line
            cur_vline += 1;
            continue;
        };

        let line_count = text_layout.line_count();
        cur_vline += line_count;
    }

    Some(VLine(cur_vline))
}

/// Find the (start offset, buffer line, layout line index) of a given visual line.
///
/// start offset is into the file, rather than the text layouts string, so it does not include
/// phantom text.
///
/// Returns `None` if the visual line is out of bounds.
fn find_vline_init_info(
    lines: &Lines,
    text_prov: &impl TextLayoutProvider,
    vline: VLine,
) -> Option<(usize, RVLine)> {
    let rope_text = text_prov.rope_text();

    if vline.get() == 0 {
        return Some((0, RVLine::new(0, 0)));
    }

    if lines.is_linear(text_prov) {
        // If lines is linear then we can trivially convert the visual line to a buffer line
        let line = vline.get();
        if line > rope_text.last_line() {
            return None;
        }

        return Some((rope_text.offset_of_line(line), RVLine::new(line, 0)));
    }

    let last_vline = lines.last_vline(text_prov);

    if vline > last_vline {
        return None;
    }

    if vline.get() < last_vline.get() / 2 {
        let last_rvline = lines.last_rvline(text_prov);
        find_vline_init_info_rv_backward(lines, text_prov, (last_vline, last_rvline), vline)
    } else {
        find_vline_init_info_forward(lines, text_prov, (VLine(0), 0), vline)
    }
}

// TODO(minor): should we package (VLine, buffer line) into a struct since we use it for these
// pseudo relative calculations often?
/// Find the `(start offset, rvline)` of a given [`VLine`]
///
/// start offset is into the file, rather than text layout's string, so it does not include
/// phantom text.
///
/// Returns `None` if the visual line is out of bounds, or if the start is past our target.
fn find_vline_init_info_forward(
    lines: &Lines,
    text_prov: &impl TextLayoutProvider,
    (start, start_line): (VLine, usize),
    vline: VLine,
) -> Option<(usize, RVLine)> {
    if start > vline {
        return None;
    }

    let rope_text = text_prov.rope_text();

    let mut cur_line = start_line;
    let mut cur_vline = start.get();

    let layouts = lines.text_layouts.borrow();
    while cur_vline < vline.get() {
        let font_size = lines.font_size(cur_line);
        let line_count = if let Some(text_layout) = layouts.get(font_size, cur_line) {
            let line_count = text_layout.line_count();

            // We can then check if the visual line is in this intervening range.
            if cur_vline + line_count > vline.get() {
                // We found the line that contains the visual line.
                // We can now find the offset of the visual line within the line.
                let line_index = vline.get() - cur_vline;
                // TODO: is it fine to unwrap here?
                let col = text_layout
                    .start_layout_cols(text_prov, cur_line)
                    .nth(line_index)
                    .unwrap_or(0);
                let col = text_prov.before_phantom_col(cur_line, col);

                let offset = rope_text.offset_of_line_col(cur_line, col);
                return Some((offset, RVLine::new(cur_line, line_index)));
            }

            // The visual line is not in this line, so we have to keep looking.
            line_count
        } else {
            // There was no text layout so we only have to consider the line breaks in this line.
            // Which, since we don't handle phantom text, is just one.

            1
        };

        cur_line += 1;
        cur_vline += line_count;
    }

    // We've reached the visual line we're looking for, we can return the offset.
    // This also handles the case where the vline is past the end of the text.
    if cur_vline == vline.get() {
        if cur_line > rope_text.last_line() {
            return None;
        }

        // We use cur_line because if our target vline is out of bounds
        // then the result should be len
        Some((rope_text.offset_of_line(cur_line), RVLine::new(cur_line, 0)))
    } else {
        // We've gone past the visual line we're looking for, so it is out of bounds.
        None
    }
}

/// Find the `(start offset, rvline)` of a given [`VLine`]
///
/// `start offset` is into the file, rather than the text layout's content, so it does not
/// include phantom text.
///
/// Returns `None` if the visual line is out of bounds or if the start is before our target.
/// This iterates backwards.
fn find_vline_init_info_rv_backward(
    lines: &Lines,
    text_prov: &impl TextLayoutProvider,
    (start, start_rvline): (VLine, RVLine),
    vline: VLine,
) -> Option<(usize, RVLine)> {
    if start < vline {
        // The start was before the target.
        return None;
    }

    // This would the vline at the very start of the buffer line
    let shifted_start = VLine(start.get() - start_rvline.line_index);
    match shifted_start.cmp(&vline) {
        // The shifted start was equivalent to the vline, which makes it easy to compute
        Ordering::Equal => {
            let offset = text_prov.rope_text().offset_of_line(start_rvline.line);
            Some((offset, RVLine::new(start_rvline.line, 0)))
        }
        // The new start is before the vline, that means the vline is on the same line.
        Ordering::Less => {
            let line_index = vline.get() - shifted_start.get();
            let layouts = lines.text_layouts.borrow();
            let font_size = lines.font_size(start_rvline.line);
            if let Some(text_layout) = layouts.get(font_size, start_rvline.line) {
                vline_init_info_b(
                    text_prov,
                    text_layout,
                    RVLine::new(start_rvline.line, line_index),
                )
            } else {
                // There was no text layout so we only have to consider the line breaks in this line.

                let base_offset = text_prov.rope_text().offset_of_line(start_rvline.line);
                Some((base_offset, RVLine::new(start_rvline.line, 0)))
            }
        }
        Ordering::Greater => find_vline_init_info_backward(
            lines,
            text_prov,
            (shifted_start, start_rvline.line),
            vline,
        ),
    }
}

fn find_vline_init_info_backward(
    lines: &Lines,
    text_prov: &impl TextLayoutProvider,
    (mut start, mut start_line): (VLine, usize),
    vline: VLine,
) -> Option<(usize, RVLine)> {
    loop {
        let (prev_vline, prev_line) = prev_line_start(lines, start, start_line)?;

        match prev_vline.cmp(&vline) {
            // We found the target, and it was at the start
            Ordering::Equal => {
                let offset = text_prov.rope_text().offset_of_line(prev_line);
                return Some((offset, RVLine::new(prev_line, 0)));
            }
            // The target is on this line, so we can just search for it
            Ordering::Less => {
                let font_size = lines.font_size(prev_line);
                let layouts = lines.text_layouts.borrow();
                if let Some(text_layout) = layouts.get(font_size, prev_line) {
                    return vline_init_info_b(
                        text_prov,
                        text_layout,
                        RVLine::new(prev_line, vline.get() - prev_vline.get()),
                    );
                } else {
                    // There was no text layout so we only have to consider the line breaks in this line.
                    // Which, since we don't handle phantom text, is just one.

                    let base_offset = text_prov.rope_text().offset_of_line(prev_line);
                    return Some((base_offset, RVLine::new(prev_line, 0)));
                }
            }
            // The target is before this line, so we have to keep searching
            Ordering::Greater => {
                start = prev_vline;
                start_line = prev_line;
            }
        }
    }
}

/// Get the previous (line, start visual line) from a (line, start visual line).
fn prev_line_start(lines: &Lines, vline: VLine, line: usize) -> Option<(VLine, usize)> {
    if line == 0 {
        return None;
    }

    let layouts = lines.text_layouts.borrow();

    let prev_line = line - 1;
    let font_size = lines.font_size(line);
    if let Some(layout) = layouts.get(font_size, prev_line) {
        let line_count = layout.line_count();
        let prev_vline = vline.get() - line_count;
        Some((VLine(prev_vline), prev_line))
    } else {
        // There's no layout for the previous line which makes this easy
        Some((VLine(vline.get() - 1), prev_line))
    }
}

fn vline_init_info_b(
    text_prov: &impl TextLayoutProvider,
    text_layout: &TextLayoutLine,
    rv: RVLine,
) -> Option<(usize, RVLine)> {
    let rope_text = text_prov.rope_text();
    let col = text_layout
        .start_layout_cols(text_prov, rv.line)
        .nth(rv.line_index)
        .unwrap_or(0);
    let col = text_prov.before_phantom_col(rv.line, col);

    let offset = rope_text.offset_of_line_col(rv.line, col);

    Some((offset, rv))
}

/// Information about the visual line and how it relates to the underlying buffer line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct VLineInfo<L = VLine> {
    /// Start offset to end offset in the buffer that this visual line covers.
    ///
    /// Note that this is obviously not including phantom text.
    pub interval: Interval,
    /// The total number of lines in this buffer line. Always at least 1.
    pub line_count: usize,
    pub rvline: RVLine,
    /// The actual visual line this is for.
    ///
    /// For relative visual line iteration, this is empty.
    pub vline: L,
}
impl<L: std::fmt::Debug> VLineInfo<L> {
    /// Create a new instance of `VLineInfo`
    ///
    /// This should rarely be used directly.
    pub fn new<I: Into<Interval>>(iv: I, rvline: RVLine, line_count: usize, vline: L) -> Self {
        Self {
            interval: iv.into(),
            line_count,
            rvline,
            vline,
        }
    }

    pub fn to_blank(&self) -> VLineInfo<()> {
        VLineInfo::new(self.interval, self.rvline, self.line_count, ())
    }

    /// Check whether the interval is empty.
    ///
    /// Note that there could still be phantom text on this line.
    pub fn is_empty(&self) -> bool {
        self.interval.is_empty()
    }

    /// Check whether the interval is empty and we're not on the first line,
    /// thus likely being phantom text (or possibly poor wrapping)
    pub fn is_empty_phantom(&self) -> bool {
        self.is_empty() && self.rvline.line_index != 0
    }

    pub fn is_first(&self) -> bool {
        self.rvline.is_first()
    }

    // TODO: is this correct for phantom lines?
    // TODO: can't we just use the line count field now?
    /// Is this the last visual line for the relevant buffer line?
    pub fn is_last(&self, text_prov: &impl TextLayoutProvider) -> bool {
        let rope_text = text_prov.rope_text();
        let line_end = rope_text.line_end_offset(self.rvline.line, false);
        let vline_end = self.line_end_offset(text_prov, false);

        line_end == vline_end
    }

    /// Get the first column of the overall line of the visual line
    pub fn first_col(&self, text_prov: &impl TextLayoutProvider) -> usize {
        let line_start = self.interval.start;
        let start_offset = text_prov.text().offset_of_line(self.rvline.line);
        line_start - start_offset
    }

    /// Get the last column in the overall line of this visual line
    ///
    /// The caret decides whether it is after the last character, or before it.
    /// ```rust,ignore
    /// // line content = "conf = Config::default();\n"
    /// // wrapped breakup = ["conf = ", "Config::default();\n"]
    ///
    /// // when vline_info is for "conf = "
    /// assert_eq!(vline_info.last_col(text_prov, false), 6) // "conf =| "
    /// assert_eq!(vline_info.last_col(text_prov, true), 7) // "conf = |"
    /// // when vline_info is for "Config::default();\n"
    /// // Notice that the column is in the overall line, not the wrapped line.
    /// assert_eq!(vline_info.last_col(text_prov, false), 24) // "Config::default()|;"
    /// assert_eq!(vline_info.last_col(text_prov, true), 25) // "Config::default();|"
    /// ```
    pub fn last_col(&self, text_prov: &impl TextLayoutProvider, caret: bool) -> usize {
        let vline_end = self.interval.end;
        let start_offset = text_prov.text().offset_of_line(self.rvline.line);
        // If these subtractions crash, then it is likely due to a bad vline being kept around
        // somewhere
        if !caret && !self.is_empty() {
            let vline_pre_end = text_prov.rope_text().prev_grapheme_offset(vline_end, 1, 0);
            vline_pre_end - start_offset
        } else {
            vline_end - start_offset
        }
    }

    // TODO: we could generalize `RopeText::line_end_offset` to any interval, and then just use it here instead of basically reimplementing it.
    pub fn line_end_offset(&self, text_prov: &impl TextLayoutProvider, caret: bool) -> usize {
        let text = text_prov.text();
        let rope_text = text_prov.rope_text();

        let mut offset = self.interval.end;
        let mut line_content: &str = &text.slice_to_cow(self.interval);
        if line_content.ends_with("\r\n") {
            offset -= 2;
            line_content = &line_content[..line_content.len() - 2];
        } else if line_content.ends_with('\n') {
            offset -= 1;
            line_content = &line_content[..line_content.len() - 1];
        }
        if !caret && !line_content.is_empty() {
            offset = rope_text.prev_grapheme_offset(offset, 1, 0);
        }
        offset
    }

    /// Returns the offset of the first non-blank character in the line.
    pub fn first_non_blank_character(&self, text_prov: &impl TextLayoutProvider) -> usize {
        WordCursor::new(&text_prov.text(), self.interval.start).next_non_blank_char()
    }
}

/// Iterator of the visual lines in a [`Lines`].
///
/// This only considers wrapped and phantom text lines that have been rendered into a text layout.
///
/// In principle, we could consider the newlines in phantom text for lines that have not been
/// rendered. However, that is more expensive to compute and is probably not actually *useful*.
struct VisualLines<T: TextLayoutProvider> {
    v: VisualLinesRelative<T>,
    vline: VLine,
}
impl<T: TextLayoutProvider> VisualLines<T> {
    pub fn new(lines: &Lines, text_prov: T, backwards: bool, start: VLine) -> VisualLines<T> {
        // TODO(minor): If we aren't using offset here then don't calculate it.
        let Some((_offset, rvline)) = find_vline_init_info(lines, &text_prov, start) else {
            return VisualLines::empty(lines, text_prov, backwards);
        };

        VisualLines {
            v: VisualLinesRelative::new(lines, text_prov, backwards, rvline),
            vline: start,
        }
    }

    pub fn empty(lines: &Lines, text_prov: T, backwards: bool) -> VisualLines<T> {
        VisualLines {
            v: VisualLinesRelative::empty(lines, text_prov, backwards),
            vline: VLine(0),
        }
    }
}
impl<T: TextLayoutProvider> Iterator for VisualLines<T> {
    type Item = VLineInfo;

    fn next(&mut self) -> Option<VLineInfo> {
        let was_first_iter = self.v.is_first_iter;
        let info = self.v.next()?;

        if !was_first_iter {
            if self.v.backwards {
                // This saturation isn't really needed, but just in case.
                debug_assert!(
                    self.vline.get() != 0,
                    "Expected VLine to always be nonzero if we were going backwards"
                );
                self.vline = VLine(self.vline.get().saturating_sub(1));
            } else {
                self.vline = VLine(self.vline.get() + 1);
            }
        }

        Some(VLineInfo {
            interval: info.interval,
            line_count: info.line_count,
            rvline: info.rvline,
            vline: self.vline,
        })
    }
}

/// Iterator of the visual lines in a [`Lines`] relative to some starting buffer line.
///
/// This only considers wrapped and phantom text lines that have been rendered into a text layout.
struct VisualLinesRelative<T: TextLayoutProvider> {
    font_sizes: Rc<dyn LineFontSizeProvider>,
    text_layouts: Rc<RefCell<TextLayoutCache>>,
    text_prov: T,

    is_done: bool,

    rvline: RVLine,
    /// Our current offset into the rope.
    offset: usize,

    /// Which direction we should move in.
    backwards: bool,
    /// Whether there is a one-to-one mapping between buffer lines and visual lines.
    linear: bool,

    is_first_iter: bool,
}
impl<T: TextLayoutProvider> VisualLinesRelative<T> {
    pub fn new(
        lines: &Lines,
        text_prov: T,
        backwards: bool,
        start: RVLine,
    ) -> VisualLinesRelative<T> {
        // Empty iterator if we're past the end of the possible lines
        if start > lines.last_rvline(&text_prov) {
            return VisualLinesRelative::empty(lines, text_prov, backwards);
        }

        let layouts = lines.text_layouts.borrow();
        let font_size = lines.font_size(start.line);
        let offset = rvline_offset(&layouts, &text_prov, font_size, start);

        let linear = lines.is_linear(&text_prov);

        VisualLinesRelative {
            font_sizes: lines.font_sizes.borrow().clone(),
            text_layouts: lines.text_layouts.clone(),
            text_prov,
            is_done: false,
            rvline: start,
            offset,
            backwards,
            linear,
            is_first_iter: true,
        }
    }

    pub fn empty(lines: &Lines, text_prov: T, backwards: bool) -> VisualLinesRelative<T> {
        VisualLinesRelative {
            font_sizes: lines.font_sizes.borrow().clone(),
            text_layouts: lines.text_layouts.clone(),
            text_prov,
            is_done: true,
            rvline: RVLine::new(0, 0),
            offset: 0,
            backwards,
            linear: true,
            is_first_iter: true,
        }
    }
}
impl<T: TextLayoutProvider> Iterator for VisualLinesRelative<T> {
    type Item = VLineInfo<()>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.is_done {
            return None;
        }

        let layouts = self.text_layouts.borrow();
        if self.is_first_iter {
            // This skips the next line call on the first line.
            self.is_first_iter = false;
        } else {
            let v = shift_rvline(
                &layouts,
                &self.text_prov,
                &*self.font_sizes,
                self.rvline,
                self.backwards,
                self.linear,
            );
            let Some((new_rel_vline, offset)) = v else {
                self.is_done = true;
                return None;
            };

            self.rvline = new_rel_vline;
            self.offset = offset;

            if self.rvline.line > self.text_prov.rope_text().last_line() {
                self.is_done = true;
                return None;
            }
        }

        let line = self.rvline.line;
        let line_index = self.rvline.line_index;
        let vline = self.rvline;

        let start = self.offset;

        let font_size = self.font_sizes.font_size(line);
        let end = end_of_rvline(&layouts, &self.text_prov, font_size, self.rvline);

        let line_count = if let Some(text_layout) = layouts.get(font_size, line) {
            text_layout.line_count()
        } else {
            1
        };
        debug_assert!(start <= end, "line: {line}, line_index: {line_index}, line_count: {line_count}, vline: {vline:?}, start: {start}, end: {end}, backwards: {} text_len: {}", self.backwards, self.text_prov.text().len());
        let info = VLineInfo::new(start..end, self.rvline, line_count, ());

        Some(info)
    }
}

// TODO: This might skip spaces at the end of lines, which we probably don't want?
/// Get the end offset of the visual line from the file's line and the line index.
fn end_of_rvline(
    layouts: &TextLayoutCache,
    text_prov: &impl TextLayoutProvider,
    font_size: usize,
    RVLine { line, line_index }: RVLine,
) -> usize {
    if line > text_prov.rope_text().last_line() {
        return text_prov.text().len();
    }

    if let Some((_, end_col)) = layouts.get_layout_col(text_prov, font_size, line, line_index) {
        let end_col = text_prov.before_phantom_col(line, end_col);
        text_prov.rope_text().offset_of_line_col(line, end_col)
    } else {
        let rope_text = text_prov.rope_text();

        rope_text.line_end_offset(line, true)
    }
}

/// Shift a relative visual line forward or backwards based on the `backwards` parameter.
fn shift_rvline(
    layouts: &TextLayoutCache,
    text_prov: &impl TextLayoutProvider,
    font_sizes: &dyn LineFontSizeProvider,
    vline: RVLine,
    backwards: bool,
    linear: bool,
) -> Option<(RVLine, usize)> {
    if linear {
        let rope_text = text_prov.rope_text();
        debug_assert_eq!(
            vline.line_index, 0,
            "Line index should be zero if we're linearly working with lines"
        );
        if backwards {
            if vline.line == 0 {
                return None;
            }

            let prev_line = vline.line - 1;
            let offset = rope_text.offset_of_line(prev_line);
            Some((RVLine::new(prev_line, 0), offset))
        } else {
            let next_line = vline.line + 1;

            if next_line > rope_text.last_line() {
                return None;
            }

            let offset = rope_text.offset_of_line(next_line);
            Some((RVLine::new(next_line, 0), offset))
        }
    } else if backwards {
        prev_rvline(layouts, text_prov, font_sizes, vline)
    } else {
        let font_size = font_sizes.font_size(vline.line);
        Some(next_rvline(layouts, text_prov, font_size, vline))
    }
}

fn rvline_offset(
    layouts: &TextLayoutCache,
    text_prov: &impl TextLayoutProvider,
    font_size: usize,
    RVLine { line, line_index }: RVLine,
) -> usize {
    let rope_text = text_prov.rope_text();
    if let Some((line_col, _)) = layouts.get_layout_col(text_prov, font_size, line, line_index) {
        let line_col = text_prov.before_phantom_col(line, line_col);

        rope_text.offset_of_line_col(line, line_col)
    } else {
        // There was no text layout line so this is a normal line.
        debug_assert_eq!(line_index, 0);

        rope_text.offset_of_line(line)
    }
}

/// Move to the next visual line, giving the new information.
///
/// Returns `(new rel vline, offset)`
fn next_rvline(
    layouts: &TextLayoutCache,
    text_prov: &impl TextLayoutProvider,
    font_size: usize,
    RVLine { line, line_index }: RVLine,
) -> (RVLine, usize) {
    let rope_text = text_prov.rope_text();
    if let Some(layout_line) = layouts.get(font_size, line) {
        if let Some((line_col, _)) = layout_line.layout_cols(text_prov, line).nth(line_index + 1) {
            let line_col = text_prov.before_phantom_col(line, line_col);
            let offset = rope_text.offset_of_line_col(line, line_col);

            (RVLine::new(line, line_index + 1), offset)
        } else {
            // There was no next layout/vline on this buffer line.
            // So we can simply move to the start of the next buffer line.

            (RVLine::new(line + 1, 0), rope_text.offset_of_line(line + 1))
        }
    } else {
        // There was no text layout line, so this is a normal line.
        debug_assert_eq!(line_index, 0);

        (RVLine::new(line + 1, 0), rope_text.offset_of_line(line + 1))
    }
}

/// Move to the previous visual line, giving the new information.
///
/// Returns `(new line, new line_index, offset)`
///
/// Returns `None` if the line and line index are zero and thus there is no previous visual line.
fn prev_rvline(
    layouts: &TextLayoutCache,
    text_prov: &impl TextLayoutProvider,
    font_sizes: &dyn LineFontSizeProvider,
    RVLine { line, line_index }: RVLine,
) -> Option<(RVLine, usize)> {
    let rope_text = text_prov.rope_text();
    if line_index == 0 {
        // Line index was zero so we must be moving back a buffer line
        if line == 0 {
            return None;
        }

        let prev_line = line - 1;
        let font_size = font_sizes.font_size(prev_line);
        if let Some(layout_line) = layouts.get(font_size, prev_line) {
            let (i, line_col) = layout_line
                .start_layout_cols(text_prov, prev_line)
                .enumerate()
                .last()
                .unwrap_or((0, 0));
            let line_col = text_prov.before_phantom_col(prev_line, line_col);
            let offset = rope_text.offset_of_line_col(prev_line, line_col);

            Some((RVLine::new(prev_line, i), offset))
        } else {
            // There was no text layout line, so the previous line is a normal line.
            let prev_line_offset = rope_text.offset_of_line(prev_line);
            Some((RVLine::new(prev_line, 0), prev_line_offset))
        }
    } else {
        // We're still on the same buffer line, so we can just move to the previous layout/vline.

        let prev_line_index = line_index - 1;
        let font_size = font_sizes.font_size(line);
        if let Some(layout_line) = layouts.get(font_size, line) {
            if let Some((line_col, _)) = layout_line
                .layout_cols(text_prov, line)
                .nth(prev_line_index)
            {
                let line_col = text_prov.before_phantom_col(line, line_col);
                let offset = rope_text.offset_of_line_col(line, line_col);

                Some((RVLine::new(line, prev_line_index), offset))
            } else {
                // There was no previous layout/vline on this buffer line.
                // So we can simply move to the end of the previous buffer line.

                let prev_line_offset = rope_text.offset_of_line(line - 1);
                Some((RVLine::new(line - 1, 0), prev_line_offset))
            }
        } else {
            debug_assert!(
                false,
                "line_index was nonzero but there was no text layout line"
            );
            // Despite that this shouldn't happen we default to just giving the start of this
            // normal line
            let line_offset = rope_text.offset_of_line(line);
            Some((RVLine::new(line, 0), line_offset))
        }
    }
}

// FIXME: Put this in our cosmic-text fork.

/// Hit position but decides whether it should go to the next line based on the `before` bool.
///
/// (Hit position should be equivalent to `before=false`).
/// This is needed when we have an idx at the end of, for example, a wrapped line which could be on
/// the first or second line.
pub fn hit_position_aff(this: &TextLayout, idx: usize, before: bool) -> HitPosition {
    let mut last_line = 0;
    let mut last_end: usize = 0;
    let mut offset = 0;
    let mut last_glyph: Option<(&LayoutGlyph, usize)> = None;
    let mut last_line_width = 0.0;
    let mut last_glyph_width = 0.0;
    let mut last_position = HitPosition {
        line: 0,
        point: Point::ZERO,
        glyph_ascent: 0.0,
        glyph_descent: 0.0,
    };
    for (line, run) in this.layout_runs().enumerate() {
        if run.line_i > last_line {
            last_line = run.line_i;
            offset += last_end;
        }

        // Handles wrapped lines, like:
        // ```rust
        // let config_path = |
        // dirs::config_dir();
        // ```
        // The glyphs won't contain the space at the end of the first part, and the position right
        // after the space is the same column as at `|dirs`, which is what before is letting us
        // distinguish.
        // So essentially, if the next run has a glyph that is at the same idx as the end of the
        // previous run, *and* it is at `idx` itself, then we know to position it on the previous.
        if let Some((last_glyph, last_offset)) = last_glyph {
            if let Some(first_glyph) = run.glyphs.first() {
                let end = last_glyph.end + last_offset;
                if before && idx == first_glyph.start + offset {
                    last_position.point.x = if end == idx {
                        // if last glyph end index == idx == first glyph start index,
                        // it means the wrap wasn't from a whitespace
                        last_line_width as f64
                    } else {
                        // the wrap was a whitespace so we need to add the whitespace's width
                        // to the line width
                        (last_line_width + last_glyph.w) as f64
                    };
                    return last_position;
                }
            }
        }

        for glyph in run.glyphs {
            if glyph.start + offset > idx {
                last_position.point.x += last_glyph_width as f64;
                return last_position;
            }
            last_end = glyph.end;
            last_glyph_width = glyph.w;
            last_position = HitPosition {
                line,
                point: Point::new(glyph.x as f64, run.line_y as f64),
                glyph_ascent: run.max_ascent as f64,
                glyph_descent: run.max_descent as f64,
            };
            if (glyph.start + offset..glyph.end + offset).contains(&idx) {
                return last_position;
            }
        }

        last_glyph = run.glyphs.last().map(|g| (g, offset));
        last_line_width = run.line_w;
    }

    if idx > 0 {
        last_position.point.x += last_glyph_width as f64;
        return last_position;
    }

    HitPosition {
        line: 0,
        point: Point::ZERO,
        glyph_ascent: 0.0,
        glyph_descent: 0.0,
    }
}

#[cfg(test)]
mod tests {
    use std::{borrow::Cow, cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};

    use floem_editor_core::{
        buffer::rope_text::{RopeText, RopeTextRef, RopeTextVal},
        cursor::CursorAffinity,
    };
    use floem_reactive::Scope;
    use floem_renderer::text::{Attrs, AttrsList, FamilyOwned, TextLayout, Wrap};
    use lapce_xi_rope::Rope;
    use smallvec::smallvec;

    use crate::views::editor::{
        layout::TextLayoutLine,
        phantom_text::{PhantomText, PhantomTextKind, PhantomTextLine},
        visual_line::{end_of_rvline, find_vline_of_line_backwards, find_vline_of_line_forwards},
    };

    use super::{
        find_vline_init_info_forward, find_vline_init_info_rv_backward, ConfigId, FontSizeCacheId,
        LineFontSizeProvider, Lines, RVLine, ResolvedWrap, TextLayoutProvider, VLine,
    };

    /// For most of the logic we standardize on a specific font size.
    const FONT_SIZE: usize = 12;

    struct TestTextLayoutProvider<'a> {
        text: &'a Rope,
        phantom: HashMap<usize, PhantomTextLine>,
        font_family: Vec<FamilyOwned>,
        #[allow(dead_code)]
        wrap: Wrap,
    }
    impl<'a> TestTextLayoutProvider<'a> {
        fn new(text: &'a Rope, ph: HashMap<usize, PhantomTextLine>, wrap: Wrap) -> Self {
            Self {
                text,
                phantom: ph,
                // we use a specific font to make width calculations consistent between platforms.
                // TODO(minor): Is there a more common font that we can use?
                #[cfg(not(target_os = "windows"))]
                font_family: vec![FamilyOwned::SansSerif],
                #[cfg(target_os = "windows")]
                font_family: vec![FamilyOwned::Name("Arial".to_string())],
                wrap,
            }
        }
    }
    impl<'a> TextLayoutProvider for TestTextLayoutProvider<'a> {
        fn text(&self) -> Rope {
            self.text.clone()
        }

        // An implementation relatively close to the actual new text layout impl but simplified.
        // TODO(minor): It would be nice to just use the same impl as view's
        fn new_text_layout(
            &self,
            line: usize,
            font_size: usize,
            wrap: ResolvedWrap,
        ) -> Arc<TextLayoutLine> {
            let rope_text = RopeTextRef::new(self.text);
            let line_content_original = rope_text.line_content(line);

            // Get the line content with newline characters replaced with spaces
            // and the content without the newline characters
            let (line_content, _line_content_original) =
                if let Some(s) = line_content_original.strip_suffix("\r\n") {
                    (
                        format!("{s}  "),
                        &line_content_original[..line_content_original.len() - 2],
                    )
                } else if let Some(s) = line_content_original.strip_suffix('\n') {
                    (
                        format!("{s} ",),
                        &line_content_original[..line_content_original.len() - 1],
                    )
                } else {
                    (
                        line_content_original.to_string(),
                        &line_content_original[..],
                    )
                };

            let phantom_text = self.phantom.get(&line).cloned().unwrap_or_default();
            let line_content = phantom_text.combine_with_text(&line_content);

            // let color

            let attrs = Attrs::new()
                .family(&self.font_family)
                .font_size(font_size as f32);
            let mut attrs_list = AttrsList::new(attrs);

            // We don't do line styles, since they aren't relevant

            // Apply phantom text specific styling
            for (offset, size, col, phantom) in phantom_text.offset_size_iter() {
                let start = col + offset;
                let end = start + size;

                let mut attrs = attrs;
                if let Some(fg) = phantom.fg {
                    attrs = attrs.color(fg);
                }
                if let Some(phantom_font_size) = phantom.font_size {
                    attrs = attrs.font_size(phantom_font_size.min(font_size) as f32);
                }
                attrs_list.add_span(start..end, attrs);
                // if let Some(font_family) = phantom.font_family.clone() {
                //     layout_builder = layout_builder.range_attribute(
                //         start..end,
                //         TextAttribute::FontFamily(font_family),
                //     );
                // }
            }

            let mut text_layout = TextLayout::new();
            text_layout.set_wrap(Wrap::Word);
            match wrap {
                // We do not have to set the wrap mode if we do not set the width
                ResolvedWrap::None => {}
                ResolvedWrap::Column(_col) => todo!(),
                ResolvedWrap::Width(px) => {
                    text_layout.set_size(px, f32::MAX);
                }
            }
            text_layout.set_text(&line_content, attrs_list);

            // skip phantom text background styling because it doesn't shift positions
            // skip severity styling
            // skip diagnostic background styling

            Arc::new(TextLayoutLine {
                extra_style: Vec::new(),
                text: text_layout,
                whitespaces: None,
                indent: 0.0,
                phantom_text: PhantomTextLine::default(),
            })
        }

        fn before_phantom_col(&self, line: usize, col: usize) -> usize {
            self.phantom
                .get(&line)
                .map(|x| x.before_col(col))
                .unwrap_or(col)
        }

        fn has_multiline_phantom(&self) -> bool {
            // Conservatively, yes.
            true
        }
    }

    struct TestFontSize {
        font_size: usize,
    }
    impl LineFontSizeProvider for TestFontSize {
        fn font_size(&self, _line: usize) -> usize {
            self.font_size
        }

        fn cache_id(&self) -> FontSizeCacheId {
            0
        }
    }

    fn make_lines(text: &Rope, width: f32, init: bool) -> (TestTextLayoutProvider<'_>, Lines) {
        make_lines_ph(text, width, init, HashMap::new())
    }

    fn make_lines_ph(
        text: &Rope,
        width: f32,
        init: bool,
        ph: HashMap<usize, PhantomTextLine>,
    ) -> (TestTextLayoutProvider<'_>, Lines) {
        let wrap = Wrap::Word;
        let r_wrap = ResolvedWrap::Width(width);
        let font_sizes = TestFontSize {
            font_size: FONT_SIZE,
        };
        let text = TestTextLayoutProvider::new(text, ph, wrap);
        let cx = Scope::new();
        let lines = Lines::new(cx, RefCell::new(Rc::new(font_sizes)));
        lines.set_wrap(r_wrap);

        if init {
            let config_id = 0;
            let floem_style_id = 0;
            lines.init_all(0, ConfigId::new(config_id, floem_style_id), &text, true);
        }

        (text, lines)
    }

    fn render_breaks<'a>(text: &'a Rope, lines: &mut Lines, font_size: usize) -> Vec<Cow<'a, str>> {
        // TODO: line_content on ropetextref would have the lifetime reference rope_text
        // rather than the held &'a Rope.
        // I think this would require an alternate trait for those functions to avoid incorrect lifetimes. Annoying but workable.
        let rope_text = RopeTextRef::new(text);
        let mut result = Vec::new();
        let layouts = lines.text_layouts.borrow();

        for line in 0..rope_text.num_lines() {
            if let Some(text_layout) = layouts.get(font_size, line) {
                for line in text_layout.text.lines() {
                    let layouts = line.layout_opt().as_deref().unwrap();
                    for layout in layouts {
                        // Spacing
                        if layout.glyphs.is_empty() {
                            continue;
                        }
                        let start_idx = layout.glyphs[0].start;
                        let end_idx = layout.glyphs.last().unwrap().end;
                        // Hacky solution to include the ending space/newline since those get trimmed off
                        let line_content = line
                            .text()
                            .get(start_idx..=end_idx)
                            .unwrap_or(&line.text()[start_idx..end_idx]);
                        result.push(Cow::Owned(line_content.to_string()));
                    }
                }
            } else {
                let line_content = rope_text.line_content(line);

                let line_content = match line_content {
                    Cow::Borrowed(x) => {
                        if let Some(x) = x.strip_suffix('\n') {
                            // Cow::Borrowed(x)
                            Cow::Owned(x.to_string())
                        } else {
                            // Cow::Borrowed(x)
                            Cow::Owned(x.to_string())
                        }
                    }
                    Cow::Owned(x) => {
                        if let Some(x) = x.strip_suffix('\n') {
                            Cow::Owned(x.to_string())
                        } else {
                            Cow::Owned(x)
                        }
                    }
                };
                result.push(line_content);
            }
        }
        result
    }

    /// Utility fn to quickly create simple phantom text
    fn mph(kind: PhantomTextKind, col: usize, text: &str) -> PhantomText {
        PhantomText {
            kind,
            col,
            affinity: None,
            text: text.to_string(),
            font_size: None,
            fg: None,
            bg: None,
            under_line: None,
        }
    }

    fn ffvline_info(
        lines: &Lines,
        text_prov: impl TextLayoutProvider,
        vline: VLine,
    ) -> Option<(usize, RVLine)> {
        find_vline_init_info_forward(lines, &text_prov, (VLine(0), 0), vline)
    }

    fn fbvline_info(
        lines: &Lines,
        text_prov: impl TextLayoutProvider,
        vline: VLine,
    ) -> Option<(usize, RVLine)> {
        let last_vline = lines.last_vline(&text_prov);
        let last_rvline = lines.last_rvline(&text_prov);
        find_vline_init_info_rv_backward(lines, &text_prov, (last_vline, last_rvline), vline)
    }

    #[test]
    fn find_vline_init_info_empty() {
        // Test empty buffer
        let text = Rope::from("");
        let (text_prov, lines) = make_lines(&text, 50.0, false);

        assert_eq!(
            ffvline_info(&lines, &text_prov, VLine(0)),
            Some((0, RVLine::new(0, 0)))
        );
        assert_eq!(
            fbvline_info(&lines, &text_prov, VLine(0)),
            Some((0, RVLine::new(0, 0)))
        );
        assert_eq!(ffvline_info(&lines, &text_prov, VLine(1)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(1)), None);

        // Test empty buffer with phantom text and no wrapping
        let text = Rope::from("");
        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 0, "hello world abc")],
            },
        );
        let (text_prov, lines) = make_lines_ph(&text, 20.0, false, ph);

        assert_eq!(
            ffvline_info(&lines, &text_prov, VLine(0)),
            Some((0, RVLine::new(0, 0)))
        );
        assert_eq!(
            fbvline_info(&lines, &text_prov, VLine(0)),
            Some((0, RVLine::new(0, 0)))
        );
        assert_eq!(ffvline_info(&lines, &text_prov, VLine(1)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(1)), None);

        // Test empty buffer with phantom text and wrapping
        lines.init_all(0, ConfigId::new(0, 0), &text_prov, true);

        assert_eq!(
            ffvline_info(&lines, &text_prov, VLine(0)),
            Some((0, RVLine::new(0, 0)))
        );
        assert_eq!(
            fbvline_info(&lines, &text_prov, VLine(0)),
            Some((0, RVLine::new(0, 0)))
        );
        assert_eq!(
            ffvline_info(&lines, &text_prov, VLine(1)),
            Some((0, RVLine::new(0, 1)))
        );
        assert_eq!(
            fbvline_info(&lines, &text_prov, VLine(1)),
            Some((0, RVLine::new(0, 1)))
        );
        assert_eq!(
            ffvline_info(&lines, &text_prov, VLine(2)),
            Some((0, RVLine::new(0, 2)))
        );
        assert_eq!(
            fbvline_info(&lines, &text_prov, VLine(2)),
            Some((0, RVLine::new(0, 2)))
        );
        // Going outside bounds only ends up with None
        assert_eq!(ffvline_info(&lines, &text_prov, VLine(3)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(3)), None);
        // The affinity would shift from the front/end of the phantom line
        // TODO: test affinity of logic behind clicking past the last vline?
    }

    #[test]
    fn find_vline_init_info_unwrapping() {
        // Multiple lines with too large width for there to be any wrapping.
        let text = Rope::from("hello\nworld toast and jam\nthe end\nhi");
        let rope_text = RopeTextRef::new(&text);
        let (text_prov, mut lines) = make_lines(&text, 500.0, false);

        // Assert that with no text layouts (aka no wrapping and no phantom text) the function
        // works
        for line in 0..rope_text.num_lines() {
            let line_offset = rope_text.offset_of_line(line);

            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);

            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);
        }

        assert_eq!(ffvline_info(&lines, &text_prov, VLine(20)), None);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            ["hello", "world toast and jam", "the end", "hi"]
        );

        lines.init_all(0, ConfigId::new(0, 0), &text_prov, true);

        // Assert that even with text layouts, if it has no wrapping applied (because the width is large in this case) and no phantom text then it produces the same offsets as before.
        for line in 0..rope_text.num_lines() {
            let line_offset = rope_text.offset_of_line(line);

            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);
            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);
        }

        assert_eq!(ffvline_info(&lines, &text_prov, VLine(20)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(20)), None);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            ["hello ", "world toast and jam ", "the end ", "hi"]
        );
    }

    #[test]
    fn find_vline_init_info_phantom_unwrapping() {
        let text = Rope::from("hello\nworld toast and jam\nthe end\nhi");
        let rope_text = RopeTextRef::new(&text);

        // Multiple lines with too large width for there to be any wrapping and phantom text
        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 0, "greet world")],
            },
        );

        let (text_prov, lines) = make_lines_ph(&text, 500.0, false, ph);

        // With no text layouts, phantom text isn't initialized so it has no affect.
        for line in 0..rope_text.num_lines() {
            let line_offset = rope_text.offset_of_line(line);

            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);

            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);
        }

        lines.init_all(0, ConfigId::new(0, 0), &text_prov, true);

        // With text layouts, the phantom text is applied.
        // But with a single line of phantom text, it doesn't affect the offsets.
        for line in 0..rope_text.num_lines() {
            let line_offset = rope_text.offset_of_line(line);

            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);

            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);
        }

        // Multiple lines with too large width and a phantom text that takes up multiple lines.
        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 0, "greet\nworld"),],
            },
        );

        let (text_prov, mut lines) = make_lines_ph(&text, 500.0, false, ph);

        // With no text layouts, phantom text isn't initialized so it has no affect.
        for line in 0..rope_text.num_lines() {
            let line_offset = rope_text.offset_of_line(line);

            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);

            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);
        }

        lines.init_all(0, ConfigId::new(0, 0), &text_prov, true);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            [
                "greet",
                "worldhello ",
                "world toast and jam ",
                "the end ",
                "hi"
            ]
        );

        // With text layouts, the phantom text is applied.
        // With a phantom text that takes up multiple lines, it does not affect the offsets
        // but it does affect the valid visual lines.
        let info = ffvline_info(&lines, &text_prov, VLine(0));
        assert_eq!(info, Some((0, RVLine::new(0, 0))));
        let info = fbvline_info(&lines, &text_prov, VLine(0));
        assert_eq!(info, Some((0, RVLine::new(0, 0))));
        let info = ffvline_info(&lines, &text_prov, VLine(1));
        assert_eq!(info, Some((0, RVLine::new(0, 1))));
        let info = fbvline_info(&lines, &text_prov, VLine(1));
        assert_eq!(info, Some((0, RVLine::new(0, 1))));

        for line in 2..rope_text.num_lines() {
            let line_offset = rope_text.offset_of_line(line - 1);

            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(
                info,
                (line_offset, RVLine::new(line - 1, 0)),
                "vline {}",
                line
            );
            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(
                info,
                (line_offset, RVLine::new(line - 1, 0)),
                "vline {}",
                line
            );
        }

        // Then there's one extra vline due to the phantom text wrapping
        let line_offset = rope_text.offset_of_line(rope_text.last_line());

        let info = ffvline_info(&lines, &text_prov, VLine(rope_text.last_line() + 1));
        assert_eq!(
            info,
            Some((line_offset, RVLine::new(rope_text.last_line(), 0))),
            "line {}",
            rope_text.last_line() + 1,
        );
        let info = fbvline_info(&lines, &text_prov, VLine(rope_text.last_line() + 1));
        assert_eq!(
            info,
            Some((line_offset, RVLine::new(rope_text.last_line(), 0))),
            "line {}",
            rope_text.last_line() + 1,
        );

        // Multiple lines with too large width and a phantom text that takes up multiple lines.
        // But the phantom text is not at the start of the first line.
        let mut ph = HashMap::new();
        ph.insert(
            2, // "the end"
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 3, "greet\nworld"),],
            },
        );

        let (text_prov, mut lines) = make_lines_ph(&text, 500.0, false, ph);

        // With no text layouts, phantom text isn't initialized so it has no affect.
        for line in 0..rope_text.num_lines() {
            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();

            let line_offset = rope_text.offset_of_line(line);

            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);
        }

        lines.init_all(0, ConfigId::new(0, 0), &text_prov, true);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            [
                "hello ",
                "world toast and jam ",
                "thegreet",
                "world end ",
                "hi"
            ]
        );

        // With text layouts, the phantom text is applied.
        // With a phantom text that takes up multiple lines, it does not affect the offsets
        // but it does affect the valid visual lines.
        for line in 0..3 {
            let line_offset = rope_text.offset_of_line(line);

            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);

            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "vline {}", line);
        }

        // ' end'
        let info = ffvline_info(&lines, &text_prov, VLine(3));
        assert_eq!(info, Some((29, RVLine::new(2, 1))));
        let info = fbvline_info(&lines, &text_prov, VLine(3));
        assert_eq!(info, Some((29, RVLine::new(2, 1))));

        let info = ffvline_info(&lines, &text_prov, VLine(4));
        assert_eq!(info, Some((34, RVLine::new(3, 0))));
        let info = fbvline_info(&lines, &text_prov, VLine(4));
        assert_eq!(info, Some((34, RVLine::new(3, 0))));
    }

    #[test]
    fn find_vline_init_info_basic_wrapping() {
        // Tests with more mixes of text layout lines and uninitialized lines

        // Multiple lines with a small enough width for there to be a bunch of wrapping
        let text = Rope::from("hello\nworld toast and jam\nthe end\nhi");
        let rope_text = RopeTextRef::new(&text);
        let (text_prov, mut lines) = make_lines(&text, 30.0, false);

        // Assert that with no text layouts (aka no wrapping and no phantom text) the function
        // works
        for line in 0..rope_text.num_lines() {
            let line_offset = rope_text.offset_of_line(line);

            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "line {}", line);

            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(info, (line_offset, RVLine::new(line, 0)), "line {}", line);
        }

        assert_eq!(ffvline_info(&lines, &text_prov, VLine(20)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(20)), None);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            ["hello", "world toast and jam", "the end", "hi"]
        );

        lines.init_all(0, ConfigId::new(0, 0), &text_prov, true);

        {
            let layouts = lines.text_layouts.borrow();

            assert!(layouts.get(FONT_SIZE, 0).is_some());
            assert!(layouts.get(FONT_SIZE, 1).is_some());
            assert!(layouts.get(FONT_SIZE, 2).is_some());
            assert!(layouts.get(FONT_SIZE, 3).is_some());
            assert!(layouts.get(FONT_SIZE, 4).is_none());
        }

        // start offset, start buffer line, layout line index)
        let line_data = [
            (0, 0, 0),
            (6, 1, 0),
            (12, 1, 1),
            (18, 1, 2),
            (22, 1, 3),
            (26, 2, 0),
            (30, 2, 1),
            (34, 3, 0),
        ];
        assert_eq!(lines.last_vline(&text_prov), VLine(7));
        assert_eq!(lines.last_rvline(&text_prov), RVLine::new(3, 0));
        #[allow(clippy::needless_range_loop)]
        for line in 0..8 {
            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(
                (info.0, info.1.line, info.1.line_index),
                line_data[line],
                "vline {}",
                line
            );
            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(
                (info.0, info.1.line, info.1.line_index),
                line_data[line],
                "vline {}",
                line
            );
        }

        // Directly out of bounds
        assert_eq!(ffvline_info(&lines, &text_prov, VLine(9)), None,);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(9)), None,);

        assert_eq!(ffvline_info(&lines, &text_prov, VLine(20)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(20)), None);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            ["hello ", "world ", "toast ", "and ", "jam ", "the ", "end ", "hi"]
        );

        let vline_line_data = [0, 1, 5, 7];

        let rope = text_prov.rope_text();
        let last_start_vline =
            VLine(lines.last_vline(&text_prov).get() - lines.last_rvline(&text_prov).line_index);
        #[allow(clippy::needless_range_loop)]
        for line in 0..4 {
            let vline = VLine(vline_line_data[line]);
            assert_eq!(
                find_vline_of_line_forwards(&lines, Default::default(), line),
                Some(vline)
            );
            assert_eq!(
                find_vline_of_line_backwards(&lines, (last_start_vline, rope.last_line()), line),
                Some(vline),
                "line: {line}"
            );
        }

        let text: Rope = "aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg".into();
        let (text_prov, mut lines) = make_lines(&text, 2., true);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            ["aaaa ", "bb ", "bb ", "cc ", "cc ", "dddd ", "eeee ", "ff ", "ff ", "gggg"]
        );

        // (start offset, start buffer line, layout line index)
        let line_data = [
            (0, 0, 0),
            (5, 1, 0),
            (8, 1, 1),
            (11, 1, 2),
            (14, 2, 0),
            (17, 2, 1),
            (22, 2, 2),
            (27, 2, 3),
            (30, 3, 0),
            (33, 3, 1),
        ];
        #[allow(clippy::needless_range_loop)]
        for vline in 0..10 {
            let info = ffvline_info(&lines, &text_prov, VLine(vline)).unwrap();
            assert_eq!(
                (info.0, info.1.line, info.1.line_index),
                line_data[vline],
                "vline {}",
                vline
            );
            let info = fbvline_info(&lines, &text_prov, VLine(vline)).unwrap();
            assert_eq!(
                (info.0, info.1.line, info.1.line_index),
                line_data[vline],
                "vline {}",
                vline
            );
        }

        let vline_line_data = [0, 1, 4, 8];

        let rope = text_prov.rope_text();
        let last_start_vline =
            VLine(lines.last_vline(&text_prov).get() - lines.last_rvline(&text_prov).line_index);
        #[allow(clippy::needless_range_loop)]
        for line in 0..4 {
            let vline = VLine(vline_line_data[line]);
            assert_eq!(
                find_vline_of_line_forwards(&lines, Default::default(), line),
                Some(vline)
            );
            assert_eq!(
                find_vline_of_line_backwards(&lines, (last_start_vline, rope.last_line()), line),
                Some(vline),
                "line: {line}"
            );
        }

        // TODO: tests that have less line wrapping
    }

    #[test]
    fn find_vline_init_info_basic_wrapping_phantom() {
        // Single line Phantom text at the very start
        let text = Rope::from("hello\nworld toast and jam\nthe end\nhi");
        let rope_text = RopeTextRef::new(&text);

        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 0, "greet world")],
            },
        );

        let (text_prov, mut lines) = make_lines_ph(&text, 30.0, false, ph);

        // Assert that with no text layouts there is no change in behavior from having no phantom
        // text
        for line in 0..rope_text.num_lines() {
            let line_offset = rope_text.offset_of_line(line);

            let info = ffvline_info(&lines, &text_prov, VLine(line));
            assert_eq!(
                info,
                Some((line_offset, RVLine::new(line, 0))),
                "line {}",
                line
            );

            let info = fbvline_info(&lines, &text_prov, VLine(line));
            assert_eq!(
                info,
                Some((line_offset, RVLine::new(line, 0))),
                "line {}",
                line
            );
        }

        assert_eq!(ffvline_info(&lines, &text_prov, VLine(20)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(20)), None);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            ["hello", "world toast and jam", "the end", "hi"]
        );

        lines.init_all(0, ConfigId::new(0, 0), &text_prov, true);

        {
            let layouts = lines.text_layouts.borrow();

            assert!(layouts.get(FONT_SIZE, 0).is_some());
            assert!(layouts.get(FONT_SIZE, 1).is_some());
            assert!(layouts.get(FONT_SIZE, 2).is_some());
            assert!(layouts.get(FONT_SIZE, 3).is_some());
            assert!(layouts.get(FONT_SIZE, 4).is_none());
        }

        // start offset, start buffer line, layout line index)
        let line_data = [
            (0, 0, 0),
            (0, 0, 1),
            (6, 1, 0),
            (12, 1, 1),
            (18, 1, 2),
            (22, 1, 3),
            (26, 2, 0),
            (30, 2, 1),
            (34, 3, 0),
        ];

        #[allow(clippy::needless_range_loop)]
        for line in 0..9 {
            let info = ffvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(
                (info.0, info.1.line, info.1.line_index),
                line_data[line],
                "vline {}",
                line
            );

            let info = fbvline_info(&lines, &text_prov, VLine(line)).unwrap();
            assert_eq!(
                (info.0, info.1.line, info.1.line_index),
                line_data[line],
                "vline {}",
                line
            );
        }

        // Directly out of bounds
        assert_eq!(ffvline_info(&lines, &text_prov, VLine(9)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(9)), None);

        assert_eq!(ffvline_info(&lines, &text_prov, VLine(20)), None);
        assert_eq!(fbvline_info(&lines, &text_prov, VLine(20)), None);

        // TODO: Currently the way we join phantom text and how cosmic wraps lines,
        // the phantom text will be joined with whatever the word next to it is - if there is no
        // spaces. It might be desirable to always separate them to let it wrap independently.
        // An easy way to do this is to always include a space, and then manually cut the glyph
        // margin in the text layout.
        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            [
                "greet ",
                "worldhello ",
                "world ",
                "toast ",
                "and ",
                "jam ",
                "the ",
                "end ",
                "hi"
            ]
        );

        // TODO: multiline phantom text in the middle
        // TODO: test at the end
    }

    #[test]
    fn num_vlines() {
        let text: Rope = "aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg".into();
        let (text_prov, lines) = make_lines(&text, 2., true);
        assert_eq!(lines.num_vlines(&text_prov), 10);

        // With phantom text
        let text: Rope = "aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg".into();
        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 0, "greet\nworld")],
            },
        );

        let (text_prov, lines) = make_lines_ph(&text, 2., true, ph);

        // Only one increase because the second line of the phantom text is directly attached to
        // the word at the start of the next line.
        assert_eq!(lines.num_vlines(&text_prov), 11);
    }

    #[test]
    fn offset_to_line() {
        let text = "a b c d ".into();
        let (text_prov, lines) = make_lines(&text, 1., true);
        assert_eq!(lines.num_vlines(&text_prov), 4);

        let vlines = [0, 0, 1, 1, 2, 2, 3, 3];
        for (i, v) in vlines.iter().enumerate() {
            assert_eq!(
                lines.vline_of_offset(&text_prov, i, CursorAffinity::Forward),
                VLine(*v),
                "offset: {i}"
            );
        }

        assert_eq!(lines.offset_of_vline(&text_prov, VLine(0)), 0);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(1)), 2);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(2)), 4);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(3)), 6);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(10)), 8);

        for offset in 0..text.len() {
            let line = lines.vline_of_offset(&text_prov, offset, CursorAffinity::Forward);
            let line_offset = lines.offset_of_vline(&text_prov, line);
            assert!(
                line_offset <= offset,
                "{} <= {} L{:?} O{}",
                line_offset,
                offset,
                line,
                offset
            );
        }

        let text = "blah\n\n\nhi\na b c d e".into();
        let (text_prov, lines) = make_lines(&text, 12.0 * 3.0, true);
        let vlines = [0, 0, 0, 0, 0];
        for (i, v) in vlines.iter().enumerate() {
            assert_eq!(
                lines.vline_of_offset(&text_prov, i, CursorAffinity::Forward),
                VLine(*v),
                "offset: {i}"
            );
        }
        assert_eq!(
            lines
                .vline_of_offset(&text_prov, 4, CursorAffinity::Backward)
                .get(),
            0
        );
        // Test that cursor affinity has no effect for hard line breaks
        assert_eq!(
            lines
                .vline_of_offset(&text_prov, 5, CursorAffinity::Forward)
                .get(),
            1
        );
        assert_eq!(
            lines
                .vline_of_offset(&text_prov, 5, CursorAffinity::Backward)
                .get(),
            1
        );
        // starts at 'd'. Tests that cursor affinity works for soft line breaks
        assert_eq!(
            lines
                .vline_of_offset(&text_prov, 16, CursorAffinity::Forward)
                .get(),
            5
        );
        assert_eq!(
            lines
                .vline_of_offset(&text_prov, 16, CursorAffinity::Backward)
                .get(),
            4
        );

        assert_eq!(
            lines.vline_of_offset(&text_prov, 20, CursorAffinity::Forward),
            lines.last_vline(&text_prov)
        );

        let text = "a\nb\nc\n".into();
        let (text_prov, lines) = make_lines(&text, 1., true);
        assert_eq!(lines.num_vlines(&text_prov), 4);

        // let vlines = [(0, 0), (0, 0), (1, 1), (1, 1), (2, 2), (2, 2), (3, 3)];
        let vlines = [0, 0, 1, 1, 2, 2, 3, 3];
        for (i, v) in vlines.iter().enumerate() {
            assert_eq!(
                lines.vline_of_offset(&text_prov, i, CursorAffinity::Forward),
                VLine(*v),
                "offset: {i}"
            );
            assert_eq!(
                lines.vline_of_offset(&text_prov, i, CursorAffinity::Backward),
                VLine(*v),
                "offset: {i}"
            );
        }

        let text =
            Rope::from("asdf\nposition: Some(EditorPosition::Offset(self.offset))\nasdf\nasdf");
        let (text_prov, mut lines) = make_lines(&text, 1., true);
        println!("Breaks: {:?}", render_breaks(&text, &mut lines, FONT_SIZE));

        let rvline = lines.rvline_of_offset(&text_prov, 3, CursorAffinity::Backward);
        assert_eq!(rvline, RVLine::new(0, 0));
        let rvline_info = lines
            .iter_rvlines(&text_prov, false, rvline)
            .next()
            .unwrap();
        assert_eq!(rvline_info.rvline, rvline);
        let offset = lines.offset_of_rvline(&text_prov, rvline);
        assert_eq!(offset, 0);
        assert_eq!(
            lines.vline_of_offset(&text_prov, offset, CursorAffinity::Backward),
            VLine(0)
        );
        assert_eq!(lines.vline_of_rvline(&text_prov, rvline), VLine(0));

        let rvline = lines.rvline_of_offset(&text_prov, 7, CursorAffinity::Backward);
        assert_eq!(rvline, RVLine::new(1, 0));
        let rvline_info = lines
            .iter_rvlines(&text_prov, false, rvline)
            .next()
            .unwrap();
        assert_eq!(rvline_info.rvline, rvline);
        let offset = lines.offset_of_rvline(&text_prov, rvline);
        assert_eq!(offset, 5);
        assert_eq!(
            lines.vline_of_offset(&text_prov, offset, CursorAffinity::Backward),
            VLine(1)
        );
        assert_eq!(lines.vline_of_rvline(&text_prov, rvline), VLine(1));

        let rvline = lines.rvline_of_offset(&text_prov, 17, CursorAffinity::Backward);
        assert_eq!(rvline, RVLine::new(1, 1));
        let rvline_info = lines
            .iter_rvlines(&text_prov, false, rvline)
            .next()
            .unwrap();
        assert_eq!(rvline_info.rvline, rvline);
        let offset = lines.offset_of_rvline(&text_prov, rvline);
        assert_eq!(offset, 15);
        assert_eq!(
            lines.vline_of_offset(&text_prov, offset, CursorAffinity::Backward),
            VLine(1)
        );
        assert_eq!(
            lines.vline_of_offset(&text_prov, offset, CursorAffinity::Forward),
            VLine(2)
        );
        assert_eq!(lines.vline_of_rvline(&text_prov, rvline), VLine(2));
    }

    #[test]
    fn offset_to_line_phantom() {
        let text = "a b c d ".into();
        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 1, "hi")],
            },
        );

        let (text_prov, mut lines) = make_lines_ph(&text, 1., true, ph);

        // The 'hi' is joined with the 'a' so it's not wrapped to a separate line
        assert_eq!(lines.num_vlines(&text_prov), 4);

        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            ["ahi ", "b ", "c ", "d "]
        );

        let vlines = [0, 0, 1, 1, 2, 2, 3, 3];
        // Unchanged. The phantom text has no effect in the position. It doesn't shift a line with
        // the affinity due to its position and it isn't multiline.
        for (i, v) in vlines.iter().enumerate() {
            assert_eq!(
                lines.vline_of_offset(&text_prov, i, CursorAffinity::Forward),
                VLine(*v),
                "offset: {i}"
            );
        }

        assert_eq!(lines.offset_of_vline(&text_prov, VLine(0)), 0);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(1)), 2);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(2)), 4);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(3)), 6);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(10)), 8);

        for offset in 0..text.len() {
            let line = lines.vline_of_offset(&text_prov, offset, CursorAffinity::Forward);
            let line_offset = lines.offset_of_vline(&text_prov, line);
            assert!(
                line_offset <= offset,
                "{} <= {} L{:?} O{}",
                line_offset,
                offset,
                line,
                offset
            );
        }

        // Same as above but with a slightly shifted to make the affinity change the resulting vline
        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 2, "hi")],
            },
        );

        let (text_prov, mut lines) = make_lines_ph(&text, 1., true, ph);

        // The 'hi' is joined with the 'a' so it's not wrapped to a separate line
        assert_eq!(lines.num_vlines(&text_prov), 4);

        // TODO: Should this really be forward rendered?
        assert_eq!(
            render_breaks(&text, &mut lines, FONT_SIZE),
            ["a ", "hib ", "c ", "d "]
        );

        for (i, v) in vlines.iter().enumerate() {
            assert_eq!(
                lines.vline_of_offset(&text_prov, i, CursorAffinity::Forward),
                VLine(*v),
                "offset: {i}"
            );
        }
        assert_eq!(
            lines.vline_of_offset(&text_prov, 2, CursorAffinity::Backward),
            VLine(0)
        );

        assert_eq!(lines.offset_of_vline(&text_prov, VLine(0)), 0);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(1)), 2);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(2)), 4);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(3)), 6);
        assert_eq!(lines.offset_of_vline(&text_prov, VLine(10)), 8);

        for offset in 0..text.len() {
            let line = lines.vline_of_offset(&text_prov, offset, CursorAffinity::Forward);
            let line_offset = lines.offset_of_vline(&text_prov, line);
            assert!(
                line_offset <= offset,
                "{} <= {} L{:?} O{}",
                line_offset,
                offset,
                line,
                offset
            );
        }
    }

    #[test]
    fn iter_lines() {
        let text: Rope = "aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg".into();
        let (text_prov, lines) = make_lines(&text, 2., true);
        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(0))
            .take(2)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec!["aaaa", "bb "]);

        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(1))
            .take(2)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec!["bb ", "bb "]);

        let v = lines.get_init_text_layout(0, ConfigId::new(0, 0), &text_prov, 2, true);
        let v = v.layout_cols(&text_prov, 2).collect::<Vec<_>>();
        assert_eq!(v, [(0, 3), (3, 8), (8, 13), (13, 15)]);
        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(3))
            .take(3)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec!["cc", "cc ", "dddd "]);

        let mut r: Vec<_> = lines.iter_vlines(&text_prov, false, VLine(0)).collect();
        r.reverse();
        let r1: Vec<_> = lines
            .iter_vlines(&text_prov, true, lines.last_vline(&text_prov))
            .collect();
        assert_eq!(r, r1);

        let rel1: Vec<_> = lines
            .iter_rvlines(&text_prov, false, RVLine::new(0, 0))
            .map(|i| i.rvline)
            .collect();
        r.reverse(); // revert back
        assert!(r.iter().map(|i| i.rvline).eq(rel1));

        // Empty initialized
        let text: Rope = "".into();
        let (text_prov, lines) = make_lines(&text, 2., true);
        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(0))
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec![""]);
        // Empty initialized - Out of bounds
        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(1))
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, Vec::<&str>::new());
        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(2))
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, Vec::<&str>::new());

        let mut r: Vec<_> = lines.iter_vlines(&text_prov, false, VLine(0)).collect();
        r.reverse();
        let r1: Vec<_> = lines
            .iter_vlines(&text_prov, true, lines.last_vline(&text_prov))
            .collect();
        assert_eq!(r, r1);

        let rel1: Vec<_> = lines
            .iter_rvlines(&text_prov, false, RVLine::new(0, 0))
            .map(|i| i.rvline)
            .collect();
        r.reverse(); // revert back
        assert!(r.iter().map(|i| i.rvline).eq(rel1));

        // Empty uninitialized
        let text: Rope = "".into();
        let (text_prov, lines) = make_lines(&text, 2., false);
        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(0))
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec![""]);
        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(1))
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, Vec::<&str>::new());
        let r: Vec<_> = lines
            .iter_vlines(&text_prov, false, VLine(2))
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, Vec::<&str>::new());

        let mut r: Vec<_> = lines.iter_vlines(&text_prov, false, VLine(0)).collect();
        r.reverse();
        let r1: Vec<_> = lines
            .iter_vlines(&text_prov, true, lines.last_vline(&text_prov))
            .collect();
        assert_eq!(r, r1);

        let rel1: Vec<_> = lines
            .iter_rvlines(&text_prov, false, RVLine::new(0, 0))
            .map(|i| i.rvline)
            .collect();
        r.reverse(); // revert back
        assert!(r.iter().map(|i| i.rvline).eq(rel1));

        // TODO: clean up the above tests with some helper function. Very noisy at the moment.
        // TODO: phantom text iter lines tests?
    }

    // TODO(minor): Deduplicate the test code between this and iter_lines
    // We're just testing whether it has equivalent behavior to iter lines (when lines are
    // initialized)
    #[test]
    fn init_iter_vlines() {
        let text: Rope = "aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg".into();
        let (text_prov, lines) = make_lines(&text, 2., false);
        let r: Vec<_> = lines
            .iter_vlines_init(&text_prov, 0, ConfigId::new(0, 0), VLine(0), true)
            .take(2)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec!["aaaa", "bb "]);

        let r: Vec<_> = lines
            .iter_vlines_init(&text_prov, 0, ConfigId::new(0, 0), VLine(1), true)
            .take(2)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec!["bb ", "bb "]);

        let r: Vec<_> = lines
            .iter_vlines_init(&text_prov, 0, ConfigId::new(0, 0), VLine(3), true)
            .take(3)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec!["cc", "cc ", "dddd "]);

        // Empty initialized
        let text: Rope = "".into();
        let (text_prov, lines) = make_lines(&text, 2., false);
        let r: Vec<_> = lines
            .iter_vlines_init(&text_prov, 0, ConfigId::new(0, 0), VLine(0), true)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, vec![""]);
        let r: Vec<_> = lines
            .iter_vlines_init(&text_prov, 0, ConfigId::new(0, 0), VLine(1), true)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, Vec::<&str>::new());
        let r: Vec<_> = lines
            .iter_vlines_init(&text_prov, 0, ConfigId::new(0, 0), VLine(2), true)
            .map(|l| text.slice_to_cow(l.interval))
            .collect();
        assert_eq!(r, Vec::<&str>::new());
    }

    #[test]
    fn line_numbers() {
        let text: Rope = "aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg".into();
        let (text_prov, lines) = make_lines(&text, 12.0 * 2.0, true);
        let get_nums = |start_vline: usize| {
            lines
                .iter_vlines(&text_prov, false, VLine(start_vline))
                .map(|l| {
                    (
                        l.rvline.line,
                        l.vline.get(),
                        l.is_first(),
                        text.slice_to_cow(l.interval),
                    )
                })
                .collect::<Vec<_>>()
        };
        // (line, vline, is_first, text)
        let x = vec![
            (0, 0, true, "aaaa".into()),
            (1, 1, true, "bb ".into()),
            (1, 2, false, "bb ".into()),
            (1, 3, false, "cc".into()),
            (2, 4, true, "cc ".into()),
            (2, 5, false, "dddd ".into()),
            (2, 6, false, "eeee ".into()),
            (2, 7, false, "ff".into()),
            (3, 8, true, "ff ".into()),
            (3, 9, false, "gggg".into()),
        ];

        // This ensures that there's no inconsistencies between starting at a specific index
        // vs starting at zero and iterating to that index.
        for i in 0..x.len() {
            let nums = get_nums(i);
            println!("i: {i}, #nums: {}, #&x[i..]: {}", nums.len(), x[i..].len());
            assert_eq!(nums, &x[i..], "failed at #{i}");
        }

        // TODO: test this without any wrapping
    }

    #[test]
    fn last_col() {
        let text: Rope = Rope::from("conf = Config::default();");
        let (text_prov, lines) = make_lines(&text, 24.0 * 2.0, true);

        let mut iter = lines.iter_rvlines(&text_prov, false, RVLine::default());

        // "conf = "
        let v = iter.next().unwrap();
        assert_eq!(v.last_col(&text_prov, false), 6);
        assert_eq!(v.last_col(&text_prov, true), 7);

        // "Config::default();"
        let v = iter.next().unwrap();
        assert_eq!(v.last_col(&text_prov, false), 24);
        assert_eq!(v.last_col(&text_prov, true), 25);

        let text = Rope::from("blah\nthing");
        let (text_prov, lines) = make_lines(&text, 1000., false);
        let mut iter = lines.iter_rvlines(&text_prov, false, RVLine::default());

        let rtext = RopeTextVal::new(text.clone());

        // "blah"
        let v = iter.next().unwrap();
        assert_eq!(v.last_col(&text_prov, false), 3);
        assert_eq!(v.last_col(&text_prov, true), 4);
        assert_eq!(rtext.offset_of_line_col(0, 3), 3);
        assert_eq!(rtext.offset_of_line_col(0, 4), 4);

        // "text"
        let v = iter.next().unwrap();
        assert_eq!(v.last_col(&text_prov, false), 4);
        assert_eq!(v.last_col(&text_prov, true), 5);

        let text = Rope::from("blah\r\nthing");
        let (text_prov, lines) = make_lines(&text, 1000., false);
        let mut iter = lines.iter_rvlines(&text_prov, false, RVLine::default());

        let rtext = RopeTextVal::new(text.clone());

        // "blah"
        let v = iter.next().unwrap();
        assert_eq!(v.last_col(&text_prov, false), 3);
        assert_eq!(v.last_col(&text_prov, true), 4);
        assert_eq!(rtext.offset_of_line_col(0, 3), 3);
        assert_eq!(rtext.offset_of_line_col(0, 4), 4);

        // "text"
        let v = iter.next().unwrap();
        assert_eq!(v.last_col(&text_prov, false), 4);
        assert_eq!(v.last_col(&text_prov, true), 5);
        assert_eq!(rtext.offset_of_line_col(0, 4), 4);
        assert_eq!(rtext.offset_of_line_col(0, 5), 4);
    }

    #[test]
    fn layout_cols() {
        let text = Rope::from("aaaa\nbb bb cc\ndd");
        let mut layout = TextLayout::new();
        layout.set_text("aaaa", AttrsList::new(Attrs::new()));
        let layout = TextLayoutLine {
            extra_style: Vec::new(),
            text: layout,
            whitespaces: None,
            indent: 0.,
            phantom_text: PhantomTextLine::default(),
        };

        let (text_prov, _) = make_lines(&text, 10000., false);
        assert_eq!(
            layout.layout_cols(&text_prov, 0).collect::<Vec<_>>(),
            vec![(0, 4)]
        );
        let (text_prov, _) = make_lines(&text, 10000., true);
        assert_eq!(
            layout.layout_cols(&text_prov, 0).collect::<Vec<_>>(),
            vec![(0, 4)]
        );

        let text = Rope::from("aaaa\r\nbb bb cc\r\ndd");
        let mut layout = TextLayout::new();
        layout.set_text("aaaa", AttrsList::new(Attrs::new()));
        let layout = TextLayoutLine {
            extra_style: Vec::new(),
            text: layout,
            whitespaces: None,
            indent: 0.,
            phantom_text: PhantomTextLine::default(),
        };

        let (text_prov, _) = make_lines(&text, 10000., false);
        assert_eq!(
            layout.layout_cols(&text_prov, 0).collect::<Vec<_>>(),
            vec![(0, 4)]
        );
        let (text_prov, _) = make_lines(&text, 10000., true);
        assert_eq!(
            layout.layout_cols(&text_prov, 0).collect::<Vec<_>>(),
            vec![(0, 4)]
        );
    }

    #[test]
    fn test_end_of_rvline() {
        fn eor(lines: &Lines, text_prov: &impl TextLayoutProvider, rvline: RVLine) -> usize {
            let layouts = lines.text_layouts.borrow();
            end_of_rvline(&layouts, text_prov, 12, rvline)
        }

        fn check_equiv(text: &Rope, expected: usize, from: &str) {
            let (text_prov, lines) = make_lines(text, 10000., false);
            let end1 = eor(&lines, &text_prov, RVLine::new(0, 0));

            let (text_prov, lines) = make_lines(text, 10000., true);
            assert_eq!(
                eor(&lines, &text_prov, RVLine::new(0, 0)),
                end1,
                "non-init end_of_rvline not equivalent to init ({from})"
            );
            assert_eq!(end1, expected, "end_of_rvline not equivalent ({from})");
        }

        let text = Rope::from("");
        check_equiv(&text, 0, "empty");

        let text = Rope::from("aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg");
        check_equiv(&text, 4, "simple multiline (LF)");

        let text = Rope::from("aaaa\r\nbb bb cc\r\ncc dddd eeee ff\r\nff gggg");
        check_equiv(&text, 4, "simple multiline (CRLF)");

        let text = Rope::from("a b c d ");
        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![mph(PhantomTextKind::Completion, 1, "hi")],
            },
        );

        let (text_prov, lines) = make_lines_ph(&text, 1., true, ph);

        assert_eq!(eor(&lines, &text_prov, RVLine::new(0, 0)), 2);

        assert_eq!(eor(&lines, &text_prov, RVLine::new(0, 1)), 4);

        let text = Rope::from("        let j = test_test\nlet blah = 5;");

        let mut ph = HashMap::new();
        ph.insert(
            0,
            PhantomTextLine {
                text: smallvec![
                    mph(
                        PhantomTextKind::Diagnostic,
                        26,
                        "    Syntax Error: `let` expressions are not supported here"
                    ),
                    mph(
                        PhantomTextKind::Diagnostic,
                        26,
                        "    Syntax Error: expected SEMICOLON"
                    ),
                ],
            },
        );

        let (text_prov, lines) = make_lines_ph(&text, 250., true, ph);

        assert_eq!(eor(&lines, &text_prov, RVLine::new(0, 0)), 25);
        assert_eq!(eor(&lines, &text_prov, RVLine::new(0, 1)), 25);
        assert_eq!(eor(&lines, &text_prov, RVLine::new(0, 2)), 25);
        assert_eq!(eor(&lines, &text_prov, RVLine::new(0, 3)), 25);
        assert_eq!(eor(&lines, &text_prov, RVLine::new(1, 0)), 39);
    }

    #[test]
    fn equivalence() {
        // Extra tests that the visual lines you get when initting are equivalent to the ones you
        // get if you don't init
        // TODO: tests for them being equivalent even with wrapping

        fn check_equiv(text: &Rope, from: &str) {
            let (text_prov, lines) = make_lines(text, 10000., false);
            let iter = lines.iter_rvlines(&text_prov, false, RVLine::default());

            let (text_prov, lines) = make_lines(text, 01000., true);
            let iter2 = lines.iter_rvlines(&text_prov, false, RVLine::default());

            // Just assume same length
            for (i, v) in iter.zip(iter2) {
                assert_eq!(
                    i, v,
                    "Line {} is not equivalent when initting ({from})",
                    i.rvline.line
                );
            }
        }

        check_equiv(&Rope::from(""), "empty");
        check_equiv(&Rope::from("a"), "a");
        check_equiv(
            &Rope::from("aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg"),
            "simple multiline (LF)",
        );
        check_equiv(
            &Rope::from("aaaa\r\nbb bb cc\r\ncc dddd eeee ff\r\nff gggg"),
            "simple multiline (CRLF)",
        );
    }
}