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
//! Split pane layout and buffer rendering
use std::collections::BTreeMap;
use crate::app::types::ViewLineMapping;
use crate::app::BufferMetadata;
use crate::model::buffer::Buffer;
use crate::model::cursor::SelectionMode;
use crate::model::event::{BufferId, EventLog, SplitDirection};
use crate::primitives::ansi::AnsiParser;
use crate::primitives::ansi_background::AnsiBackground;
use crate::services::plugins::api::ViewTransformPayload;
use crate::state::{EditorState, ViewMode};
use crate::view::split::SplitManager;
use crate::view::ui::tabs::TabsRenderer;
use crate::view::ui::view_pipeline::{
should_show_line_number, LineStart, ViewLine, ViewLineIterator,
};
use crate::view::virtual_text::VirtualTextPosition;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use ratatui::Frame;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
fn push_span_with_map(
spans: &mut Vec<Span<'static>>,
map: &mut Vec<Option<usize>>,
text: String,
style: Style,
source: Option<usize>,
) {
if text.is_empty() {
return;
}
for _ in text.chars() {
map.push(source);
}
spans.push(Span::styled(text, style));
}
/// Processed view data containing display lines from the view pipeline
struct ViewData {
/// Display lines with all token information preserved
lines: Vec<ViewLine>,
}
struct ViewAnchor {
start_line_idx: usize,
start_line_skip: usize,
}
struct ComposeLayout {
render_area: Rect,
left_pad: u16,
right_pad: u16,
}
struct SelectionContext {
ranges: Vec<Range<usize>>,
block_rects: Vec<(usize, usize, usize, usize)>,
cursor_positions: Vec<usize>,
primary_cursor_position: usize,
}
struct DecorationContext {
highlight_spans: Vec<crate::primitives::highlighter::HighlightSpan>,
semantic_spans: Vec<crate::primitives::highlighter::HighlightSpan>,
viewport_overlays: Vec<(crate::view::overlay::Overlay, Range<usize>)>,
virtual_text_lookup: HashMap<usize, Vec<crate::view::virtual_text::VirtualText>>,
diagnostic_lines: HashSet<usize>,
/// Line indicators indexed by line number (highest priority indicator per line)
line_indicators: BTreeMap<usize, crate::view::margin::LineIndicator>,
}
struct LineRenderOutput {
lines: Vec<Line<'static>>,
cursor: Option<(u16, u16)>,
last_line_end: Option<LastLineEnd>,
content_lines_rendered: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct LastLineEnd {
pos: (u16, u16),
terminated_with_newline: bool,
}
struct SplitLayout {
tabs_rect: Rect,
content_rect: Rect,
scrollbar_rect: Rect,
}
struct ViewPreferences {
view_mode: ViewMode,
compose_width: Option<u16>,
compose_column_guides: Option<Vec<u16>>,
view_transform: Option<ViewTransformPayload>,
}
struct LineRenderInput<'a> {
state: &'a EditorState,
theme: &'a crate::view::theme::Theme,
/// Display lines from the view pipeline (each line has its own mappings, styles, etc.)
view_lines: &'a [ViewLine],
view_anchor: ViewAnchor,
render_area: Rect,
gutter_width: usize,
selection: &'a SelectionContext,
decorations: &'a DecorationContext,
starting_line_num: usize,
visible_line_count: usize,
lsp_waiting: bool,
is_active: bool,
line_wrap: bool,
estimated_lines: usize,
/// Left column offset for horizontal scrolling
left_column: usize,
}
/// Context for computing the style of a single character
struct CharStyleContext<'a> {
byte_pos: Option<usize>,
token_style: Option<&'a crate::services::plugins::api::ViewTokenStyle>,
ansi_style: Style,
is_cursor: bool,
is_selected: bool,
theme: &'a crate::view::theme::Theme,
highlight_spans: &'a [crate::primitives::highlighter::HighlightSpan],
semantic_spans: &'a [crate::primitives::highlighter::HighlightSpan],
viewport_overlays: &'a [(crate::view::overlay::Overlay, Range<usize>)],
primary_cursor_position: usize,
is_active: bool,
}
/// Output from compute_char_style
struct CharStyleOutput {
style: Style,
is_secondary_cursor: bool,
}
/// Context for rendering the left margin (line numbers, indicators, separator)
struct LeftMarginContext<'a> {
state: &'a EditorState,
theme: &'a crate::view::theme::Theme,
is_continuation: bool,
current_source_line_num: usize,
estimated_lines: usize,
diagnostic_lines: &'a HashSet<usize>,
/// Pre-computed line indicators (line_num -> indicator)
line_indicators: &'a BTreeMap<usize, crate::view::margin::LineIndicator>,
}
/// Render the left margin (indicators + line numbers + separator) to line_spans
fn render_left_margin(
ctx: &LeftMarginContext,
line_spans: &mut Vec<Span<'static>>,
line_view_map: &mut Vec<Option<usize>>,
) {
if !ctx.state.margins.left_config.enabled {
return;
}
// For continuation lines, don't show any indicators
if ctx.is_continuation {
push_span_with_map(
line_spans,
line_view_map,
" ".to_string(),
Style::default(),
None,
);
} else if ctx.diagnostic_lines.contains(&ctx.current_source_line_num) {
// Diagnostic indicators have highest priority
push_span_with_map(
line_spans,
line_view_map,
"●".to_string(),
Style::default().fg(ratatui::style::Color::Red),
None,
);
} else if let Some(indicator) = ctx.line_indicators.get(&ctx.current_source_line_num) {
// Show line indicator (git gutter, breakpoints, etc.)
push_span_with_map(
line_spans,
line_view_map,
indicator.symbol.clone(),
Style::default().fg(indicator.color),
None,
);
} else {
// Show space (no indicator)
push_span_with_map(
line_spans,
line_view_map,
" ".to_string(),
Style::default(),
None,
);
}
// Render line number (right-aligned) or blank for continuations
if ctx.is_continuation {
// For wrapped continuation lines, render blank space
let blank = " ".repeat(ctx.state.margins.left_config.width);
push_span_with_map(
line_spans,
line_view_map,
blank,
Style::default().fg(ctx.theme.line_number_fg),
None,
);
} else {
let margin_content = ctx.state.margins.render_line(
ctx.current_source_line_num,
crate::view::margin::MarginPosition::Left,
ctx.estimated_lines,
);
let (rendered_text, style_opt) = margin_content.render(ctx.state.margins.left_config.width);
// Use custom style if provided, otherwise use default theme color
let margin_style =
style_opt.unwrap_or_else(|| Style::default().fg(ctx.theme.line_number_fg));
push_span_with_map(line_spans, line_view_map, rendered_text, margin_style, None);
}
// Render separator
if ctx.state.margins.left_config.show_separator {
let separator_style = Style::default().fg(ctx.theme.line_number_fg);
push_span_with_map(
line_spans,
line_view_map,
ctx.state.margins.left_config.separator.clone(),
separator_style,
None,
);
}
}
/// Compute the style for a character by layering: token -> ANSI -> syntax -> semantic -> overlays -> selection -> cursor
fn compute_char_style(ctx: &CharStyleContext) -> CharStyleOutput {
use crate::view::overlay::OverlayFace;
// Find highlight color for this byte position
let highlight_color = ctx.byte_pos.and_then(|bp| {
ctx.highlight_spans
.iter()
.find(|span| span.range.contains(&bp))
.map(|span| span.color)
});
// Find overlays for this byte position
let overlays: Vec<&crate::view::overlay::Overlay> = if let Some(bp) = ctx.byte_pos {
ctx.viewport_overlays
.iter()
.filter(|(_, range)| range.contains(&bp))
.map(|(overlay, _)| overlay)
.collect()
} else {
Vec::new()
};
// Start with token style if present (for injected content like annotation headers)
// Otherwise use ANSI/syntax/theme default
let mut style = if let Some(ts) = ctx.token_style {
let mut s = Style::default();
if let Some((r, g, b)) = ts.fg {
s = s.fg(ratatui::style::Color::Rgb(r, g, b));
} else {
s = s.fg(ctx.theme.editor_fg);
}
if let Some((r, g, b)) = ts.bg {
s = s.bg(ratatui::style::Color::Rgb(r, g, b));
}
if ts.bold {
s = s.add_modifier(Modifier::BOLD);
}
if ts.italic {
s = s.add_modifier(Modifier::ITALIC);
}
s
} else if ctx.ansi_style.fg.is_some()
|| ctx.ansi_style.bg.is_some()
|| !ctx.ansi_style.add_modifier.is_empty()
{
// Apply ANSI styling from escape codes
let mut s = Style::default();
if let Some(fg) = ctx.ansi_style.fg {
s = s.fg(fg);
} else {
s = s.fg(ctx.theme.editor_fg);
}
if let Some(bg) = ctx.ansi_style.bg {
s = s.bg(bg);
}
s = s.add_modifier(ctx.ansi_style.add_modifier);
s
} else if let Some(color) = highlight_color {
// Apply syntax highlighting
Style::default().fg(color)
} else {
// Default color from theme
Style::default().fg(ctx.theme.editor_fg)
};
// If we have ANSI style but also syntax highlighting, syntax takes precedence for color
// (unless ANSI has explicit color which we already applied above)
if highlight_color.is_some()
&& ctx.ansi_style.fg.is_none()
&& (ctx.ansi_style.bg.is_some() || !ctx.ansi_style.add_modifier.is_empty())
{
style = style.fg(highlight_color.unwrap());
}
// Apply semantic highlighting
if let Some(bp) = ctx.byte_pos {
if let Some(semantic_span) = ctx
.semantic_spans
.iter()
.find(|span| span.range.contains(&bp))
{
style = style.bg(semantic_span.color);
}
}
// Apply overlay styles
for overlay in &overlays {
match &overlay.face {
OverlayFace::Underline {
color,
style: _underline_style,
} => {
style = style.add_modifier(Modifier::UNDERLINED).fg(*color);
}
OverlayFace::Background { color } => {
style = style.bg(*color);
}
OverlayFace::Foreground { color } => {
style = style.fg(*color);
}
OverlayFace::Style {
style: overlay_style,
} => {
style = style.patch(*overlay_style);
}
}
}
// Apply selection highlighting
if ctx.is_selected {
style = Style::default()
.fg(ctx.theme.editor_fg)
.bg(ctx.theme.selection_bg);
}
// Apply cursor styling - make secondary cursors visible with reversed colors
// Don't apply REVERSED to primary cursor to preserve terminal cursor visibility
// For inactive splits, ALL cursors use a less pronounced color (no hardware cursor)
let is_secondary_cursor = ctx.is_cursor && ctx.byte_pos != Some(ctx.primary_cursor_position);
if ctx.is_active {
if is_secondary_cursor {
style = style.add_modifier(Modifier::REVERSED);
}
} else if ctx.is_cursor {
style = style.fg(ctx.theme.editor_fg).bg(ctx.theme.inactive_cursor);
}
CharStyleOutput {
style,
is_secondary_cursor,
}
}
/// Renders split panes and their content
pub struct SplitRenderer;
impl SplitRenderer {
/// Render the main content area with all splits
///
/// # Arguments
/// * `frame` - The ratatui frame to render to
/// * `area` - The rectangular area to render in
/// * `split_manager` - The split manager
/// * `buffers` - All open buffers
/// * `buffer_metadata` - Metadata for buffers (contains display names)
/// * `event_logs` - Event logs for each buffer
/// * `theme` - The active theme for colors
/// * `lsp_waiting` - Whether LSP is waiting
/// * `large_file_threshold_bytes` - Threshold for using constant scrollbar thumb size
/// * `line_wrap` - Whether line wrapping is enabled
/// * `estimated_line_length` - Estimated average line length for large file line estimation
/// * `hide_cursor` - Whether to hide the hardware cursor (e.g., when menu is open)
///
/// # Returns
/// * Vec of (split_id, buffer_id, content_rect, scrollbar_rect, thumb_start, thumb_end) for mouse handling
pub fn render_content(
frame: &mut Frame,
area: Rect,
split_manager: &SplitManager,
buffers: &mut HashMap<BufferId, EditorState>,
buffer_metadata: &HashMap<BufferId, BufferMetadata>,
event_logs: &mut HashMap<BufferId, EventLog>,
theme: &crate::view::theme::Theme,
ansi_background: Option<&AnsiBackground>,
background_fade: f32,
lsp_waiting: bool,
large_file_threshold_bytes: u64,
_line_wrap: bool,
estimated_line_length: usize,
highlight_context_bytes: usize,
mut split_view_states: Option<
&mut HashMap<crate::model::event::SplitId, crate::view::split::SplitViewState>,
>,
hide_cursor: bool,
hovered_tab: Option<(BufferId, crate::model::event::SplitId, bool)>, // (buffer_id, split_id, is_close_button)
hovered_close_split: Option<crate::model::event::SplitId>,
hovered_maximize_split: Option<crate::model::event::SplitId>,
is_maximized: bool,
) -> (
Vec<(
crate::model::event::SplitId,
BufferId,
Rect,
Rect,
usize,
usize,
)>,
Vec<(crate::model::event::SplitId, BufferId, u16, u16, u16, u16)>,
Vec<(crate::model::event::SplitId, u16, u16, u16)>, // close split button areas
Vec<(crate::model::event::SplitId, u16, u16, u16)>, // maximize split button areas
HashMap<crate::model::event::SplitId, Vec<ViewLineMapping>>, // view line mappings for mouse clicks
) {
let _span = tracing::trace_span!("render_content").entered();
// Get all visible splits with their areas
let visible_buffers = split_manager.get_visible_buffers(area);
let active_split_id = split_manager.active_split();
let has_multiple_splits = visible_buffers.len() > 1;
// Collect areas for mouse handling
let mut split_areas = Vec::new();
let mut all_tab_areas = Vec::new();
let mut close_split_areas = Vec::new();
let mut maximize_split_areas = Vec::new();
let mut view_line_mappings: HashMap<crate::model::event::SplitId, Vec<ViewLineMapping>> =
HashMap::new();
// Render each split
for (split_id, buffer_id, split_area) in visible_buffers {
let is_active = split_id == active_split_id;
let layout = Self::split_layout(split_area);
let (split_buffers, tab_scroll_offset) =
Self::split_buffers_for_tabs(split_view_states.as_deref(), split_id, buffer_id);
// Determine hover state for this split's tabs
let tab_hover_for_split = hovered_tab.and_then(|(hover_buf, hover_split, is_close)| {
if hover_split == split_id {
Some((hover_buf, is_close))
} else {
None
}
});
// Render tabs for this split and collect hit areas
let tab_hit_areas = TabsRenderer::render_for_split(
frame,
layout.tabs_rect,
&split_buffers,
buffers,
buffer_metadata,
buffer_id, // The currently displayed buffer in this split
theme,
is_active,
tab_scroll_offset,
tab_hover_for_split,
);
// Add tab row to hit areas (all tabs share the same row)
let tab_row = layout.tabs_rect.y;
for (buf_id, start_col, end_col, close_start) in tab_hit_areas {
all_tab_areas.push((split_id, buf_id, tab_row, start_col, end_col, close_start));
}
// Render split control buttons at the right side of tabs row
// Show maximize/unmaximize button when: multiple splits exist OR we're currently maximized
// Show close button when: multiple splits exist AND we're not maximized
let show_maximize_btn = has_multiple_splits || is_maximized;
let show_close_btn = has_multiple_splits && !is_maximized;
if show_maximize_btn || show_close_btn {
// Calculate button positions from right edge
// Layout: [maximize] [space] [close] |
let mut btn_x = layout.tabs_rect.x + layout.tabs_rect.width.saturating_sub(2);
// Render close button first (rightmost) if visible
if show_close_btn {
let is_hovered = hovered_close_split == Some(split_id);
let close_fg = if is_hovered {
theme.tab_close_hover_fg
} else {
theme.line_number_fg
};
let close_button = Paragraph::new("×")
.style(Style::default().fg(close_fg).bg(theme.tab_separator_bg));
let close_area = Rect::new(btn_x, tab_row, 1, 1);
frame.render_widget(close_button, close_area);
close_split_areas.push((split_id, tab_row, btn_x, btn_x + 1));
btn_x = btn_x.saturating_sub(2); // Move left with 1 space for next button
}
// Render maximize/unmaximize button
if show_maximize_btn {
let is_hovered = hovered_maximize_split == Some(split_id);
let max_fg = if is_hovered {
theme.tab_close_hover_fg
} else {
theme.line_number_fg
};
// Use □ for maximize, ⧉ for unmaximize (restore)
let icon = if is_maximized { "⧉" } else { "□" };
let max_button = Paragraph::new(icon)
.style(Style::default().fg(max_fg).bg(theme.tab_separator_bg));
let max_area = Rect::new(btn_x, tab_row, 1, 1);
frame.render_widget(max_button, max_area);
maximize_split_areas.push((split_id, tab_row, btn_x, btn_x + 1));
}
}
// Get references separately to avoid double borrow
let state_opt = buffers.get_mut(&buffer_id);
let event_log_opt = event_logs.get_mut(&buffer_id);
if let Some(state) = state_opt {
// Get viewport from SplitViewState (authoritative source)
// We need to get it mutably for sync operations
// Use as_deref() to get Option<&HashMap> for read-only operations
let view_state_opt = split_view_states
.as_deref()
.and_then(|vs| vs.get(&split_id));
let viewport_clone =
view_state_opt
.map(|vs| vs.viewport.clone())
.unwrap_or_else(|| {
crate::view::viewport::Viewport::new(
layout.content_rect.width,
layout.content_rect.height,
)
});
let mut viewport = viewport_clone;
let saved_cursors = Self::temporary_split_state(
state,
split_view_states.as_deref(),
split_id,
is_active,
);
Self::sync_viewport_to_content(
&mut viewport,
&mut state.buffer,
&state.cursors,
layout.content_rect,
);
let view_prefs =
Self::resolve_view_preferences(state, split_view_states.as_deref(), split_id);
let split_view_mappings = Self::render_buffer_in_split(
frame,
state,
&mut viewport,
event_log_opt,
layout.content_rect,
is_active,
theme,
ansi_background,
background_fade,
lsp_waiting,
view_prefs.view_mode,
view_prefs.compose_width,
view_prefs.compose_column_guides,
view_prefs.view_transform,
estimated_line_length,
highlight_context_bytes,
buffer_id,
hide_cursor,
);
// Store view line mappings for mouse click handling
view_line_mappings.insert(split_id, split_view_mappings);
// For small files, count actual lines for accurate scrollbar
// For large files, we'll use a constant thumb size
let buffer_len = state.buffer.len();
let (total_lines, top_line) = Self::scrollbar_line_counts(
state,
&viewport,
large_file_threshold_bytes,
buffer_len,
);
// Render scrollbar for this split and get thumb position
let (thumb_start, thumb_end) = Self::render_scrollbar(
frame,
state,
&viewport,
layout.scrollbar_rect,
is_active,
theme,
large_file_threshold_bytes,
total_lines,
top_line,
);
// Restore the original cursors after rendering content and scrollbar
Self::restore_split_state(state, saved_cursors);
// Write back updated viewport to SplitViewState
// This is crucial for cursor visibility tracking (ensure_visible_in_layout updates)
// NOTE: We do NOT clear skip_ensure_visible here - it should persist across
// renders until something actually needs cursor visibility check
if let Some(view_states) = split_view_states.as_deref_mut() {
if let Some(view_state) = view_states.get_mut(&split_id) {
tracing::trace!(
"Writing back viewport: top_byte={}, skip_ensure_visible={}",
viewport.top_byte,
viewport.should_skip_ensure_visible()
);
view_state.viewport = viewport.clone();
}
}
// Store the areas for mouse handling
split_areas.push((
split_id,
buffer_id,
layout.content_rect,
layout.scrollbar_rect,
thumb_start,
thumb_end,
));
}
}
// Render split separators
let separators = split_manager.get_separators(area);
for (direction, x, y, length) in separators {
Self::render_separator(frame, direction, x, y, length, theme);
}
(
split_areas,
all_tab_areas,
close_split_areas,
maximize_split_areas,
view_line_mappings,
)
}
/// Render a split separator line
fn render_separator(
frame: &mut Frame,
direction: SplitDirection,
x: u16,
y: u16,
length: u16,
theme: &crate::view::theme::Theme,
) {
match direction {
SplitDirection::Horizontal => {
// Draw horizontal line
let line_area = Rect::new(x, y, length, 1);
let line_text = "─".repeat(length as usize);
let paragraph =
Paragraph::new(line_text).style(Style::default().fg(theme.split_separator_fg));
frame.render_widget(paragraph, line_area);
}
SplitDirection::Vertical => {
// Draw vertical line
for offset in 0..length {
let cell_area = Rect::new(x, y + offset, 1, 1);
let paragraph =
Paragraph::new("│").style(Style::default().fg(theme.split_separator_fg));
frame.render_widget(paragraph, cell_area);
}
}
}
}
fn split_layout(split_area: Rect) -> SplitLayout {
let tabs_height = 1u16;
let scrollbar_width = 1u16;
let tabs_rect = Rect::new(split_area.x, split_area.y, split_area.width, tabs_height);
let content_rect = Rect::new(
split_area.x,
split_area.y + tabs_height,
split_area.width.saturating_sub(scrollbar_width),
split_area.height.saturating_sub(tabs_height),
);
let scrollbar_rect = Rect::new(
split_area.x + split_area.width.saturating_sub(scrollbar_width),
split_area.y + tabs_height,
scrollbar_width,
split_area.height.saturating_sub(tabs_height),
);
SplitLayout {
tabs_rect,
content_rect,
scrollbar_rect,
}
}
fn split_buffers_for_tabs(
split_view_states: Option<
&HashMap<crate::model::event::SplitId, crate::view::split::SplitViewState>,
>,
split_id: crate::model::event::SplitId,
buffer_id: BufferId,
) -> (Vec<BufferId>, usize) {
if let Some(view_states) = split_view_states {
if let Some(view_state) = view_states.get(&split_id) {
return (
view_state.open_buffers.clone(),
view_state.tab_scroll_offset,
);
}
}
(vec![buffer_id], 0)
}
fn temporary_split_state(
state: &mut EditorState,
split_view_states: Option<
&HashMap<crate::model::event::SplitId, crate::view::split::SplitViewState>,
>,
split_id: crate::model::event::SplitId,
is_active: bool,
) -> Option<crate::model::cursor::Cursors> {
if is_active {
return None;
}
if let Some(view_states) = split_view_states {
if let Some(view_state) = view_states.get(&split_id) {
// Only save/restore cursors - viewport is now owned by SplitViewState
let saved_cursors = Some(std::mem::replace(
&mut state.cursors,
view_state.cursors.clone(),
));
return saved_cursors;
}
}
None
}
fn restore_split_state(
state: &mut EditorState,
saved_cursors: Option<crate::model::cursor::Cursors>,
) {
if let Some(cursors) = saved_cursors {
state.cursors = cursors;
}
}
fn sync_viewport_to_content(
viewport: &mut crate::view::viewport::Viewport,
buffer: &mut crate::model::buffer::Buffer,
cursors: &crate::model::cursor::Cursors,
content_rect: Rect,
) {
let size_changed =
viewport.width != content_rect.width || viewport.height != content_rect.height;
if size_changed {
viewport.resize(content_rect.width, content_rect.height);
}
// Always sync viewport with cursor to ensure visibility after cursor movements
// The sync_with_cursor method internally checks needs_sync and skip_resize_sync
// so this is safe to call unconditionally. Previously needs_sync was set by
// EditorState.apply() but now viewport is owned by SplitViewState.
let primary = *cursors.primary();
viewport.ensure_visible(buffer, &primary);
}
fn resolve_view_preferences(
state: &EditorState,
split_view_states: Option<
&HashMap<crate::model::event::SplitId, crate::view::split::SplitViewState>,
>,
split_id: crate::model::event::SplitId,
) -> ViewPreferences {
if let Some(view_states) = split_view_states {
if let Some(view_state) = view_states.get(&split_id) {
return ViewPreferences {
view_mode: view_state.view_mode.clone(),
compose_width: view_state.compose_width,
compose_column_guides: view_state.compose_column_guides.clone(),
view_transform: view_state.view_transform.clone(),
};
}
}
ViewPreferences {
view_mode: state.view_mode.clone(),
compose_width: state.compose_width,
compose_column_guides: state.compose_column_guides.clone(),
view_transform: state.view_transform.clone(),
}
}
fn scrollbar_line_counts(
state: &EditorState,
viewport: &crate::view::viewport::Viewport,
large_file_threshold_bytes: u64,
buffer_len: usize,
) -> (usize, usize) {
if buffer_len > large_file_threshold_bytes as usize {
return (0, 0);
}
let total_lines = if buffer_len > 0 {
state.buffer.get_line_number(buffer_len.saturating_sub(1)) + 1
} else {
1
};
let top_line = if viewport.top_byte < buffer_len {
state.buffer.get_line_number(viewport.top_byte)
} else {
0
};
(total_lines, top_line)
}
/// Render a scrollbar for a split
/// Returns (thumb_start, thumb_end) positions for mouse hit testing
fn render_scrollbar(
frame: &mut Frame,
state: &EditorState,
viewport: &crate::view::viewport::Viewport,
scrollbar_rect: Rect,
is_active: bool,
_theme: &crate::view::theme::Theme,
large_file_threshold_bytes: u64,
total_lines: usize,
top_line: usize,
) -> (usize, usize) {
let height = scrollbar_rect.height as usize;
if height == 0 {
return (0, 0);
}
let buffer_len = state.buffer.len();
let viewport_top = viewport.top_byte;
// Use the constant viewport height (allocated terminal rows), not visible_line_count()
// which varies based on content. The scrollbar should represent the ratio of the
// viewport AREA to total document size, remaining constant throughout scrolling.
let viewport_height_lines = viewport.height as usize;
// Calculate scrollbar thumb position and size
let (thumb_start, thumb_size) = if buffer_len > large_file_threshold_bytes as usize {
// Large file: use constant 1-character thumb for performance
let thumb_start = if buffer_len > 0 {
((viewport_top as f64 / buffer_len as f64) * height as f64) as usize
} else {
0
};
(thumb_start, 1)
} else {
// Small file: use actual line count for accurate scrollbar
// total_lines and top_line are passed in (already calculated with mutable access)
// Calculate thumb size based on viewport ratio to total document
let thumb_size_raw = if total_lines > 0 {
((viewport_height_lines as f64 / total_lines as f64) * height as f64).ceil()
as usize
} else {
1
};
// Calculate the maximum scroll position first to determine if buffer fits in viewport
// The maximum scroll position is when the last line of the file is at
// the bottom of the viewport, i.e., max_scroll_line = total_lines - viewport_height
let max_scroll_line = total_lines.saturating_sub(viewport_height_lines);
// When buffer fits entirely in viewport (no scrolling possible),
// fill the entire scrollbar to make it obvious to the user
let thumb_size = if max_scroll_line == 0 {
height
} else {
// Cap thumb size: minimum 1, maximum 80% of scrollbar height
let max_thumb_size = (height as f64 * 0.8).floor() as usize;
thumb_size_raw.max(1).min(max_thumb_size).min(height)
};
// Calculate thumb position using proper linear mapping:
// - At line 0: thumb_start = 0
// - At max scroll position: thumb_start = height - thumb_size
let thumb_start = if max_scroll_line > 0 {
// Linear interpolation from 0 to (height - thumb_size)
let scroll_ratio = top_line.min(max_scroll_line) as f64 / max_scroll_line as f64;
let max_thumb_start = height.saturating_sub(thumb_size);
(scroll_ratio * max_thumb_start as f64) as usize
} else {
// File fits in viewport, thumb fills entire height starting at top
0
};
(thumb_start, thumb_size)
};
let thumb_end = thumb_start + thumb_size;
// Choose colors based on whether split is active
let track_color = if is_active {
Color::DarkGray
} else {
Color::Black
};
let thumb_color = if is_active {
Color::Gray
} else {
Color::DarkGray
};
// Render scrollbar track and thumb
for row in 0..height {
let cell_area = Rect::new(scrollbar_rect.x, scrollbar_rect.y + row as u16, 1, 1);
let (char, color) = if row >= thumb_start && row < thumb_end {
// Thumb
("█", thumb_color)
} else {
// Track
("│", track_color)
};
let paragraph = Paragraph::new(char).style(Style::default().fg(color));
frame.render_widget(paragraph, cell_area);
}
// Return thumb position for mouse hit testing
(thumb_start, thumb_end)
}
fn build_view_data(
state: &mut EditorState,
viewport: &crate::view::viewport::Viewport,
view_transform: Option<ViewTransformPayload>,
estimated_line_length: usize,
visible_count: usize,
line_wrap_enabled: bool,
content_width: usize,
gutter_width: usize,
) -> ViewData {
// Check if buffer is binary before building tokens
let is_binary = state.buffer.is_binary();
// Build base token stream from source
let base_tokens = Self::build_base_tokens(
&mut state.buffer,
viewport.top_byte,
estimated_line_length,
visible_count,
is_binary,
);
// Use plugin transform if available, otherwise use base tokens
let mut tokens = view_transform.map(|vt| vt.tokens).unwrap_or(base_tokens);
// Apply wrapping transform if enabled
if line_wrap_enabled {
tokens = Self::apply_wrapping_transform(tokens, content_width, gutter_width);
}
// Convert tokens to display lines using the view pipeline
// Each ViewLine preserves LineStart info for correct line number rendering
// Use binary mode if the buffer contains binary content
let is_binary = state.buffer.is_binary();
let source_lines: Vec<ViewLine> =
ViewLineIterator::with_binary_mode(&tokens, is_binary).collect();
// Inject virtual lines (LineAbove/LineBelow) from VirtualTextManager
let lines = Self::inject_virtual_lines(source_lines, state);
ViewData { lines }
}
/// Create a ViewLine from virtual text content (for LineAbove/LineBelow)
fn create_virtual_line(text: &str, style: ratatui::style::Style) -> ViewLine {
use crate::services::plugins::api::ViewTokenStyle;
let text = text.to_string();
let len = text.chars().count();
// Convert ratatui Style to ViewTokenStyle
let token_style = ViewTokenStyle {
fg: style.fg.and_then(|c| match c {
ratatui::style::Color::Rgb(r, g, b) => Some((r, g, b)),
_ => None,
}),
bg: style.bg.and_then(|c| match c {
ratatui::style::Color::Rgb(r, g, b) => Some((r, g, b)),
_ => None,
}),
bold: style.add_modifier.contains(ratatui::style::Modifier::BOLD),
italic: style
.add_modifier
.contains(ratatui::style::Modifier::ITALIC),
};
ViewLine {
text,
// All None - no source mapping (this is injected content)
char_mappings: vec![None; len],
// All have the virtual text's style
char_styles: vec![Some(token_style); len],
tab_starts: HashSet::new(),
// AfterInjectedNewline means no line number will be shown
line_start: LineStart::AfterInjectedNewline,
ends_with_newline: true,
}
}
/// Inject virtual lines (LineAbove/LineBelow) into the ViewLine stream
fn inject_virtual_lines(source_lines: Vec<ViewLine>, state: &EditorState) -> Vec<ViewLine> {
use crate::view::virtual_text::VirtualTextPosition;
// Get viewport byte range from source lines
let viewport_start = source_lines
.first()
.and_then(|l| l.char_mappings.iter().find_map(|m| *m))
.unwrap_or(0);
let viewport_end = source_lines
.last()
.and_then(|l| l.char_mappings.iter().rev().find_map(|m| *m))
.map(|b| b + 1)
.unwrap_or(viewport_start);
// Query virtual lines in viewport range
let virtual_lines = state.virtual_texts.query_lines_in_range(
&state.marker_list,
viewport_start,
viewport_end,
);
// If no virtual lines, return source lines unchanged
if virtual_lines.is_empty() {
return source_lines;
}
// Build result with virtual lines injected
let mut result = Vec::with_capacity(source_lines.len() + virtual_lines.len());
for source_line in source_lines {
// Get this line's byte range
let line_start_byte = source_line.char_mappings.iter().find_map(|m| *m);
let line_end_byte = source_line
.char_mappings
.iter()
.rev()
.find_map(|m| *m)
.map(|b| b + 1);
// Find LineAbove virtual texts anchored to this line
if let (Some(start), Some(end)) = (line_start_byte, line_end_byte) {
for (anchor_pos, vtext) in &virtual_lines {
if *anchor_pos >= start && *anchor_pos < end {
if vtext.position == VirtualTextPosition::LineAbove {
result.push(Self::create_virtual_line(&vtext.text, vtext.style));
}
}
}
}
// Add the source line
result.push(source_line.clone());
// Find LineBelow virtual texts anchored to this line
if let (Some(start), Some(end)) = (line_start_byte, line_end_byte) {
for (anchor_pos, vtext) in &virtual_lines {
if *anchor_pos >= start && *anchor_pos < end {
if vtext.position == VirtualTextPosition::LineBelow {
result.push(Self::create_virtual_line(&vtext.text, vtext.style));
}
}
}
}
}
result
}
fn build_base_tokens(
buffer: &mut Buffer,
top_byte: usize,
estimated_line_length: usize,
visible_count: usize,
is_binary: bool,
) -> Vec<crate::services::plugins::api::ViewTokenWire> {
use crate::services::plugins::api::{ViewTokenWire, ViewTokenWireKind};
let mut tokens = Vec::new();
// For binary files, read raw bytes directly to preserve byte values
// (LineIterator uses String::from_utf8_lossy which loses high bytes)
if is_binary {
return Self::build_base_tokens_binary(
buffer,
top_byte,
estimated_line_length,
visible_count,
);
}
let mut iter = buffer.line_iterator(top_byte, estimated_line_length);
let mut lines_seen = 0usize;
let max_lines = visible_count.saturating_add(4);
while lines_seen < max_lines {
if let Some((line_start, line_content)) = iter.next() {
let mut byte_offset = 0usize;
for ch in line_content.chars() {
let ch_len = ch.len_utf8();
let source_offset = Some(line_start + byte_offset);
match ch {
'\n' => {
tokens.push(ViewTokenWire {
source_offset,
kind: ViewTokenWireKind::Newline,
style: None,
});
}
' ' => {
tokens.push(ViewTokenWire {
source_offset,
kind: ViewTokenWireKind::Space,
style: None,
});
}
'\t' => {
// Tab is safe, emit as Text
tokens.push(ViewTokenWire {
source_offset,
kind: ViewTokenWireKind::Text(ch.to_string()),
style: None,
});
}
_ if Self::is_control_char(ch) => {
// Control character - emit as BinaryByte to render as <XX>
tokens.push(ViewTokenWire {
source_offset,
kind: ViewTokenWireKind::BinaryByte(ch as u8),
style: None,
});
}
_ => {
// Accumulate consecutive non-space/non-newline chars into Text tokens
if let Some(last) = tokens.last_mut() {
if let ViewTokenWireKind::Text(ref mut s) = last.kind {
// Extend existing Text token if contiguous
let expected_offset = last.source_offset.map(|o| o + s.len());
if expected_offset == Some(line_start + byte_offset) {
s.push(ch);
byte_offset += ch_len;
continue;
}
}
}
tokens.push(ViewTokenWire {
source_offset,
kind: ViewTokenWireKind::Text(ch.to_string()),
style: None,
});
}
}
byte_offset += ch_len;
}
lines_seen += 1;
} else {
break;
}
}
// Handle empty buffer
if tokens.is_empty() {
tokens.push(ViewTokenWire {
source_offset: Some(top_byte),
kind: ViewTokenWireKind::Text(String::new()),
style: None,
});
}
tokens
}
/// Build tokens for binary files by reading raw bytes directly
/// This preserves byte values >= 0x80 that would be lost by String::from_utf8_lossy
fn build_base_tokens_binary(
buffer: &mut Buffer,
top_byte: usize,
estimated_line_length: usize,
visible_count: usize,
) -> Vec<crate::services::plugins::api::ViewTokenWire> {
use crate::services::plugins::api::{ViewTokenWire, ViewTokenWireKind};
let mut tokens = Vec::new();
let max_lines = visible_count.saturating_add(4);
let buffer_len = buffer.len();
if top_byte >= buffer_len {
tokens.push(ViewTokenWire {
source_offset: Some(top_byte),
kind: ViewTokenWireKind::Text(String::new()),
style: None,
});
return tokens;
}
// Estimate how many bytes we need to read
let estimated_bytes = estimated_line_length * max_lines * 2;
let bytes_to_read = estimated_bytes.min(buffer_len - top_byte);
// Read raw bytes directly from buffer
let raw_bytes = buffer.slice_bytes(top_byte..top_byte + bytes_to_read);
let mut byte_offset = 0usize;
let mut lines_seen = 0usize;
let mut current_text = String::new();
let mut current_text_start: Option<usize> = None;
// Helper to flush accumulated text to tokens
let flush_text =
|tokens: &mut Vec<ViewTokenWire>, text: &mut String, start: &mut Option<usize>| {
if !text.is_empty() {
tokens.push(ViewTokenWire {
source_offset: *start,
kind: ViewTokenWireKind::Text(std::mem::take(text)),
style: None,
});
*start = None;
}
};
while byte_offset < raw_bytes.len() && lines_seen < max_lines {
let b = raw_bytes[byte_offset];
let source_offset = top_byte + byte_offset;
match b {
b'\n' => {
flush_text(&mut tokens, &mut current_text, &mut current_text_start);
tokens.push(ViewTokenWire {
source_offset: Some(source_offset),
kind: ViewTokenWireKind::Newline,
style: None,
});
lines_seen += 1;
}
b' ' => {
flush_text(&mut tokens, &mut current_text, &mut current_text_start);
tokens.push(ViewTokenWire {
source_offset: Some(source_offset),
kind: ViewTokenWireKind::Space,
style: None,
});
}
_ => {
// For binary files, emit unprintable bytes as BinaryByte tokens
// This ensures view_pipeline.rs can map all 4 chars of <XX> to the same source byte
if Self::is_binary_unprintable(b) {
// Flush any accumulated printable text first
flush_text(&mut tokens, &mut current_text, &mut current_text_start);
// Emit as BinaryByte so cursor positioning works correctly
tokens.push(ViewTokenWire {
source_offset: Some(source_offset),
kind: ViewTokenWireKind::BinaryByte(b),
style: None,
});
} else {
// Printable ASCII - accumulate into text token
// Each printable char is 1 byte so accumulation works correctly
if current_text_start.is_none() {
current_text_start = Some(source_offset);
}
current_text.push(b as char);
}
}
}
byte_offset += 1;
}
// Flush any remaining text
flush_text(&mut tokens, &mut current_text, &mut current_text_start);
// Handle empty buffer
if tokens.is_empty() {
tokens.push(ViewTokenWire {
source_offset: Some(top_byte),
kind: ViewTokenWireKind::Text(String::new()),
style: None,
});
}
tokens
}
/// Check if a byte should be displayed as <XX> in binary mode
/// Returns true for:
/// - Control characters (0x00-0x1F) except tab and newline
/// - DEL (0x7F)
/// - High bytes (0x80-0xFF) which are not valid single-byte UTF-8
///
/// Note: In binary mode, we must be very strict about what characters we allow through,
/// because control characters can move the terminal cursor and corrupt the display:
/// - CR (0x0D) moves cursor to column 0, overwriting the gutter
/// - VT (0x0B) and FF (0x0C) move cursor vertically
/// - ESC (0x1B) starts ANSI escape sequences
fn is_binary_unprintable(b: u8) -> bool {
// Only allow: tab (0x09) and newline (0x0A)
// These are the only safe whitespace characters in binary mode
// All other control characters can corrupt terminal output
if b == 0x09 || b == 0x0A {
return false;
}
// All other control characters (0x00-0x1F) are unprintable in binary mode
// This includes CR, VT, FF, ESC which can move the cursor
if b < 0x20 {
return true;
}
// DEL character (0x7F) is unprintable
if b == 0x7F {
return true;
}
// High bytes (0x80-0xFF) are unprintable in binary mode
// (they're not valid single-byte UTF-8 and would be converted to replacement char)
if b >= 0x80 {
return true;
}
false
}
/// Check if a character is a control character that should be rendered as <XX>
/// This applies to ALL files (binary and non-binary) to prevent terminal corruption
fn is_control_char(ch: char) -> bool {
let code = ch as u32;
// Only check ASCII range
if code >= 128 {
return false;
}
let b = code as u8;
// Allow: tab (0x09), newline (0x0A), ESC (0x1B - for ANSI sequences)
if b == 0x09 || b == 0x0A || b == 0x1B {
return false;
}
// Other control characters (0x00-0x1F) and DEL (0x7F) are dangerous
// This includes CR (0x0D), VT (0x0B), FF (0x0C) which move the cursor
b < 0x20 || b == 0x7F
}
/// Public wrapper for building base tokens - used by render.rs for the view_transform_request hook
pub fn build_base_tokens_for_hook(
buffer: &mut Buffer,
top_byte: usize,
estimated_line_length: usize,
visible_count: usize,
is_binary: bool,
) -> Vec<crate::services::plugins::api::ViewTokenWire> {
Self::build_base_tokens(
buffer,
top_byte,
estimated_line_length,
visible_count,
is_binary,
)
}
fn apply_wrapping_transform(
tokens: Vec<crate::services::plugins::api::ViewTokenWire>,
content_width: usize,
gutter_width: usize,
) -> Vec<crate::services::plugins::api::ViewTokenWire> {
use crate::primitives::ansi::visible_char_count;
use crate::services::plugins::api::{ViewTokenWire, ViewTokenWireKind};
let mut wrapped = Vec::new();
let mut current_line_width = 0;
// Calculate available width (accounting for gutter on first line only)
let available_width = content_width.saturating_sub(gutter_width);
for token in tokens {
match &token.kind {
ViewTokenWireKind::Newline => {
// Real newlines always break the line
wrapped.push(token);
current_line_width = 0;
}
ViewTokenWireKind::Text(text) => {
// Use visible character count (excludes ANSI escape sequences)
// so line width calculation is based on actual visual width
let text_len = visible_char_count(text);
// If this token would exceed line width, insert Break before it
if current_line_width > 0 && current_line_width + text_len > available_width {
wrapped.push(ViewTokenWire {
source_offset: None,
kind: ViewTokenWireKind::Break,
style: None,
});
current_line_width = 0;
}
// If visible text is longer than line width, we need to split
// However, we don't split tokens containing ANSI codes to avoid
// breaking escape sequences. ANSI-heavy content may exceed line width.
if text_len > available_width
&& !crate::primitives::ansi::contains_ansi_codes(text)
{
let chars: Vec<char> = text.chars().collect();
let mut char_idx = 0;
let source_base = token.source_offset;
while char_idx < chars.len() {
let remaining = chars.len() - char_idx;
let chunk_size = remaining.min(available_width - current_line_width);
if chunk_size == 0 {
// Need to break to next line
wrapped.push(ViewTokenWire {
source_offset: None,
kind: ViewTokenWireKind::Break,
style: None,
});
current_line_width = 0;
continue;
}
let chunk: String =
chars[char_idx..char_idx + chunk_size].iter().collect();
let chunk_source = source_base.map(|b| b + char_idx);
wrapped.push(ViewTokenWire {
source_offset: chunk_source,
kind: ViewTokenWireKind::Text(chunk),
style: token.style.clone(),
});
current_line_width += chunk_size;
char_idx += chunk_size;
// If we filled the line, break
if current_line_width >= available_width {
wrapped.push(ViewTokenWire {
source_offset: None,
kind: ViewTokenWireKind::Break,
style: None,
});
current_line_width = 0;
}
}
} else {
wrapped.push(token);
current_line_width += text_len;
}
}
ViewTokenWireKind::Space => {
// Spaces count toward line width
if current_line_width + 1 > available_width {
wrapped.push(ViewTokenWire {
source_offset: None,
kind: ViewTokenWireKind::Break,
style: None,
});
current_line_width = 0;
}
wrapped.push(token);
current_line_width += 1;
}
ViewTokenWireKind::Break => {
// Pass through existing breaks
wrapped.push(token);
current_line_width = 0;
}
ViewTokenWireKind::BinaryByte(_) => {
// Binary bytes render as <XX> which is 4 characters
let byte_display_width = 4;
if current_line_width + byte_display_width > available_width {
wrapped.push(ViewTokenWire {
source_offset: None,
kind: ViewTokenWireKind::Break,
style: None,
});
current_line_width = 0;
}
wrapped.push(token);
current_line_width += byte_display_width;
}
}
}
wrapped
}
fn calculate_view_anchor(view_lines: &[ViewLine], top_byte: usize) -> ViewAnchor {
// Find the first line that contains source content at or after top_byte
// Walk backwards to include any injected content (headers) that precede it
for (idx, line) in view_lines.iter().enumerate() {
// Check if this line has source content at or after top_byte
if let Some(first_source) = line.char_mappings.iter().find_map(|m| *m) {
if first_source >= top_byte {
// Found a line with source >= top_byte
// But we may need to include previous lines if they're injected headers
let mut start_idx = idx;
while start_idx > 0 {
let prev_line = &view_lines[start_idx - 1];
// If previous line is all injected (no source mappings), include it
let prev_has_source = prev_line.char_mappings.iter().any(|m| m.is_some());
if !prev_has_source {
start_idx -= 1;
} else {
break;
}
}
return ViewAnchor {
start_line_idx: start_idx,
start_line_skip: 0,
};
}
}
}
// No matching source found, start from beginning
ViewAnchor {
start_line_idx: 0,
start_line_skip: 0,
}
}
fn calculate_compose_layout(
area: Rect,
view_mode: &ViewMode,
compose_width: Option<u16>,
) -> ComposeLayout {
// Enable centering/margins if:
// 1. View mode is explicitly Compose, OR
// 2. compose_width is set (plugin-driven compose mode)
let should_compose = view_mode == &ViewMode::Compose || compose_width.is_some();
if !should_compose {
return ComposeLayout {
render_area: area,
left_pad: 0,
right_pad: 0,
};
}
let target_width = compose_width.map(|w| w as u16).unwrap_or(area.width);
let clamped_width = target_width.min(area.width).max(1);
if clamped_width >= area.width {
return ComposeLayout {
render_area: area,
left_pad: 0,
right_pad: 0,
};
}
let pad_total = area.width - clamped_width;
let left_pad = pad_total / 2;
let right_pad = pad_total - left_pad;
ComposeLayout {
render_area: Rect::new(area.x + left_pad, area.y, clamped_width, area.height),
left_pad,
right_pad,
}
}
fn render_compose_margins(
frame: &mut Frame,
area: Rect,
layout: &ComposeLayout,
_view_mode: &ViewMode,
theme: &crate::view::theme::Theme,
) {
// Render margins if there are any pads (indicates compose layout is active)
if layout.left_pad == 0 && layout.right_pad == 0 {
return;
}
// Paper-on-desk effect: outer "desk" margin with inner "paper edge"
// Layout: [desk][paper edge][content][paper edge][desk]
const PAPER_EDGE_WIDTH: u16 = 1;
let desk_style = Style::default().bg(theme.compose_margin_bg);
let paper_style = Style::default().bg(theme.editor_bg);
if layout.left_pad > 0 {
let paper_edge = PAPER_EDGE_WIDTH.min(layout.left_pad);
let desk_width = layout.left_pad.saturating_sub(paper_edge);
// Desk area (outer)
if desk_width > 0 {
let desk_rect = Rect::new(area.x, area.y, desk_width, area.height);
frame.render_widget(Block::default().style(desk_style), desk_rect);
}
// Paper edge (inner, adjacent to content)
if paper_edge > 0 {
let paper_rect = Rect::new(area.x + desk_width, area.y, paper_edge, area.height);
frame.render_widget(Block::default().style(paper_style), paper_rect);
}
}
if layout.right_pad > 0 {
let paper_edge = PAPER_EDGE_WIDTH.min(layout.right_pad);
let desk_width = layout.right_pad.saturating_sub(paper_edge);
let right_start = area.x + layout.left_pad + layout.render_area.width;
// Paper edge (inner, adjacent to content)
if paper_edge > 0 {
let paper_rect = Rect::new(right_start, area.y, paper_edge, area.height);
frame.render_widget(Block::default().style(paper_style), paper_rect);
}
// Desk area (outer)
if desk_width > 0 {
let desk_rect =
Rect::new(right_start + paper_edge, area.y, desk_width, area.height);
frame.render_widget(Block::default().style(desk_style), desk_rect);
}
}
}
fn selection_context(state: &EditorState) -> SelectionContext {
let ranges: Vec<Range<usize>> = state
.cursors
.iter()
.filter_map(|(_, cursor)| cursor.selection_range())
.collect();
let block_rects: Vec<(usize, usize, usize, usize)> = state
.cursors
.iter()
.filter_map(|(_, cursor)| {
if cursor.selection_mode == SelectionMode::Block {
if let Some(anchor) = cursor.block_anchor {
// Convert cursor position to 2D coords
let cur_line = state.buffer.get_line_number(cursor.position);
let cur_line_start = state.buffer.line_start_offset(cur_line).unwrap_or(0);
let cur_col = cursor.position.saturating_sub(cur_line_start);
// Return normalized rectangle (min values first)
Some((
anchor.line.min(cur_line),
anchor.column.min(cur_col),
anchor.line.max(cur_line),
anchor.column.max(cur_col),
))
} else {
None
}
} else {
None
}
})
.collect();
let cursor_positions: Vec<usize> = if state.show_cursors {
state
.cursors
.iter()
.map(|(_, cursor)| cursor.position)
.collect()
} else {
Vec::new()
};
SelectionContext {
ranges,
block_rects,
cursor_positions,
primary_cursor_position: state.cursors.primary().position,
}
}
fn decoration_context(
state: &mut EditorState,
viewport_start: usize,
viewport_end: usize,
primary_cursor_position: usize,
theme: &crate::view::theme::Theme,
highlight_context_bytes: usize,
) -> DecorationContext {
// Extend highlighting range by ~1 viewport size before/after for better context.
// This helps tree-sitter parse multi-line constructs that span viewport boundaries.
let viewport_size = viewport_end.saturating_sub(viewport_start);
let highlight_start = viewport_start.saturating_sub(viewport_size);
let highlight_end = viewport_end
.saturating_add(viewport_size)
.min(state.buffer.len());
let highlight_spans = state.highlighter.highlight_viewport(
&state.buffer,
highlight_start,
highlight_end,
theme,
highlight_context_bytes,
);
// Update semantic highlighter color from theme
state.semantic_highlighter.highlight_color = theme.semantic_highlight_bg;
let semantic_spans = state.semantic_highlighter.highlight_occurrences(
&state.buffer,
primary_cursor_position,
viewport_start,
viewport_end,
highlight_context_bytes,
);
let viewport_overlays = state
.overlays
.query_viewport(viewport_start, viewport_end, &state.marker_list)
.into_iter()
.map(|(overlay, range)| (overlay.clone(), range))
.collect::<Vec<_>>();
// Use the lsp-diagnostic namespace to identify diagnostic overlays
let diagnostic_ns = crate::services::lsp::diagnostics::lsp_diagnostic_namespace();
let diagnostic_lines: HashSet<usize> = viewport_overlays
.iter()
.filter_map(|(overlay, range)| {
if overlay.namespace.as_ref() == Some(&diagnostic_ns) {
return Some(state.buffer.get_line_number(range.start));
}
None
})
.collect();
let virtual_text_lookup: HashMap<usize, Vec<crate::view::virtual_text::VirtualText>> =
state
.virtual_texts
.build_lookup(&state.marker_list, viewport_start, viewport_end)
.into_iter()
.map(|(position, texts)| (position, texts.into_iter().cloned().collect()))
.collect();
// Pre-compute line indicators for the viewport (only query markers in visible range)
let line_indicators = state.margins.get_indicators_for_viewport(
viewport_start,
viewport_end,
|byte_offset| state.buffer.get_line_number(byte_offset),
);
DecorationContext {
highlight_spans,
semantic_spans,
viewport_overlays,
virtual_text_lookup,
diagnostic_lines,
line_indicators,
}
}
fn calculate_viewport_end(
state: &mut EditorState,
viewport_start: usize,
estimated_line_length: usize,
visible_count: usize,
) -> usize {
let mut iter_temp = state
.buffer
.line_iterator(viewport_start, estimated_line_length);
let mut viewport_end = viewport_start;
for _ in 0..visible_count {
if let Some((line_start, line_content)) = iter_temp.next() {
viewport_end = line_start + line_content.len();
} else {
break;
}
}
viewport_end
}
fn render_view_lines(input: LineRenderInput<'_>) -> LineRenderOutput {
let LineRenderInput {
state,
theme,
view_lines,
view_anchor,
render_area,
gutter_width,
selection,
decorations,
starting_line_num,
visible_line_count,
lsp_waiting,
is_active,
line_wrap,
estimated_lines,
left_column,
} = input;
let selection_ranges = &selection.ranges;
let block_selections = &selection.block_rects;
let cursor_positions = &selection.cursor_positions;
let primary_cursor_position = selection.primary_cursor_position;
let highlight_spans = &decorations.highlight_spans;
let semantic_spans = &decorations.semantic_spans;
let viewport_overlays = &decorations.viewport_overlays;
let virtual_text_lookup = &decorations.virtual_text_lookup;
let diagnostic_lines = &decorations.diagnostic_lines;
let line_indicators = &decorations.line_indicators;
let mut lines = Vec::new();
let mut lines_rendered = 0usize;
let mut view_iter_idx = view_anchor.start_line_idx;
let mut cursor_screen_x = 0u16;
let mut cursor_screen_y = 0u16;
let mut have_cursor = false;
let mut last_line_end: Option<LastLineEnd> = None;
let is_empty_buffer = state.buffer.is_empty();
// Track cursor position during rendering (eliminates duplicate line iteration)
let mut last_visible_x: u16 = 0;
let _view_start_line_skip = view_anchor.start_line_skip; // Currently unused
// Track the current source line number separately from display lines
let mut current_source_line_num = starting_line_num;
// Track whether the previous line was a source line (showed a line number)
// Used to determine when to increment the line counter
let mut prev_was_source_line = false;
loop {
// Get the current ViewLine from the pipeline
let current_view_line = if let Some(vl) = view_lines.get(view_iter_idx) {
vl
} else if is_empty_buffer && lines_rendered == 0 {
// Handle empty buffer case - create a minimal line
static EMPTY_LINE: std::sync::OnceLock<ViewLine> = std::sync::OnceLock::new();
EMPTY_LINE.get_or_init(|| ViewLine {
text: String::new(),
char_mappings: Vec::new(),
char_styles: Vec::new(),
tab_starts: HashSet::new(),
line_start: LineStart::Beginning,
ends_with_newline: false,
})
} else {
break;
};
// Extract line data
let line_content = current_view_line.text.clone();
let line_has_newline = current_view_line.ends_with_newline;
let line_char_mappings = ¤t_view_line.char_mappings;
let line_char_styles = ¤t_view_line.char_styles;
let line_tab_starts = ¤t_view_line.tab_starts;
let _line_start_type = current_view_line.line_start; // Available for future use
view_iter_idx += 1;
if lines_rendered >= visible_line_count {
break;
}
// Use the elegant pipeline's should_show_line_number function
// This correctly handles: injected content, wrapped continuations, and source lines
let show_line_number = should_show_line_number(current_view_line);
// Only increment source line number when BOTH:
// 1. We've already rendered at least one source line (prev_was_source_line)
// 2. The CURRENT line is also a source line
// This ensures virtual/injected lines don't cause line numbers to skip
if show_line_number && prev_was_source_line {
current_source_line_num += 1;
}
// Only update the flag when we see a source line - virtual lines
// between source lines shouldn't reset the tracking
if show_line_number {
prev_was_source_line = true;
}
// is_continuation means "don't show line number" for rendering purposes
let is_continuation = !show_line_number;
lines_rendered += 1;
// Apply horizontal scrolling - skip characters before left_column
let left_col = left_column;
// Build line with selection highlighting
let mut line_spans = Vec::new();
let mut line_view_map: Vec<Option<usize>> = Vec::new();
let mut last_seg_y: Option<u16> = None;
let mut _last_seg_width: usize = 0;
// Render left margin (indicators + line numbers + separator)
render_left_margin(
&LeftMarginContext {
state,
theme,
is_continuation,
current_source_line_num,
estimated_lines,
diagnostic_lines,
line_indicators,
},
&mut line_spans,
&mut line_view_map,
);
// Check if this line has any selected text
let mut char_index = 0;
let mut col_offset = 0usize;
// Performance optimization: For very long lines, only process visible characters
// Calculate the maximum characters we might need to render based on screen width
// For wrapped lines, we need enough characters to fill the visible viewport
// For non-wrapped lines, we only need one screen width worth
let visible_lines_remaining = visible_line_count.saturating_sub(lines_rendered);
let max_visible_chars = if line_wrap {
// With wrapping: might need chars for multiple wrapped lines
// Be generous to avoid cutting off wrapped content
(render_area.width as usize)
.saturating_mul(visible_lines_remaining.max(1))
.saturating_add(200)
} else {
// Without wrapping: only need one line worth of characters
(render_area.width as usize).saturating_add(100)
};
let max_chars_to_process = left_col.saturating_add(max_visible_chars);
// ANSI parser for this line to handle escape sequences
// Optimization: only create parser if line contains ESC byte
let line_has_ansi = line_content.contains('\x1b');
let mut ansi_parser = if line_has_ansi {
Some(AnsiParser::new())
} else {
None
};
// Track visible characters separately from byte position for ANSI handling
let mut visible_char_count = 0usize;
let mut chars_iterator = line_content.chars().peekable();
while let Some(ch) = chars_iterator.next() {
// Use per-line mappings instead of global view_mapping
let byte_pos = line_char_mappings.get(col_offset).copied().flatten();
// Process character through ANSI parser first (if line has ANSI)
// If parser returns None, the character is part of an escape sequence and should be skipped
let ansi_style = if let Some(ref mut parser) = ansi_parser {
match parser.parse_char(ch) {
Some(style) => style,
None => {
// This character is part of an ANSI escape sequence, skip it
// IMPORTANT: If the cursor is on this ANSI byte, track it
if let Some(bp) = byte_pos {
if bp == primary_cursor_position && !have_cursor {
cursor_screen_x =
gutter_width as u16 + visible_char_count as u16;
cursor_screen_y = lines_rendered.saturating_sub(1) as u16;
have_cursor = true;
}
}
char_index += ch.len_utf8();
col_offset += 1;
continue;
}
}
} else {
// No ANSI in this line - use default style (fast path)
Style::default()
};
// Performance: skip expensive style calculations for characters beyond visible range
// Use visible_char_count (not char_index) since ANSI codes don't take up visible space
if visible_char_count > max_chars_to_process {
// Fast path: just count remaining characters without processing
// This is critical for performance with very long lines (e.g., 100KB single line)
char_index += ch.len_utf8();
for remaining_ch in chars_iterator.by_ref() {
char_index += remaining_ch.len_utf8();
}
break;
}
// Skip characters before left_column
if col_offset >= left_col as usize {
// Check if this view position is the START of a tab expansion
let is_tab_start = line_tab_starts.contains(&col_offset);
// Check if this character is at a cursor position
// For tab expansions: only show cursor on the FIRST space (the tab_start position)
// This prevents cursor from appearing on all 8 expanded spaces
let is_cursor = byte_pos
.map(|bp| {
if !cursor_positions.contains(&bp) || bp >= state.buffer.len() {
return false;
}
// If this byte maps to a tab character, only show cursor at tab_start
// Check if this is part of a tab expansion by looking at surrounding positions
let prev_col_offset = col_offset.saturating_sub(1);
let prev_byte_pos =
line_char_mappings.get(prev_col_offset).copied().flatten();
// Show cursor if: this is start of line, OR previous char had different byte pos
col_offset == 0 || prev_byte_pos != Some(bp)
})
.unwrap_or(false);
// Check if this character is in any selection range (but not at cursor position)
// Also check for block/rectangular selections
let is_in_block_selection = block_selections.iter().any(
|(start_line, start_col, end_line, end_col)| {
current_source_line_num >= *start_line
&& current_source_line_num <= *end_line
&& char_index >= *start_col
&& char_index <= *end_col
},
);
let is_selected = !is_cursor
&& byte_pos.map_or(false, |bp| {
selection_ranges.iter().any(|range| range.contains(&bp))
})
|| (!is_cursor && is_in_block_selection);
// Compute character style using helper function
let token_style = line_char_styles.get(col_offset).and_then(|s| s.as_ref());
let CharStyleOutput {
style,
is_secondary_cursor,
} = compute_char_style(&CharStyleContext {
byte_pos,
token_style,
ansi_style,
is_cursor,
is_selected,
theme,
highlight_spans,
semantic_spans,
viewport_overlays,
primary_cursor_position,
is_active,
});
// Determine display character (tabs already expanded in ViewLineIterator)
// Show tab indicator (→) at the start of tab expansions
let tab_indicator: String;
let display_char: &str = if is_cursor && lsp_waiting && is_active {
"⋯"
} else if is_cursor && is_active && ch == '\n' {
""
} else if ch == '\n' {
""
} else if is_tab_start {
// Visual indicator for tab: show → at the first position
tab_indicator = "→".to_string();
&tab_indicator
} else {
tab_indicator = ch.to_string();
&tab_indicator
};
if let Some(bp) = byte_pos {
if let Some(vtexts) = virtual_text_lookup.get(&bp) {
for vtext in vtexts
.iter()
.filter(|v| v.position == VirtualTextPosition::BeforeChar)
{
let text_with_space = format!("{} ", vtext.text);
push_span_with_map(
&mut line_spans,
&mut line_view_map,
text_with_space,
vtext.style,
None,
);
}
}
}
if !display_char.is_empty() {
push_span_with_map(
&mut line_spans,
&mut line_view_map,
display_char.to_string(),
style,
byte_pos,
);
}
if let Some(bp) = byte_pos {
if let Some(vtexts) = virtual_text_lookup.get(&bp) {
for vtext in vtexts
.iter()
.filter(|v| v.position == VirtualTextPosition::AfterChar)
{
let text_with_space = format!(" {}", vtext.text);
push_span_with_map(
&mut line_spans,
&mut line_view_map,
text_with_space,
vtext.style,
None,
);
}
}
}
if is_cursor && ch == '\n' {
let should_add_indicator =
if is_active { is_secondary_cursor } else { true };
if should_add_indicator {
let cursor_style = if is_active {
Style::default()
.fg(theme.editor_fg)
.bg(theme.editor_bg)
.add_modifier(Modifier::REVERSED)
} else {
Style::default()
.fg(theme.editor_fg)
.bg(theme.inactive_cursor)
};
push_span_with_map(
&mut line_spans,
&mut line_view_map,
" ".to_string(),
cursor_style,
byte_pos,
);
}
}
}
char_index += ch.len_utf8();
col_offset += 1;
visible_char_count += 1;
}
// Set last_seg_y early so cursor detection works for both empty and non-empty lines
// For lines without wrapping, this will be the final y position
// Also set for empty content lines (regardless of line_wrap) so cursor at EOF can be positioned
let content_is_empty = line_content.is_empty();
if line_spans.is_empty() || !line_wrap || content_is_empty {
last_seg_y = Some(lines.len() as u16);
}
if !line_has_newline {
let line_len_chars = line_content.chars().count();
// Map view positions to buffer positions using per-line char_mappings
let last_char_idx = line_len_chars.saturating_sub(1);
let after_last_char_idx = line_len_chars;
let last_char_buf_pos = line_char_mappings.get(last_char_idx).copied().flatten();
let after_last_char_buf_pos = line_char_mappings
.get(after_last_char_idx)
.copied()
.flatten();
let cursor_at_end = cursor_positions.iter().any(|&pos| {
// Cursor is "at end" only if it's AFTER the last character, not ON it.
// A cursor ON the last character should render on that character (handled in main loop).
let matches_after = after_last_char_buf_pos.map_or(false, |bp| pos == bp);
// Fallback: when there's no mapping after last char (EOF), check if cursor is after last char
// The fallback should match the position that would be "after" if there was a mapping
let expected_after_pos = last_char_buf_pos.map(|p| p + 1).unwrap_or(0);
let matches_fallback =
after_last_char_buf_pos.is_none() && pos == expected_after_pos;
matches_after || matches_fallback
});
if cursor_at_end {
// Primary cursor is at end only if AFTER the last char, not ON it
let is_primary_at_end = after_last_char_buf_pos
.map_or(false, |bp| bp == primary_cursor_position)
|| (after_last_char_buf_pos.is_none()
&& primary_cursor_position >= state.buffer.len());
// Track cursor position for primary cursor
if is_primary_at_end && last_seg_y.is_some() {
// Cursor position now includes gutter width (consistent with main cursor tracking)
// For empty lines, cursor is at gutter width (right after gutter)
// For non-empty lines without newline, cursor is after the last character
cursor_screen_x = if line_len_chars == 0 {
gutter_width as u16
} else {
gutter_width as u16 + line_len_chars as u16
};
cursor_screen_y = last_seg_y.unwrap();
have_cursor = true;
}
let should_add_indicator = if is_active { !is_primary_at_end } else { true };
if should_add_indicator {
let cursor_style = if is_active {
Style::default()
.fg(theme.editor_fg)
.bg(theme.editor_bg)
.add_modifier(Modifier::REVERSED)
} else {
Style::default()
.fg(theme.editor_fg)
.bg(theme.inactive_cursor)
};
push_span_with_map(
&mut line_spans,
&mut line_view_map,
" ".to_string(),
cursor_style,
None,
);
}
}
}
// ViewLines are already wrapped (Break tokens became newlines in ViewLineIterator)
// so each line is one visual line - no need to wrap again
let current_y = lines.len() as u16;
last_seg_y = Some(current_y);
if !line_spans.is_empty() {
// Find cursor position and track last visible x by iterating through line_view_map
// Note: line_view_map includes both gutter and content character mappings
for (screen_x, source_offset) in line_view_map.iter().enumerate() {
if let Some(src) = source_offset {
// Check if this is the primary cursor position
// Only set cursor on the FIRST screen position that maps to cursor byte
// (important for tabs where multiple spaces map to same byte)
if *src == primary_cursor_position && !have_cursor {
cursor_screen_x = screen_x as u16;
cursor_screen_y = current_y;
have_cursor = true;
}
// Track the last visible position (rightmost character with a source mapping)
// This is used for EOF cursor placement
last_visible_x = screen_x as u16;
}
}
}
// Track if line was empty before moving line_spans
let line_was_empty = line_spans.is_empty();
lines.push(Line::from(line_spans));
// Update last_line_end and check for cursor on newline BEFORE the break check
// This ensures the last visible line's metadata is captured
if let Some(y) = last_seg_y {
// end_x is the cursor position after the last visible character.
// For empty lines, last_visible_x stays at 0, so we need to ensure end_x is
// at least gutter_width to place the cursor after the gutter, not in it.
let end_x = if line_was_empty {
gutter_width as u16
} else {
last_visible_x.saturating_add(1)
};
let line_len_chars = line_content.chars().count();
last_line_end = Some(LastLineEnd {
pos: (end_x, y),
terminated_with_newline: line_has_newline,
});
if line_has_newline && line_len_chars > 0 {
let newline_idx = line_len_chars.saturating_sub(1);
if let Some(Some(src_newline)) = line_char_mappings.get(newline_idx) {
if *src_newline == primary_cursor_position {
// Cursor position now includes gutter width (consistent with main cursor tracking)
// For empty lines (just newline), cursor should be at gutter width (after gutter)
// For lines with content, cursor on newline should be after the content
if line_len_chars == 1 {
// Empty line - just the newline character
cursor_screen_x = gutter_width as u16;
cursor_screen_y = y;
} else {
// Line has content before the newline - cursor after last char
// end_x already includes gutter (from last_visible_x)
cursor_screen_x = end_x;
cursor_screen_y = y;
}
have_cursor = true;
}
}
}
}
if lines_rendered >= visible_line_count {
break;
}
}
// If the last line ended with a newline, render an implicit empty line after it.
// This shows the line number for the cursor position after the final newline.
if let Some(ref end) = last_line_end {
if end.terminated_with_newline && lines_rendered < visible_line_count {
// Render the implicit line after the newline
let mut implicit_line_spans = Vec::new();
let implicit_line_num = current_source_line_num + 1;
if state.margins.left_config.enabled {
// Indicator column (space)
implicit_line_spans.push(Span::styled(" ", Style::default()));
// Line number
let estimated_lines = (state.buffer.len() / 80).max(1);
let margin_content = state.margins.render_line(
implicit_line_num,
crate::view::margin::MarginPosition::Left,
estimated_lines,
);
let (rendered_text, style_opt) =
margin_content.render(state.margins.left_config.width);
let margin_style =
style_opt.unwrap_or_else(|| Style::default().fg(theme.line_number_fg));
implicit_line_spans.push(Span::styled(rendered_text, margin_style));
// Separator
if state.margins.left_config.show_separator {
implicit_line_spans.push(Span::styled(
state.margins.left_config.separator.to_string(),
Style::default().fg(theme.line_number_fg),
));
}
}
let implicit_y = lines.len() as u16;
lines.push(Line::from(implicit_line_spans));
lines_rendered += 1;
// NOTE: We intentionally do NOT update last_line_end here.
// The implicit empty line is a visual display aid, not an actual content line.
// last_line_end should track the last actual content line for cursor placement logic.
// If primary cursor is at EOF (after the newline), set cursor on this line
if primary_cursor_position == state.buffer.len() && !have_cursor {
cursor_screen_x = gutter_width as u16;
cursor_screen_y = implicit_y;
have_cursor = true;
}
}
}
// Fill remaining rows with tilde characters to indicate EOF (like vim/neovim).
// This also ensures proper clearing in differential rendering because tildes
// are guaranteed to differ from previous content, forcing ratatui to update.
// See: https://github.com/ratatui/ratatui/issues/1606
let eof_style = Style::default()
.fg(theme.line_number_fg)
.add_modifier(ratatui::style::Modifier::DIM);
while lines.len() < render_area.height as usize {
// Show tilde with dim styling, padded with spaces to fill the line
let tilde_line = format!(
"~{}",
" ".repeat(render_area.width.saturating_sub(1) as usize)
);
lines.push(Line::styled(tilde_line, eof_style));
}
LineRenderOutput {
lines,
cursor: have_cursor.then_some((cursor_screen_x, cursor_screen_y)),
last_line_end,
content_lines_rendered: lines_rendered,
}
}
fn resolve_cursor_fallback(
current_cursor: Option<(u16, u16)>,
primary_cursor_position: usize,
buffer_len: usize,
buffer_ends_with_newline: bool,
last_line_end: Option<LastLineEnd>,
lines_rendered: usize,
gutter_width: usize,
) -> Option<(u16, u16)> {
if current_cursor.is_some() || primary_cursor_position != buffer_len {
return current_cursor;
}
if buffer_ends_with_newline {
if let Some(end) = last_line_end {
// Cursor should appear on the implicit empty line after the newline
// Include gutter width in x coordinate
return Some((gutter_width as u16, end.pos.1.saturating_add(1)));
}
return Some((gutter_width as u16, lines_rendered as u16));
}
last_line_end.map(|end| end.pos)
}
/// Render a single buffer in a split pane
/// Returns the view line mappings for mouse click handling
fn render_buffer_in_split(
frame: &mut Frame,
state: &mut EditorState,
viewport: &mut crate::view::viewport::Viewport,
event_log: Option<&mut EventLog>,
area: Rect,
is_active: bool,
theme: &crate::view::theme::Theme,
ansi_background: Option<&AnsiBackground>,
background_fade: f32,
lsp_waiting: bool,
view_mode: ViewMode,
compose_width: Option<u16>,
compose_column_guides: Option<Vec<u16>>,
view_transform: Option<ViewTransformPayload>,
estimated_line_length: usize,
highlight_context_bytes: usize,
_buffer_id: BufferId,
hide_cursor: bool,
) -> Vec<ViewLineMapping> {
let _span = tracing::trace_span!("render_buffer_in_split").entered();
let line_wrap = viewport.line_wrap_enabled;
let overlay_count = state.overlays.all().len();
if overlay_count > 0 {
tracing::trace!("render_content: {} overlays present", overlay_count);
}
let visible_count = viewport.visible_line_count();
let buffer_len = state.buffer.len();
let estimated_lines = (buffer_len / 80).max(1);
state.margins.update_width_for_buffer(estimated_lines);
let gutter_width = state.margins.left_total_width();
let compose_layout = Self::calculate_compose_layout(area, &view_mode, compose_width);
let render_area = compose_layout.render_area;
// Clone view_transform so we can reuse it if scrolling triggers a rebuild
let view_transform_for_rebuild = view_transform.clone();
let view_data = Self::build_view_data(
state,
viewport,
view_transform,
estimated_line_length,
visible_count,
line_wrap,
render_area.width as usize,
gutter_width,
);
// Ensure cursor is visible using Layout-aware check (handles virtual lines)
// This detects when cursor is beyond the rendered view_lines and scrolls
let primary = *state.cursors.primary();
let scrolled = viewport.ensure_visible_in_layout(&view_data.lines, &primary, gutter_width);
// If we scrolled, rebuild view_data from new position WITH the view_transform
// This ensures virtual lines are included in the rebuilt view
let view_data = if scrolled {
Self::build_view_data(
state,
viewport,
view_transform_for_rebuild,
estimated_line_length,
visible_count,
line_wrap,
render_area.width as usize,
gutter_width,
)
} else {
view_data
};
let view_anchor = Self::calculate_view_anchor(&view_data.lines, viewport.top_byte);
Self::render_compose_margins(frame, area, &compose_layout, &view_mode, theme);
let selection = Self::selection_context(state);
tracing::trace!(
"Rendering buffer with {} cursors at positions: {:?}, primary at {}, is_active: {}, buffer_len: {}",
selection.cursor_positions.len(),
selection.cursor_positions,
selection.primary_cursor_position,
is_active,
state.buffer.len()
);
if !selection
.cursor_positions
.contains(&selection.primary_cursor_position)
{
tracing::warn!(
"Primary cursor position {} not found in cursor_positions list: {:?}",
selection.primary_cursor_position,
selection.cursor_positions
);
}
let starting_line_num = state
.buffer
.populate_line_cache(viewport.top_byte, visible_count);
let viewport_start = viewport.top_byte;
let viewport_end = Self::calculate_viewport_end(
state,
viewport_start,
estimated_line_length,
visible_count,
);
let decorations = Self::decoration_context(
state,
viewport_start,
viewport_end,
selection.primary_cursor_position,
theme,
highlight_context_bytes,
);
// Apply top_view_line_offset to skip virtual lines when scrolling through them
let view_line_offset = viewport.top_view_line_offset;
let view_lines_to_render =
if view_line_offset > 0 && view_line_offset < view_data.lines.len() {
&view_data.lines[view_line_offset..]
} else {
&view_data.lines
};
let render_output = Self::render_view_lines(LineRenderInput {
state,
theme,
view_lines: view_lines_to_render,
view_anchor,
render_area,
gutter_width,
selection: &selection,
decorations: &decorations,
starting_line_num,
visible_line_count: visible_count,
lsp_waiting,
is_active,
line_wrap,
estimated_lines,
left_column: viewport.left_column,
});
let mut lines = render_output.lines;
let background_x_offset = viewport.left_column as usize;
if let Some(bg) = ansi_background {
Self::apply_background_to_lines(
&mut lines,
render_area.width,
bg,
theme.editor_bg,
theme.editor_fg,
background_fade,
background_x_offset,
starting_line_num,
);
}
frame.render_widget(Clear, render_area);
let editor_block = Block::default()
.borders(Borders::NONE)
.style(Style::default().bg(theme.editor_bg));
frame.render_widget(Paragraph::new(lines).block(editor_block), render_area);
// Render column guides if present (for tables, etc.)
if let Some(guides) = compose_column_guides {
let guide_style = Style::default()
.fg(theme.line_number_fg)
.add_modifier(Modifier::DIM);
let guide_height = render_output
.content_lines_rendered
.min(render_area.height as usize);
for col in guides {
// Column guides are relative to content area (after gutter)
let guide_x = render_area.x + gutter_width as u16 + col;
// Only draw if the guide is within the visible area
if guide_x >= render_area.x && guide_x < render_area.x + render_area.width {
for row in 0..guide_height {
let cell_area = Rect::new(guide_x, render_area.y + row as u16, 1, 1);
let guide_char = Paragraph::new("│").style(guide_style);
frame.render_widget(guide_char, cell_area);
}
}
}
}
let buffer_ends_with_newline = if state.buffer.len() > 0 {
let last_char = state.get_text_range(state.buffer.len() - 1, state.buffer.len());
last_char == "\n"
} else {
false
};
let cursor = Self::resolve_cursor_fallback(
render_output.cursor,
selection.primary_cursor_position,
state.buffer.len(),
buffer_ends_with_newline,
render_output.last_line_end,
render_output.content_lines_rendered,
gutter_width,
);
if is_active && state.show_cursors && !hide_cursor {
if let Some((cursor_screen_x, cursor_screen_y)) = cursor {
// cursor_screen_x already includes gutter width from line_view_map
let screen_x = render_area.x.saturating_add(cursor_screen_x);
let screen_y = render_area.y.saturating_add(cursor_screen_y);
frame.set_cursor_position((screen_x, screen_y));
if let Some(event_log) = event_log {
let cursor_pos = state.cursors.primary().position;
let buffer_len = state.buffer.len();
event_log.log_render_state(cursor_pos, screen_x, screen_y, buffer_len);
}
}
}
// Extract view line mappings for mouse click handling
// This maps screen coordinates to buffer byte positions
Self::extract_view_line_mappings(view_lines_to_render)
}
/// Extract ViewLineMapping from rendered view lines
/// This captures the char_mappings from each ViewLine for accurate mouse click positioning
fn extract_view_line_mappings(view_lines: &[ViewLine]) -> Vec<ViewLineMapping> {
view_lines
.iter()
.map(|vl| {
// line_end_byte is the last valid mapping in char_mappings.
// For lines ending with newline, this IS the newline position.
// For wrapped continuations, this is the last char before the wrap.
let line_end_byte = vl
.char_mappings
.iter()
.filter_map(|m| *m)
.last()
.unwrap_or(0);
ViewLineMapping {
char_mappings: vl.char_mappings.clone(),
line_end_byte,
}
})
.collect()
}
/// Apply styles from original line_spans to a wrapped segment
///
/// Maps each character in the segment text back to its original span to preserve
/// syntax highlighting, selections, and other styling across wrapped lines.
///
/// # Arguments
/// * `segment_text` - The text content of this wrapped segment
/// * `line_spans` - The original styled spans for the entire line
/// * `segment_start_offset` - Character offset where this segment starts in the original line
/// * `scroll_offset` - Additional offset for horizontal scrolling (non-wrap mode)
fn apply_background_to_lines(
lines: &mut Vec<Line<'static>>,
area_width: u16,
background: &AnsiBackground,
theme_bg: Color,
default_fg: Color,
fade: f32,
x_offset: usize,
y_offset: usize,
) {
if area_width == 0 {
return;
}
let width = area_width as usize;
for (y, line) in lines.iter_mut().enumerate() {
// Flatten existing spans into per-character styles
let mut existing: Vec<(char, Style)> = Vec::new();
let spans = std::mem::take(&mut line.spans);
for span in spans {
let style = span.style;
for ch in span.content.chars() {
existing.push((ch, style));
}
}
let mut chars_with_style = Vec::with_capacity(width);
for x in 0..width {
let sample_x = x_offset + x;
let sample_y = y_offset + y;
let (ch, mut style) = if x < existing.len() {
existing[x]
} else {
(' ', Style::default().fg(default_fg))
};
if let Some(bg_color) = background.faded_color(sample_x, sample_y, theme_bg, fade) {
if style.bg.is_none() || matches!(style.bg, Some(Color::Reset)) {
style = style.bg(bg_color);
}
}
chars_with_style.push((ch, style));
}
line.spans = Self::compress_chars(chars_with_style);
}
}
fn compress_chars(chars: Vec<(char, Style)>) -> Vec<Span<'static>> {
if chars.is_empty() {
return vec![];
}
let mut spans = Vec::new();
let mut current_style = chars[0].1;
let mut current_text = String::new();
current_text.push(chars[0].0);
for (ch, style) in chars.into_iter().skip(1) {
if style == current_style {
current_text.push(ch);
} else {
spans.push(Span::styled(current_text.clone(), current_style));
current_text.clear();
current_text.push(ch);
current_style = style;
}
}
spans.push(Span::styled(current_text, current_style));
spans
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::buffer::Buffer;
use crate::view::theme::Theme;
use crate::view::viewport::Viewport;
fn render_output_for(
content: &str,
cursor_pos: usize,
) -> (LineRenderOutput, usize, bool, usize) {
render_output_for_with_gutters(content, cursor_pos, false)
}
fn render_output_for_with_gutters(
content: &str,
cursor_pos: usize,
gutters_enabled: bool,
) -> (LineRenderOutput, usize, bool, usize) {
let mut state = EditorState::new(20, 6, 1024);
state.buffer = Buffer::from_str(content, 1024);
state.cursors.primary_mut().position = cursor_pos.min(state.buffer.len());
// Create a standalone viewport (no longer part of EditorState)
let mut viewport = Viewport::new(20, 4);
// Enable/disable line numbers/gutters based on parameter
state.margins.left_config.enabled = gutters_enabled;
let render_area = Rect::new(0, 0, 20, 4);
let visible_count = viewport.visible_line_count();
let gutter_width = state.margins.left_total_width();
let view_data = SplitRenderer::build_view_data(
&mut state,
&viewport,
None,
content.len().max(1),
visible_count,
false, // line wrap disabled for tests
render_area.width as usize,
gutter_width,
);
let view_anchor = SplitRenderer::calculate_view_anchor(&view_data.lines, 0);
let estimated_lines = (state.buffer.len() / 80).max(1);
state.margins.update_width_for_buffer(estimated_lines);
let gutter_width = state.margins.left_total_width();
let selection = SplitRenderer::selection_context(&state);
let starting_line_num = state
.buffer
.populate_line_cache(viewport.top_byte, visible_count);
let viewport_start = viewport.top_byte;
let viewport_end = SplitRenderer::calculate_viewport_end(
&mut state,
viewport_start,
content.len().max(1),
visible_count,
);
let theme = Theme::default();
let decorations = SplitRenderer::decoration_context(
&mut state,
viewport_start,
viewport_end,
selection.primary_cursor_position,
&theme,
100_000, // default highlight context bytes
);
let output = SplitRenderer::render_view_lines(LineRenderInput {
state: &state,
theme: &theme,
view_lines: &view_data.lines,
view_anchor,
render_area,
gutter_width,
selection: &selection,
decorations: &decorations,
starting_line_num,
visible_line_count: visible_count,
lsp_waiting: false,
is_active: true,
line_wrap: viewport.line_wrap_enabled,
estimated_lines,
left_column: viewport.left_column,
});
(
output,
state.buffer.len(),
content.ends_with('\n'),
selection.primary_cursor_position,
)
}
#[test]
fn last_line_end_tracks_trailing_newline() {
let output = render_output_for("abc\n", 4);
assert_eq!(
output.0.last_line_end,
Some(LastLineEnd {
pos: (3, 0),
terminated_with_newline: true
})
);
}
#[test]
fn last_line_end_tracks_no_trailing_newline() {
let output = render_output_for("abc", 3);
assert_eq!(
output.0.last_line_end,
Some(LastLineEnd {
pos: (3, 0),
terminated_with_newline: false
})
);
}
#[test]
fn cursor_after_newline_places_on_next_line() {
let (output, buffer_len, buffer_newline, cursor_pos) = render_output_for("abc\n", 4);
let cursor = SplitRenderer::resolve_cursor_fallback(
output.cursor,
cursor_pos,
buffer_len,
buffer_newline,
output.last_line_end,
output.content_lines_rendered,
0, // gutter_width (gutters disabled in tests)
);
assert_eq!(cursor, Some((0, 1)));
}
#[test]
fn cursor_at_end_without_newline_stays_on_line() {
let (output, buffer_len, buffer_newline, cursor_pos) = render_output_for("abc", 3);
let cursor = SplitRenderer::resolve_cursor_fallback(
output.cursor,
cursor_pos,
buffer_len,
buffer_newline,
output.last_line_end,
output.content_lines_rendered,
0, // gutter_width (gutters disabled in tests)
);
assert_eq!(cursor, Some((3, 0)));
}
// Helper to count all cursor positions in rendered output
// Cursors can appear as:
// 1. Primary cursor in output.cursor (hardware cursor position)
// 2. Visual spans with REVERSED modifier (secondary cursors)
// 3. Visual spans with special background color (inactive cursors)
fn count_all_cursors(output: &LineRenderOutput) -> Vec<(u16, u16)> {
let mut cursor_positions = Vec::new();
// Check for primary cursor in output.cursor field
if let Some(cursor_pos) = output.cursor {
cursor_positions.push(cursor_pos);
}
// Check for visual cursor indicators in rendered spans (secondary/inactive cursors)
for (line_idx, line) in output.lines.iter().enumerate() {
let mut col = 0u16;
for span in line.spans.iter() {
// Check if this span has the REVERSED modifier (secondary cursor)
if span
.style
.add_modifier
.contains(ratatui::style::Modifier::REVERSED)
{
// Found a visual cursor - record its position
cursor_positions.push((col, line_idx as u16));
}
// Count the width of this span's content
col += span.content.chars().count() as u16;
}
}
cursor_positions
}
// Helper to dump rendered output for debugging
fn dump_render_output(content: &str, cursor_pos: usize, output: &LineRenderOutput) {
eprintln!("\n=== RENDER DEBUG ===");
eprintln!("Content: {:?}", content);
eprintln!("Cursor position: {}", cursor_pos);
eprintln!("Hardware cursor (output.cursor): {:?}", output.cursor);
eprintln!("Last line end: {:?}", output.last_line_end);
eprintln!("Content lines rendered: {}", output.content_lines_rendered);
eprintln!("\nRendered lines:");
for (line_idx, line) in output.lines.iter().enumerate() {
eprintln!(" Line {}: {} spans", line_idx, line.spans.len());
for (span_idx, span) in line.spans.iter().enumerate() {
let has_reversed = span
.style
.add_modifier
.contains(ratatui::style::Modifier::REVERSED);
let bg_color = format!("{:?}", span.style.bg);
eprintln!(
" Span {}: {:?} (REVERSED: {}, BG: {})",
span_idx, span.content, has_reversed, bg_color
);
}
}
eprintln!("===================\n");
}
// Helper to get final cursor position after fallback resolution
// Also validates that exactly one cursor is present
fn get_final_cursor(content: &str, cursor_pos: usize) -> Option<(u16, u16)> {
let (output, buffer_len, buffer_newline, cursor_pos) =
render_output_for(content, cursor_pos);
// Count all cursors (hardware + visual) in the rendered output
let all_cursors = count_all_cursors(&output);
// Validate that at most one cursor is present in rendered output
// (Some cursors are added by fallback logic, not during rendering)
assert!(
all_cursors.len() <= 1,
"Expected at most 1 cursor in rendered output, found {} at positions: {:?}",
all_cursors.len(),
all_cursors
);
let final_cursor = SplitRenderer::resolve_cursor_fallback(
output.cursor,
cursor_pos,
buffer_len,
buffer_newline,
output.last_line_end,
output.content_lines_rendered,
0, // gutter_width (gutters disabled in tests)
);
// Debug dump if we find unexpected results
if all_cursors.len() > 1 || (all_cursors.len() == 1 && Some(all_cursors[0]) != final_cursor)
{
dump_render_output(content, cursor_pos, &output);
}
// If a cursor was rendered, it should match the final cursor position
if let Some(rendered_cursor) = all_cursors.first() {
assert_eq!(
Some(*rendered_cursor),
final_cursor,
"Rendered cursor at {:?} doesn't match final cursor {:?}",
rendered_cursor,
final_cursor
);
}
// Validate that we have a final cursor position (either rendered or from fallback)
assert!(
final_cursor.is_some(),
"Expected a final cursor position, but got None. Rendered cursors: {:?}",
all_cursors
);
final_cursor
}
// Helper to simulate typing a character and check if it appears at cursor position
fn check_typing_at_cursor(
content: &str,
cursor_pos: usize,
char_to_type: char,
) -> (Option<(u16, u16)>, String) {
// Get cursor position before typing
let cursor_before = get_final_cursor(content, cursor_pos);
// Simulate inserting the character at cursor position
let mut new_content = content.to_string();
if cursor_pos <= content.len() {
new_content.insert(cursor_pos, char_to_type);
}
(cursor_before, new_content)
}
#[test]
fn e2e_cursor_at_start_of_nonempty_line() {
// "abc" with cursor at position 0 (before 'a')
let cursor = get_final_cursor("abc", 0);
assert_eq!(cursor, Some((0, 0)), "Cursor should be at column 0, line 0");
let (cursor_pos, new_content) = check_typing_at_cursor("abc", 0, 'X');
assert_eq!(
new_content, "Xabc",
"Typing should insert at cursor position"
);
assert_eq!(cursor_pos, Some((0, 0)));
}
#[test]
fn e2e_cursor_in_middle_of_line() {
// "abc" with cursor at position 1 (on 'b')
let cursor = get_final_cursor("abc", 1);
assert_eq!(cursor, Some((1, 0)), "Cursor should be at column 1, line 0");
let (cursor_pos, new_content) = check_typing_at_cursor("abc", 1, 'X');
assert_eq!(
new_content, "aXbc",
"Typing should insert at cursor position"
);
assert_eq!(cursor_pos, Some((1, 0)));
}
#[test]
fn e2e_cursor_at_end_of_line_no_newline() {
// "abc" with cursor at position 3 (after 'c', at EOF)
let cursor = get_final_cursor("abc", 3);
assert_eq!(
cursor,
Some((3, 0)),
"Cursor should be at column 3, line 0 (after last char)"
);
let (cursor_pos, new_content) = check_typing_at_cursor("abc", 3, 'X');
assert_eq!(new_content, "abcX", "Typing should append at end");
assert_eq!(cursor_pos, Some((3, 0)));
}
#[test]
fn e2e_cursor_at_empty_line() {
// "\n" with cursor at position 0 (on the newline itself)
let cursor = get_final_cursor("\n", 0);
assert_eq!(
cursor,
Some((0, 0)),
"Cursor on empty line should be at column 0"
);
let (cursor_pos, new_content) = check_typing_at_cursor("\n", 0, 'X');
assert_eq!(new_content, "X\n", "Typing should insert before newline");
assert_eq!(cursor_pos, Some((0, 0)));
}
#[test]
fn e2e_cursor_after_newline_at_eof() {
// "abc\n" with cursor at position 4 (after newline, at EOF)
let cursor = get_final_cursor("abc\n", 4);
assert_eq!(
cursor,
Some((0, 1)),
"Cursor after newline at EOF should be on next line"
);
let (cursor_pos, new_content) = check_typing_at_cursor("abc\n", 4, 'X');
assert_eq!(new_content, "abc\nX", "Typing should insert on new line");
assert_eq!(cursor_pos, Some((0, 1)));
}
#[test]
fn e2e_cursor_on_newline_with_content() {
// "abc\n" with cursor at position 3 (on the newline character)
let cursor = get_final_cursor("abc\n", 3);
assert_eq!(
cursor,
Some((3, 0)),
"Cursor on newline after content should be after last char"
);
let (cursor_pos, new_content) = check_typing_at_cursor("abc\n", 3, 'X');
assert_eq!(new_content, "abcX\n", "Typing should insert before newline");
assert_eq!(cursor_pos, Some((3, 0)));
}
#[test]
fn e2e_cursor_multiline_start_of_second_line() {
// "abc\ndef" with cursor at position 4 (start of second line, on 'd')
let cursor = get_final_cursor("abc\ndef", 4);
assert_eq!(
cursor,
Some((0, 1)),
"Cursor at start of second line should be at column 0, line 1"
);
let (cursor_pos, new_content) = check_typing_at_cursor("abc\ndef", 4, 'X');
assert_eq!(
new_content, "abc\nXdef",
"Typing should insert at start of second line"
);
assert_eq!(cursor_pos, Some((0, 1)));
}
#[test]
fn e2e_cursor_multiline_end_of_first_line() {
// "abc\ndef" with cursor at position 3 (on newline of first line)
let cursor = get_final_cursor("abc\ndef", 3);
assert_eq!(
cursor,
Some((3, 0)),
"Cursor on newline of first line should be after content"
);
let (cursor_pos, new_content) = check_typing_at_cursor("abc\ndef", 3, 'X');
assert_eq!(
new_content, "abcX\ndef",
"Typing should insert before newline"
);
assert_eq!(cursor_pos, Some((3, 0)));
}
#[test]
fn e2e_cursor_empty_buffer() {
// Empty buffer with cursor at position 0
let cursor = get_final_cursor("", 0);
assert_eq!(
cursor,
Some((0, 0)),
"Cursor in empty buffer should be at origin"
);
let (cursor_pos, new_content) = check_typing_at_cursor("", 0, 'X');
assert_eq!(
new_content, "X",
"Typing in empty buffer should insert character"
);
assert_eq!(cursor_pos, Some((0, 0)));
}
#[test]
fn e2e_cursor_empty_buffer_with_gutters() {
// Empty buffer with cursor at position 0, with gutters enabled
// The cursor should be positioned at the gutter width (right after the gutter),
// NOT at column 0 (which would be in the gutter area)
let (output, buffer_len, buffer_newline, cursor_pos) =
render_output_for_with_gutters("", 0, true);
// With gutters enabled, the gutter width should be > 0
// Default gutter includes: 1 char indicator + line number width + separator
// For a 1-line buffer, line number width is typically 1 digit + padding
let gutter_width = {
let mut state = EditorState::new(20, 6, 1024);
state.margins.left_config.enabled = true;
state.margins.update_width_for_buffer(1);
state.margins.left_total_width()
};
assert!(gutter_width > 0, "Gutter width should be > 0 when enabled");
// CRITICAL: Check the RENDERED cursor position directly from output.cursor
// This is what the terminal will actually use for cursor positioning
// The cursor should be rendered at gutter_width, not at 0
assert_eq!(
output.cursor,
Some((gutter_width as u16, 0)),
"RENDERED cursor in empty buffer should be at gutter_width ({}), got {:?}",
gutter_width,
output.cursor
);
let final_cursor = SplitRenderer::resolve_cursor_fallback(
output.cursor,
cursor_pos,
buffer_len,
buffer_newline,
output.last_line_end,
output.content_lines_rendered,
gutter_width,
);
// Cursor should be at (gutter_width, 0) - right after the gutter on line 0
assert_eq!(
final_cursor,
Some((gutter_width as u16, 0)),
"Cursor in empty buffer with gutters should be at gutter_width, not column 0"
);
}
#[test]
fn e2e_cursor_between_empty_lines() {
// "\n\n" with cursor at position 1 (on second newline)
let cursor = get_final_cursor("\n\n", 1);
assert_eq!(cursor, Some((0, 1)), "Cursor on second empty line");
let (cursor_pos, new_content) = check_typing_at_cursor("\n\n", 1, 'X');
assert_eq!(new_content, "\nX\n", "Typing should insert on second line");
assert_eq!(cursor_pos, Some((0, 1)));
}
#[test]
fn e2e_cursor_at_eof_after_multiple_lines() {
// "abc\ndef\nghi" with cursor at position 11 (at EOF, no trailing newline)
let cursor = get_final_cursor("abc\ndef\nghi", 11);
assert_eq!(
cursor,
Some((3, 2)),
"Cursor at EOF after 'i' should be at column 3, line 2"
);
let (cursor_pos, new_content) = check_typing_at_cursor("abc\ndef\nghi", 11, 'X');
assert_eq!(new_content, "abc\ndef\nghiX", "Typing should append at end");
assert_eq!(cursor_pos, Some((3, 2)));
}
#[test]
fn e2e_cursor_at_eof_with_trailing_newline() {
// "abc\ndef\nghi\n" with cursor at position 12 (after trailing newline)
let cursor = get_final_cursor("abc\ndef\nghi\n", 12);
assert_eq!(
cursor,
Some((0, 3)),
"Cursor after trailing newline should be on line 3"
);
let (cursor_pos, new_content) = check_typing_at_cursor("abc\ndef\nghi\n", 12, 'X');
assert_eq!(
new_content, "abc\ndef\nghi\nX",
"Typing should insert on new line"
);
assert_eq!(cursor_pos, Some((0, 3)));
}
#[test]
fn e2e_jump_to_end_of_buffer_no_trailing_newline() {
// Simulate Ctrl+End: jump from start to end of buffer without trailing newline
let content = "abc\ndef\nghi";
// Start at position 0
let cursor_at_start = get_final_cursor(content, 0);
assert_eq!(cursor_at_start, Some((0, 0)), "Cursor starts at beginning");
// Jump to EOF (position 11, after 'i')
let cursor_at_eof = get_final_cursor(content, 11);
assert_eq!(
cursor_at_eof,
Some((3, 2)),
"After Ctrl+End, cursor at column 3, line 2"
);
// Type a character at EOF
let (cursor_before_typing, new_content) = check_typing_at_cursor(content, 11, 'X');
assert_eq!(cursor_before_typing, Some((3, 2)));
assert_eq!(new_content, "abc\ndef\nghiX", "Character appended at end");
// Verify cursor position in the new content
let cursor_after_typing = get_final_cursor(&new_content, 12);
assert_eq!(
cursor_after_typing,
Some((4, 2)),
"After typing, cursor moved to column 4"
);
// Move cursor to start of buffer - verify cursor is no longer at end
let cursor_moved_away = get_final_cursor(&new_content, 0);
assert_eq!(cursor_moved_away, Some((0, 0)), "Cursor moved to start");
// The cursor should NOT be at the end anymore - verify by rendering without cursor at end
// This implicitly tests that only one cursor is rendered
}
#[test]
fn e2e_jump_to_end_of_buffer_with_trailing_newline() {
// Simulate Ctrl+End: jump from start to end of buffer WITH trailing newline
let content = "abc\ndef\nghi\n";
// Start at position 0
let cursor_at_start = get_final_cursor(content, 0);
assert_eq!(cursor_at_start, Some((0, 0)), "Cursor starts at beginning");
// Jump to EOF (position 12, after trailing newline)
let cursor_at_eof = get_final_cursor(content, 12);
assert_eq!(
cursor_at_eof,
Some((0, 3)),
"After Ctrl+End, cursor at column 0, line 3 (new line)"
);
// Type a character at EOF
let (cursor_before_typing, new_content) = check_typing_at_cursor(content, 12, 'X');
assert_eq!(cursor_before_typing, Some((0, 3)));
assert_eq!(
new_content, "abc\ndef\nghi\nX",
"Character inserted on new line"
);
// After typing, the cursor should move forward
let cursor_after_typing = get_final_cursor(&new_content, 13);
assert_eq!(
cursor_after_typing,
Some((1, 3)),
"After typing, cursor should be at column 1, line 3"
);
// Move cursor to middle of buffer - verify cursor is no longer at end
let cursor_moved_away = get_final_cursor(&new_content, 4);
assert_eq!(
cursor_moved_away,
Some((0, 1)),
"Cursor moved to start of line 1 (position 4 = start of 'def')"
);
}
#[test]
fn e2e_jump_to_end_of_empty_buffer() {
// Edge case: Ctrl+End in empty buffer should stay at (0,0)
let content = "";
let cursor_at_eof = get_final_cursor(content, 0);
assert_eq!(
cursor_at_eof,
Some((0, 0)),
"Empty buffer: cursor at origin"
);
// Type a character
let (cursor_before_typing, new_content) = check_typing_at_cursor(content, 0, 'X');
assert_eq!(cursor_before_typing, Some((0, 0)));
assert_eq!(new_content, "X", "Character inserted");
// Verify cursor after typing
let cursor_after_typing = get_final_cursor(&new_content, 1);
assert_eq!(
cursor_after_typing,
Some((1, 0)),
"After typing, cursor at column 1"
);
// Move cursor back to start - verify cursor is no longer at end
let cursor_moved_away = get_final_cursor(&new_content, 0);
assert_eq!(
cursor_moved_away,
Some((0, 0)),
"Cursor moved back to start"
);
}
#[test]
fn e2e_jump_to_end_of_single_empty_line() {
// Edge case: buffer with just a newline
let content = "\n";
// Position 0 is ON the newline
let cursor_on_newline = get_final_cursor(content, 0);
assert_eq!(
cursor_on_newline,
Some((0, 0)),
"Cursor on the newline character"
);
// Position 1 is AFTER the newline (EOF)
let cursor_at_eof = get_final_cursor(content, 1);
assert_eq!(
cursor_at_eof,
Some((0, 1)),
"After Ctrl+End, cursor on line 1"
);
// Type at EOF
let (cursor_before_typing, new_content) = check_typing_at_cursor(content, 1, 'X');
assert_eq!(cursor_before_typing, Some((0, 1)));
assert_eq!(new_content, "\nX", "Character on second line");
let cursor_after_typing = get_final_cursor(&new_content, 2);
assert_eq!(
cursor_after_typing,
Some((1, 1)),
"After typing, cursor at column 1, line 1"
);
// Move cursor to the newline - verify cursor is no longer at end
let cursor_moved_away = get_final_cursor(&new_content, 0);
assert_eq!(
cursor_moved_away,
Some((0, 0)),
"Cursor moved to the newline on line 0"
);
}
// NOTE: Tests for view transform header handling have been moved to src/ui/view_pipeline.rs
// where the elegant token-based pipeline properly handles these cases.
// The view_pipeline tests cover:
// - test_simple_source_lines
// - test_wrapped_continuation
// - test_injected_header_then_source
// - test_mixed_scenario
}