fresh-editor 0.4.0

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
// Integration tests - testing how modules work together

mod common;

use fresh::model::filesystem::StdFileSystem;
use fresh::{
    model::cursor::Cursors,
    model::event::{CursorId, Event, EventLog},
    state::EditorState,
    view::overlay::OverlayNamespace,
    view::theme,
};

/// Test that cursor positions are correctly adjusted after buffer edits
fn test_fs() -> std::sync::Arc<dyn fresh::model::filesystem::FileSystem + Send + Sync> {
    std::sync::Arc::new(StdFileSystem)
}

#[test]
fn test_buffer_cursor_adjustment_on_insert() {
    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut cursors = Cursors::new();

    // Get the initial primary cursor ID (CursorId(0))
    let original_primary = cursors.primary_id();

    // Insert some initial text with the original primary cursor
    state.apply(
        &mut cursors,
        &Event::Insert {
            position: 0,
            text: "hello world".to_string(),
            cursor_id: original_primary,
        },
    );

    // Original primary cursor should be at end of inserted text (position 11)
    assert_eq!(cursors.get(original_primary).unwrap().position, 11);

    // Add a second cursor at position 6 (start of "world")
    // Note: This will make CursorId(1) the new primary
    state.apply(
        &mut cursors,
        &Event::AddCursor {
            cursor_id: CursorId(1),
            position: 6,
            anchor: None,
        },
    );

    // Verify CursorId(1) is at position 6 and is now primary
    assert_eq!(cursors.get(CursorId(1)).unwrap().position, 6);
    assert_eq!(cursors.primary_id(), CursorId(1));

    // Insert text at beginning with the ORIGINAL primary cursor (not the new one)
    // This tests that non-editing cursors get adjusted
    let insert_len = "INSERTED ".len();
    state.apply(
        &mut cursors,
        &Event::Insert {
            position: 0,
            text: "INSERTED ".to_string(),
            cursor_id: original_primary, // Using original cursor, not the new primary
        },
    );

    // The cursor that made the edit (original_primary) should be at position 0 + insert_len = 9
    assert_eq!(
        cursors.get(original_primary).unwrap().position,
        insert_len,
        "Cursor that made the edit should be at end of insertion"
    );

    // CursorId(1) was at position 6, should have moved forward by insert_len to position 15
    assert_eq!(
        cursors.get(CursorId(1)).unwrap().position,
        6 + insert_len,
        "Non-editing cursor should be adjusted by insertion length"
    );

    // Buffer content should be correct
    assert_eq!(state.buffer.to_string().unwrap(), "INSERTED hello world");
}

/// Test that cursor positions are correctly adjusted after deletions
#[test]
fn test_buffer_cursor_adjustment_on_delete() {
    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut cursors = Cursors::new();

    // Insert initial text
    let cursor_id = cursors.primary_id();
    state.apply(
        &mut cursors,
        &Event::Insert {
            position: 0,
            text: "hello beautiful world".to_string(),
            cursor_id,
        },
    );

    // Add cursor at position 16 (start of "world")
    state.apply(
        &mut cursors,
        &Event::AddCursor {
            cursor_id: CursorId(1),
            position: 16,
            anchor: None,
        },
    );

    // Delete "beautiful " (positions 6-16)
    let cursor_id = cursors.primary_id();
    state.apply(
        &mut cursors,
        &Event::Delete {
            range: 6..16,
            deleted_text: "beautiful ".to_string(),
            cursor_id,
        },
    );

    // Second cursor should have moved back to position 6
    if let Some(cursor) = cursors.get(CursorId(1)) {
        assert_eq!(cursor.position, 6);
    }

    // Buffer content should be correct
    assert_eq!(state.buffer.to_string().unwrap(), "hello world");
}

/// Test undo/redo with EditorState and EventLog
#[test]
fn test_state_eventlog_undo_redo() {
    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut log = EventLog::new();
    let mut cursors = Cursors::new();

    let cursor_id = cursors.primary_id();

    // Perform a series of edits - each insert at the END of the buffer
    let event1 = Event::Insert {
        position: 0,
        text: "a".to_string(),
        cursor_id,
    };
    log.append(event1.clone());
    state.apply(&mut cursors, &event1);

    let event2 = Event::Insert {
        position: state.buffer.len(),
        text: "b".to_string(),
        cursor_id,
    };
    log.append(event2.clone());
    state.apply(&mut cursors, &event2);

    let event3 = Event::Insert {
        position: state.buffer.len(),
        text: "c".to_string(),
        cursor_id,
    };
    log.append(event3.clone());
    state.apply(&mut cursors, &event3);

    assert_eq!(state.buffer.to_string().unwrap(), "abc");

    // Undo all - log.undo() returns inverse events ready to apply
    while log.can_undo() {
        let events = log.undo();
        for (event, _displaced) in events {
            state.apply(&mut cursors, &event);
        }
    }

    assert_eq!(state.buffer.to_string().unwrap(), "");

    // Redo all - log.redo() returns the original events to replay
    while log.can_redo() {
        let events = log.redo();
        for event in events {
            state.apply(&mut cursors, &event);
        }
    }

    assert_eq!(state.buffer.to_string().unwrap(), "abc");
}

/// Test that undo/redo maintains cursor positions correctly
#[test]
fn test_undo_redo_cursor_positions() {
    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut log = EventLog::new();
    let mut cursors = Cursors::new();

    let cursor_id = cursors.primary_id();

    // Type "hello" - each character at the end of the buffer
    for ch in "hello".chars() {
        let pos = state.buffer.len();
        let event = Event::Insert {
            position: pos,
            text: ch.to_string(),
            cursor_id,
        };
        log.append(event.clone());
        state.apply(&mut cursors, &event);
    }

    assert_eq!(state.buffer.to_string().unwrap(), "hello");
    let cursor_after_typing = cursors.primary().position;
    assert_eq!(cursor_after_typing, 5);

    // Undo twice (remove 'o' and 'l')
    for _ in 0..2 {
        let events = log.undo();
        for (event, _displaced) in events {
            state.apply(&mut cursors, &event);
        }
    }

    assert_eq!(state.buffer.to_string().unwrap(), "hel");
    assert_eq!(cursors.primary().position, 3);

    // Redo twice
    for _ in 0..2 {
        let events = log.redo();
        for event in events {
            state.apply(&mut cursors, &event);
        }
    }

    assert_eq!(state.buffer.to_string().unwrap(), "hello");
    assert_eq!(cursors.primary().position, 5);
}

/// Test viewport ensures cursor stays visible after edits
#[test]
fn test_viewport_tracks_cursor_through_edits() {
    let mut state = EditorState::new(
        80,
        10,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    ); // Small viewport
    let mut cursors = Cursors::new();

    let cursor_id = cursors.primary_id();

    // Insert many lines to make content scroll
    for i in 0..20 {
        let event = Event::Insert {
            position: state.buffer.len(),
            text: format!("Line {i}\n"),
            cursor_id,
        };
        state.apply(&mut cursors, &event);
    }

    // Cursor should be at the end
    let cursor_pos = cursors.primary().position;
    assert!(cursor_pos > 0);

    // Cursor position should be within buffer bounds
    assert!(
        cursor_pos <= state.buffer.len(),
        "Cursor should be within buffer bounds"
    );
}

/// Test multi-cursor normalization after overlapping edits
#[test]
fn test_multi_cursor_normalization() {
    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut cursors = Cursors::new();

    // Insert initial text
    let cursor_id = cursors.primary_id();
    state.apply(
        &mut cursors,
        &Event::Insert {
            position: 0,
            text: "hello world".to_string(),
            cursor_id,
        },
    );

    // Add overlapping cursors
    state.apply(
        &mut cursors,
        &Event::AddCursor {
            cursor_id: CursorId(1),
            position: 5,
            anchor: None,
        },
    );

    state.apply(
        &mut cursors,
        &Event::AddCursor {
            cursor_id: CursorId(2),
            position: 6,
            anchor: None,
        },
    );

    // Should have 3 cursors initially
    assert_eq!(cursors.count(), 3);

    // After normalization (which happens in AddCursor), overlapping cursors might be merged
    // This depends on Cursors::normalize() implementation
    // For now, just verify they all exist and are in valid positions
    for (_, cursor) in cursors.iter() {
        assert!(cursor.position <= state.buffer.len());
    }
}

/// Test that cursor position is maintained within buffer bounds after edits
#[test]
fn test_cursor_within_buffer_bounds() {
    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut cursors = Cursors::new();

    // Insert text and move cursor to middle
    let cursor_id = cursors.primary_id();
    state.apply(
        &mut cursors,
        &Event::Insert {
            position: 0,
            text: "line1\nline2\nline3\nline4\nline5\n".to_string(),
            cursor_id,
        },
    );

    let cursor_id = cursors.primary_id();
    state.apply(
        &mut cursors,
        &Event::MoveCursor {
            cursor_id,
            old_position: 0,
            new_position: 12, // Middle of line 2
            old_anchor: None,
            new_anchor: None,
            old_sticky_column: 0,
            new_sticky_column: 0,
        },
    );

    // Cursor should be within buffer bounds
    let cursor_pos = cursors.primary().position;
    assert!(
        cursor_pos <= state.buffer.len(),
        "Cursor should be within buffer bounds"
    );
}

/// Test overlay events - adding and removing overlays
#[test]
fn test_overlay_events() {
    use fresh::model::event::{OverlayFace, UnderlineStyle};

    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut cursors = Cursors::new();

    // Insert some text
    state.apply(
        &mut cursors,
        &Event::Insert {
            position: 0,
            text: "hello world".to_string(),
            cursor_id: CursorId(0),
        },
    );

    // Add an error overlay with namespace
    state.apply(
        &mut cursors,
        &Event::AddOverlay {
            namespace: Some(OverlayNamespace::from_string("error".to_string())),
            range: 0..5,
            face: OverlayFace::Underline {
                color: (255, 0, 0),
                style: UnderlineStyle::Wavy,
            },
            priority: 100,
            message: Some("Error here".to_string()),
            extend_to_line_end: false,
            url: None,
        },
    );

    // Check overlay was added
    let overlays_at_pos = state.overlays.at_position(2, &state.marker_list);
    assert_eq!(overlays_at_pos.len(), 1);
    assert_eq!(
        overlays_at_pos[0].namespace,
        Some(OverlayNamespace::from_string("error".to_string()))
    );

    // Add a warning overlay with lower priority
    state.apply(
        &mut cursors,
        &Event::AddOverlay {
            namespace: Some(OverlayNamespace::from_string("warning".to_string())),
            range: 3..8,
            face: OverlayFace::Underline {
                color: (255, 255, 0),
                style: UnderlineStyle::Wavy,
            },
            priority: 50,
            message: Some("Warning here".to_string()),
            extend_to_line_end: false,
            url: None,
        },
    );

    // Position 4 should have both overlays, sorted by priority (ascending)
    let overlays_at_4 = state.overlays.at_position(4, &state.marker_list);
    assert_eq!(overlays_at_4.len(), 2);
    assert_eq!(overlays_at_4[0].priority, 50); // Warning (lower priority) comes first
    assert_eq!(overlays_at_4[1].priority, 100); // Error (higher priority) comes second

    // Remove error overlay using namespace
    state.apply(
        &mut cursors,
        &Event::ClearNamespace {
            namespace: OverlayNamespace::from_string("error".to_string()),
        },
    );

    // Now position 4 should only have warning
    let overlays_at_4 = state.overlays.at_position(4, &state.marker_list);
    assert_eq!(overlays_at_4.len(), 1);
    assert_eq!(
        overlays_at_4[0].namespace,
        Some(OverlayNamespace::from_string("warning".to_string()))
    );

    // Clear all overlays
    state.apply(&mut cursors, &Event::ClearOverlays);
    let overlays_after_clear = state.overlays.at_position(4, &state.marker_list);
    assert_eq!(overlays_after_clear.len(), 0);
}

/// Test popup events - showing, navigating, and hiding popups
#[test]
fn test_popup_events() {
    use fresh::model::event::{
        PopupContentData, PopupData, PopupKindHint, PopupListItemData, PopupPositionData,
    };

    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut cursors = Cursors::new();

    // Create a popup with list items
    let popup_data = PopupData {
        kind: PopupKindHint::List,
        title: Some("Test Popup".to_string()),
        description: None,
        transient: false,
        content: PopupContentData::List {
            items: vec![
                PopupListItemData {
                    text: "Item 1".to_string(),
                    detail: Some("First item".to_string()),
                    icon: Some("📄".to_string()),
                    data: None,
                },
                PopupListItemData {
                    text: "Item 2".to_string(),
                    detail: Some("Second item".to_string()),
                    icon: Some("📄".to_string()),
                    data: None,
                },
                PopupListItemData {
                    text: "Item 3".to_string(),
                    detail: Some("Third item".to_string()),
                    icon: Some("📄".to_string()),
                    data: None,
                },
            ],
            selected: 0,
        },
        position: PopupPositionData::Centered,
        width: 40,
        max_height: 10,
        bordered: true,
    };

    // Show the popup
    state.apply(&mut cursors, &Event::ShowPopup { popup: popup_data });

    // Check popup is visible
    assert!(state.popups.is_visible());
    let popup = state.popups.top().unwrap();
    assert_eq!(popup.title, Some("Test Popup".to_string()));

    // Navigate down
    state.apply(&mut cursors, &Event::PopupSelectNext);

    // Check selection moved to item 1
    let popup = state.popups.top().unwrap();
    let selected_item = popup.selected_item().unwrap();
    assert_eq!(selected_item.text, "Item 2");

    // Navigate down again
    state.apply(&mut cursors, &Event::PopupSelectNext);
    let popup = state.popups.top().unwrap();
    let selected_item = popup.selected_item().unwrap();
    assert_eq!(selected_item.text, "Item 3");

    // Navigate up
    state.apply(&mut cursors, &Event::PopupSelectPrev);
    let popup = state.popups.top().unwrap();
    let selected_item = popup.selected_item().unwrap();
    assert_eq!(selected_item.text, "Item 2");

    // Hide popup
    state.apply(&mut cursors, &Event::HidePopup);
    assert!(!state.popups.is_visible());
}

/// Test that overlays persist through undo/redo
#[test]
fn test_overlay_undo_redo() {
    use fresh::model::event::{OverlayFace, UnderlineStyle};

    let mut log = EventLog::new();
    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut cursors = Cursors::new();

    // Insert text and add overlay
    let event1 = Event::Insert {
        position: 0,
        text: "hello".to_string(),
        cursor_id: CursorId(0),
    };
    log.append(event1.clone());
    state.apply(&mut cursors, &event1);

    let event2 = Event::AddOverlay {
        namespace: Some(OverlayNamespace::from_string("test".to_string())),
        range: 0..5,
        face: OverlayFace::Underline {
            color: (255, 0, 0),
            style: UnderlineStyle::Wavy,
        },
        priority: 100,
        message: None,
        extend_to_line_end: false,
        url: None,
    };
    log.append(event2.clone());
    state.apply(&mut cursors, &event2);

    // Verify overlay exists
    assert_eq!(state.overlays.at_position(2, &state.marker_list).len(), 1);

    // Undo - this should process AddOverlay (remove it) and undo the Insert
    let undo_events = log.undo();
    for (event, _displaced) in &undo_events {
        state.apply(&mut cursors, event);
    }

    // After undo: buffer should be empty, and overlay should be removed
    assert_eq!(state.buffer.len(), 0);
    assert_eq!(state.overlays.at_position(2, &state.marker_list).len(), 0);
    assert!(
        !undo_events.is_empty(),
        "Should have returned events to undo"
    );

    // Redo - should redo the Insert and re-add the overlay
    let redo_events = log.redo();
    for event in &redo_events {
        state.apply(&mut cursors, event);
    }

    // After redo: buffer is back and overlay should be back
    assert_eq!(state.buffer.to_string().unwrap(), "hello");
    // Note: AddOverlay was redone, so overlay should be back
    assert_eq!(state.overlays.at_position(2, &state.marker_list).len(), 1);
    assert!(
        !redo_events.is_empty(),
        "Should have returned events to redo"
    );
}

/// Test LSP diagnostic to overlay conversion
#[test]
fn test_lsp_diagnostic_to_overlay() {
    use fresh::{
        config::LARGE_FILE_THRESHOLD_BYTES, model::buffer::Buffer,
        services::lsp::diagnostics::diagnostic_to_overlay,
    };
    use lsp_types::{Diagnostic, DiagnosticSeverity, Position, Range};

    let buffer = Buffer::from_str(
        "let x = 5;\nlet y = 10;",
        LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );

    // Create an error diagnostic on first line
    let diagnostic = Diagnostic {
        range: Range {
            start: Position {
                line: 0,
                character: 4,
            },
            end: Position {
                line: 0,
                character: 5,
            },
        },
        severity: Some(DiagnosticSeverity::ERROR),
        code: None,
        code_description: None,
        source: Some("rust-analyzer".to_string()),
        message: "unused variable: `x`".to_string(),
        related_information: None,
        tags: None,
        data: None,
    };

    let theme = fresh::view::theme::Theme::load_builtin(theme::THEME_DARK).unwrap();
    let result = diagnostic_to_overlay(&diagnostic, &buffer, &theme);
    assert!(result.is_some());

    let (range, face, priority, theme_key) = result.unwrap();

    // Check range: "let x = 5;\n" - position 4 is 'x'
    assert_eq!(range.start, 4);
    assert_eq!(range.end, 5);
    assert_eq!(theme_key, "diagnostic.error_bg");

    // Check priority (error should be highest)
    assert_eq!(priority, 100);

    // Check face (should use theme's error background color)
    match face {
        fresh::view::overlay::OverlayFace::Background { color } => {
            assert_eq!(color, theme.diagnostic_error_bg);
        }
        _ => panic!("Expected background face for error diagnostic"),
    }
}

/// Test overlay rendering with multiple priorities
#[test]
fn test_overlay_priority_layering() {
    use fresh::model::event::{OverlayFace, UnderlineStyle};

    let mut state = EditorState::new(
        80,
        24,
        fresh::config::LARGE_FILE_THRESHOLD_BYTES as usize,
        test_fs(),
    );
    let mut cursors = Cursors::new();

    // Insert text
    state.apply(
        &mut cursors,
        &Event::Insert {
            position: 0,
            text: "hello world".to_string(),
            cursor_id: CursorId(0),
        },
    );

    // Add low priority overlay (hint)
    state.apply(
        &mut cursors,
        &Event::AddOverlay {
            namespace: Some(OverlayNamespace::from_string("hint".to_string())),
            range: 0..5,
            face: OverlayFace::Underline {
                color: (128, 128, 128),
                style: UnderlineStyle::Dotted,
            },
            priority: 10,
            message: Some("Hint message".to_string()),
            extend_to_line_end: false,
            url: None,
        },
    );

    // Add high priority overlay (error) overlapping
    state.apply(
        &mut cursors,
        &Event::AddOverlay {
            namespace: Some(OverlayNamespace::from_string("error".to_string())),
            range: 2..7,
            face: OverlayFace::Underline {
                color: (255, 0, 0),
                style: UnderlineStyle::Wavy,
            },
            priority: 100,
            message: Some("Error message".to_string()),
            extend_to_line_end: false,
            url: None,
        },
    );

    // Position 3 should have both overlays, sorted by priority
    let overlays = state.overlays.at_position(3, &state.marker_list);
    assert_eq!(overlays.len(), 2);
    assert_eq!(overlays[0].priority, 10); // Hint (lower priority first)
    assert_eq!(overlays[1].priority, 100); // Error (higher priority second)

    // Verify namespaces
    assert_eq!(
        overlays[0].namespace,
        Some(OverlayNamespace::from_string("hint".to_string()))
    );
    assert_eq!(
        overlays[1].namespace,
        Some(OverlayNamespace::from_string("error".to_string()))
    );
}

/// E2E test: Verify diagnostic overlays are visually rendered with correct colors
#[test]
fn test_diagnostic_overlay_visual_rendering() {
    use common::harness::EditorTestHarness;
    use fresh::model::event::{OverlayFace, UnderlineStyle};
    use ratatui::style::{Color, Modifier};

    let mut harness = EditorTestHarness::new(80, 24).unwrap();

    // Insert some text
    harness.type_text("let x = 5;").unwrap();
    harness.render().unwrap();

    // Add an error diagnostic overlay on "x" (position 4)
    // This simulates what LSP would do when it finds an error
    // We use the overlay API directly, but convert the color to RGB format
    // since that's what OverlayFace uses (u8, u8, u8) tuples
    let state = harness.editor_mut().active_state_mut();
    let mut cursors = Cursors::new();
    state.apply(
        &mut cursors,
        &Event::AddOverlay {
            namespace: Some(OverlayNamespace::from_string("lsp-diagnostic".to_string())),
            range: 4..5, // "x"
            face: OverlayFace::Underline {
                color: (255, 0, 0), // Red as RGB
                style: UnderlineStyle::Wavy,
            },
            priority: 100,
            message: Some("unused variable: `x`".to_string()),
            extend_to_line_end: false,
            url: None,
        },
    );

    // Render again to apply the overlay styling
    harness.render().unwrap();

    // Now check that the character "x" at the expected position has red color
    // Gutter width scales with line count: 1 line → 5 chars (indicator + 1 digit + separator)
    // "let x = 5;" -> "x" is at text position 4, which maps to screen column gutter_width + 4
    let gutter_width = harness.editor().active_state().margins.left_total_width() as u16;
    let x_column = gutter_width + 4; // Position of "x" in "let x = 5;"
    let (content_first_row, _) = harness.content_area_rows();
    let x_row = content_first_row as u16; // First line of content (row 0 is menu bar, row 1 is tab bar, row 2 is first text line)

    // Get the style of the "x" character
    let style = harness.get_cell_style(x_column, x_row);
    assert!(
        style.is_some(),
        "Expected cell at ({x_column}, {x_row}) to have a style"
    );

    let style = style.unwrap();

    // Verify the foreground color is red (indicating error)
    // The color will be rendered as RGB(255, 0, 0) since that's what we passed in the overlay
    assert_eq!(
        style.fg,
        Some(Color::Rgb(255, 0, 0)),
        "Expected 'x' to be rendered in red (RGB 255,0,0) due to error diagnostic"
    );

    // Verify underline modifier is applied
    assert!(
        style.add_modifier.contains(Modifier::UNDERLINED),
        "Expected 'x' to have underline modifier"
    );

    // Verify the text itself is correct
    let text = harness.get_cell(x_column, x_row);
    assert_eq!(
        text,
        Some("x".to_string()),
        "Expected 'x' character at position"
    );
}

/// Comprehensive tests for Event::inverse()
mod event_inverse_tests {
    use fresh::model::event::{CursorId, Event, OverlayFace, UnderlineStyle};
    use fresh::view::overlay::{OverlayHandle, OverlayNamespace};

    #[test]
    fn test_insert_inverse() {
        let event = Event::Insert {
            position: 10,
            text: "hello".to_string(),
            cursor_id: CursorId(0),
        };

        let inverse = event.inverse().expect("Insert should have inverse");

        match inverse {
            Event::Delete {
                range,
                deleted_text,
                cursor_id,
            } => {
                assert_eq!(range, 10..15);
                assert_eq!(deleted_text, "hello");
                assert_eq!(cursor_id, CursorId::UNDO_SENTINEL);
            }
            _ => panic!("Insert inverse should be Delete"),
        }
    }

    #[test]
    fn test_delete_inverse() {
        let event = Event::Delete {
            range: 5..10,
            deleted_text: "world".to_string(),
            cursor_id: CursorId(1),
        };

        let inverse = event.inverse().expect("Delete should have inverse");

        match inverse {
            Event::Insert {
                position,
                text,
                cursor_id,
            } => {
                assert_eq!(position, 5);
                assert_eq!(text, "world");
                assert_eq!(cursor_id, CursorId::UNDO_SENTINEL);
            }
            _ => panic!("Delete inverse should be Insert"),
        }
    }

    #[test]
    fn test_add_cursor_inverse() {
        let event = Event::AddCursor {
            cursor_id: CursorId(2),
            position: 42,
            anchor: Some(10),
        };

        let inverse = event.inverse().expect("AddCursor should have inverse");

        match inverse {
            Event::RemoveCursor {
                cursor_id,
                position,
                anchor,
            } => {
                assert_eq!(cursor_id, CursorId(2));
                assert_eq!(position, 42);
                assert_eq!(anchor, Some(10));
            }
            _ => panic!("AddCursor inverse should be RemoveCursor"),
        }
    }

    #[test]
    fn test_remove_cursor_inverse() {
        let event = Event::RemoveCursor {
            cursor_id: CursorId(3),
            position: 100,
            anchor: None,
        };

        let inverse = event.inverse().expect("RemoveCursor should have inverse");

        match inverse {
            Event::AddCursor {
                cursor_id,
                position,
                anchor,
            } => {
                assert_eq!(cursor_id, CursorId(3));
                assert_eq!(position, 100);
                assert_eq!(anchor, None);
            }
            _ => panic!("RemoveCursor inverse should be AddCursor"),
        }
    }

    #[test]
    fn test_move_cursor_inverse() {
        let event = Event::MoveCursor {
            cursor_id: CursorId(0),
            old_position: 10,
            new_position: 20,
            old_anchor: None,
            new_anchor: Some(15),
            old_sticky_column: 5,
            new_sticky_column: 10,
        };

        let inverse = event.inverse().expect("MoveCursor should have inverse");

        match inverse {
            Event::MoveCursor {
                cursor_id,
                old_position,
                new_position,
                old_anchor,
                new_anchor,
                old_sticky_column,
                new_sticky_column,
            } => {
                assert_eq!(cursor_id, CursorId(0));
                assert_eq!(old_position, 20); // Swapped
                assert_eq!(new_position, 10); // Swapped
                assert_eq!(old_anchor, Some(15)); // Swapped
                assert_eq!(new_anchor, None); // Swapped
                assert_eq!(old_sticky_column, 10); // Swapped
                assert_eq!(new_sticky_column, 5); // Swapped
            }
            _ => panic!("MoveCursor inverse should be MoveCursor"),
        }
    }

    #[test]
    fn test_add_overlay_no_inverse() {
        // Overlays are ephemeral decorations, not undoable
        let event = Event::AddOverlay {
            namespace: Some(OverlayNamespace::from_string("test-overlay".to_string())),
            range: 0..10,
            face: OverlayFace::Underline {
                color: (255, 0, 0),
                style: UnderlineStyle::Wavy,
            },
            priority: 100,
            message: Some("error".to_string()),
            extend_to_line_end: false,
            url: None,
        };

        // AddOverlay is ephemeral and has no inverse
        assert!(event.inverse().is_none());
    }

    #[test]
    fn test_remove_overlay_no_inverse() {
        let event = Event::RemoveOverlay {
            handle: OverlayHandle::from_string("test".to_string()),
        };

        // RemoveOverlay is ephemeral and has no inverse
        assert!(event.inverse().is_none());
    }

    #[test]
    fn test_scroll_inverse() {
        let event = Event::Scroll { line_offset: 5 };

        let inverse = event.inverse().expect("Scroll should have inverse");

        match inverse {
            Event::Scroll { line_offset } => {
                assert_eq!(line_offset, -5); // Negated
            }
            _ => panic!("Scroll inverse should be Scroll with negated offset"),
        }
    }

    #[test]
    fn test_set_viewport_no_inverse() {
        let event = Event::SetViewport { top_line: 10 };

        // SetViewport doesn't have inverse because we don't store the old top_line
        assert!(event.inverse().is_none());
    }

    #[test]
    fn test_change_mode_no_inverse() {
        let event = Event::ChangeMode {
            mode: "insert".to_string(),
        };

        // ChangeMode doesn't have inverse because we don't store the old mode
        assert!(event.inverse().is_none());
    }

    #[test]
    fn test_batch_inverse() {
        let batch = Event::Batch {
            events: vec![
                Event::Insert {
                    position: 0,
                    text: "a".to_string(),
                    cursor_id: CursorId(0),
                },
                Event::Insert {
                    position: 1,
                    text: "b".to_string(),
                    cursor_id: CursorId(0),
                },
                Event::Insert {
                    position: 2,
                    text: "c".to_string(),
                    cursor_id: CursorId(0),
                },
            ],
            description: "Insert abc".to_string(),
        };

        let inverse = batch.inverse().expect("Batch should have inverse");

        match inverse {
            Event::Batch {
                events,
                description,
            } => {
                assert_eq!(events.len(), 3);
                assert_eq!(description, "Undo: Insert abc");

                // Events should be reversed
                // Original: [Insert(0,'a'), Insert(1,'b'), Insert(2,'c')]
                // Inverse: [Delete(2..3,'c'), Delete(1..2,'b'), Delete(0..1,'a')]

                // Check first event (was last insert)
                match &events[0] {
                    Event::Delete {
                        range,
                        deleted_text,
                        ..
                    } => {
                        assert_eq!(*range, 2..3);
                        assert_eq!(deleted_text, "c");
                    }
                    _ => panic!("Expected Delete"),
                }

                // Check last event (was first insert)
                match &events[2] {
                    Event::Delete {
                        range,
                        deleted_text,
                        ..
                    } => {
                        assert_eq!(*range, 0..1);
                        assert_eq!(deleted_text, "a");
                    }
                    _ => panic!("Expected Delete"),
                }
            }
            _ => panic!("Batch inverse should be Batch"),
        }
    }

    #[test]
    fn test_batch_with_non_invertible_events() {
        let batch = Event::Batch {
            events: vec![
                Event::Insert {
                    position: 0,
                    text: "a".to_string(),
                    cursor_id: CursorId(0),
                },
                Event::SetViewport { top_line: 10 }, // Not invertible
            ],
            description: "Mixed batch".to_string(),
        };

        // Batch with non-invertible events returns None
        assert!(batch.inverse().is_none());
    }

    #[test]
    fn test_nested_batch_inverse() {
        let inner_batch = Event::Batch {
            events: vec![
                Event::Insert {
                    position: 0,
                    text: "x".to_string(),
                    cursor_id: CursorId(0),
                },
                Event::Insert {
                    position: 1,
                    text: "y".to_string(),
                    cursor_id: CursorId(0),
                },
            ],
            description: "Inner".to_string(),
        };

        let outer_batch = Event::Batch {
            events: vec![
                Event::Insert {
                    position: 0,
                    text: "a".to_string(),
                    cursor_id: CursorId(0),
                },
                inner_batch,
                Event::Insert {
                    position: 3,
                    text: "z".to_string(),
                    cursor_id: CursorId(0),
                },
            ],
            description: "Outer".to_string(),
        };

        let inverse = outer_batch
            .inverse()
            .expect("Nested batch should have inverse");

        match inverse {
            Event::Batch {
                events,
                description,
            } => {
                assert_eq!(events.len(), 3);
                assert_eq!(description, "Undo: Outer");

                // Check that the inner batch is also inverted
                match &events[1] {
                    Event::Batch {
                        events: inner_events,
                        description: inner_desc,
                    } => {
                        assert_eq!(inner_events.len(), 2);
                        assert_eq!(inner_desc, "Undo: Inner");
                    }
                    _ => panic!("Expected nested Batch"),
                }
            }
            _ => panic!("Outer batch inverse should be Batch"),
        }
    }

    #[test]
    fn test_double_inverse_equals_original() {
        let original = Event::Insert {
            position: 5,
            text: "test".to_string(),
            cursor_id: CursorId(0),
        };

        let inverse = original.inverse().expect("Should have inverse");
        let double_inverse = inverse.inverse().expect("Should have double inverse");

        // Double inverse should be equivalent to original (with UNDO_SENTINEL cursor_id)
        match double_inverse {
            Event::Insert {
                position,
                text,
                cursor_id,
            } => {
                assert_eq!(position, 5);
                assert_eq!(text, "test");
                assert_eq!(cursor_id, CursorId::UNDO_SENTINEL);
            }
            _ => panic!("Double inverse should be Insert"),
        }
    }

    #[test]
    fn test_move_cursor_double_inverse() {
        let original = Event::MoveCursor {
            cursor_id: CursorId(0),
            old_position: 10,
            new_position: 20,
            old_anchor: None,
            new_anchor: Some(15),
            old_sticky_column: 5,
            new_sticky_column: 10,
        };

        let inverse = original.inverse().expect("Should have inverse");
        let double_inverse = inverse.inverse().expect("Should have double inverse");

        // Double inverse should equal original
        match double_inverse {
            Event::MoveCursor {
                cursor_id,
                old_position,
                new_position,
                old_anchor,
                new_anchor,
                old_sticky_column,
                new_sticky_column,
            } => {
                assert_eq!(cursor_id, CursorId(0));
                assert_eq!(old_position, 10);
                assert_eq!(new_position, 20);
                assert_eq!(old_anchor, None);
                assert_eq!(new_anchor, Some(15));
                assert_eq!(old_sticky_column, 5);
                assert_eq!(new_sticky_column, 10);
            }
            _ => panic!("Double inverse should be MoveCursor"),
        }
    }
}

/// Test that syntax highlighting byte offsets are correct for CRLF files.
/// This is a regression test for a bug where the TextMate highlighter used str::lines()
/// which strips line terminators, causing 1-byte offset drift per line in CRLF files.
///
/// The bug manifests as: keyword highlighting shifts left by N characters on line N+1,
/// so line 1 is correct, line 2 is off by 1, line 3 is off by 2, etc.
#[test]
fn test_crlf_syntax_highlighting_offset() {
    use common::fixtures::TestFixture;
    use common::harness::EditorTestHarness;
    use ratatui::style::Color;

    // Create a Rust file with CRLF line endings.
    // Each line has `pub` keyword at a specific column.
    // If there's offset drift, the highlighting will shift.
    //
    // Structure (with \r\n line endings):
    // Line 1: "pub fn a() {}\r\n"  - pub at columns 0-2
    // Line 2: "pub fn b() {}\r\n"  - pub at columns 0-2 (but would be off by 1 if buggy)
    // Line 3: "pub fn c() {}\r\n"  - pub at columns 0-2 (but would be off by 2 if buggy)
    // Each line has: keyword (public), identifier (x), operator (=), number (N), semicolon
    // This gives us different token types to verify highlighting isn't shifted
    // Numbers should have a DIFFERENT color than keywords
    // Using Java (.java) which uses TextMate highlighting (not tree-sitter)
    let content = "public int x = 1;\r\npublic int x = 2;\r\npublic int x = 3;\r\npublic int x = 4;\r\npublic int x = 5;\r\npublic int x = 6;\r\n";

    // Create fixture with .java extension so it gets TextMate syntax highlighting.
    let fixture = TestFixture::new("test_crlf.java", content).unwrap();

    // Java is highlighted by syntect (its tree-sitter grammar was dropped), so
    // the test needs the full grammar registry — the minimal default registry
    // only carries the bundled tree-sitter grammars.
    let mut harness = EditorTestHarness::create(
        80,
        24,
        common::harness::HarnessOptions::new().with_full_grammar_registry(),
    )
    .unwrap();
    harness.open_file(&fixture.path).unwrap();

    // Wait a bit for syntax highlighting to initialize
    harness.render().unwrap();
    std::thread::sleep(std::time::Duration::from_millis(100));
    harness.render().unwrap();

    // Debug: print screen content
    eprintln!("Screen content:");
    for row in 0..10 {
        let row_text = harness.get_row_text(row);
        eprintln!("Row {}: {:?}", row, row_text);
    }

    // Debug: Check if highlighter is active
    eprintln!("Has highlighter: {}", harness.has_highlighter());
    eprintln!(
        "Highlighter backend: {}",
        harness.editor().active_state().highlighter.backend_name()
    );

    // Debug: Print buffer line ending mode
    let buffer_content = harness.get_buffer_content().unwrap_or_default();
    let has_crlf = buffer_content.contains("\r\n");
    eprintln!("Buffer has CRLF: {}", has_crlf);
    eprintln!("Buffer content bytes: {:?}", buffer_content.as_bytes());

    // Content area starts at row 2 (after menu bar and tab bar)
    // Line 1 is at screen row 2, line 2 at row 3, line 3 at row 4
    // The gutter (line numbers) takes up some columns, so we need to find where content starts

    // Helper to find the column where a character appears on a row
    // We iterate character by character to get the correct column index
    let find_char_col = |harness: &EditorTestHarness, row: u16, ch: char| -> Option<u16> {
        let row_text = harness.get_row_text(row);
        for (col, c) in row_text.chars().enumerate() {
            if c == ch {
                return Some(col as u16);
            }
        }
        None
    };

    // Find where 'p' of 'pub' is on each line
    let line1_p_col = find_char_col(&harness, 2, 'p').expect("Should find 'p' on line 1");
    let line2_p_col = find_char_col(&harness, 3, 'p').expect("Should find 'p' on line 2");
    let line3_p_col = find_char_col(&harness, 4, 'p').expect("Should find 'p' on line 3");
    let line4_p_col = find_char_col(&harness, 5, 'p').expect("Should find 'p' on line 4");
    let line5_p_col = find_char_col(&harness, 6, 'p').expect("Should find 'p' on line 5");
    let line6_p_col = find_char_col(&harness, 7, 'p').expect("Should find 'p' on line 6");

    eprintln!(
        "Found 'p' at columns: 1={}, 2={}, 3={}, 4={}, 5={}, 6={}",
        line1_p_col, line2_p_col, line3_p_col, line4_p_col, line5_p_col, line6_p_col
    );

    // All 'pub' keywords should start at the same column
    assert_eq!(
        line1_p_col, line2_p_col,
        "Line 1 and Line 2 'pub' should be at same column"
    );
    assert_eq!(
        line2_p_col, line3_p_col,
        "Line 2 and Line 3 'pub' should be at same column"
    );

    // Now check that the highlighting color is the same for 'pub' on all three lines
    // Get the foreground color of 'p' on each line
    let get_fg_color = |harness: &EditorTestHarness, row: u16, col: u16| -> Option<Color> {
        harness.get_cell_style(col, row).and_then(|s| s.fg)
    };

    let line1_p_color = get_fg_color(&harness, 2, line1_p_col);
    let line2_p_color = get_fg_color(&harness, 3, line2_p_col);
    let line3_p_color = get_fg_color(&harness, 4, line3_p_col);
    let line4_p_color = get_fg_color(&harness, 5, line4_p_col);
    let line5_p_color = get_fg_color(&harness, 6, line5_p_col);
    let line6_p_color = get_fg_color(&harness, 7, line6_p_col);

    eprintln!("Colors at 'p' position:");
    eprintln!("  Line 1 (row 2, col {}): {:?}", line1_p_col, line1_p_color);
    eprintln!("  Line 2 (row 3, col {}): {:?}", line2_p_col, line2_p_color);
    eprintln!("  Line 3 (row 4, col {}): {:?}", line3_p_col, line3_p_color);
    eprintln!("  Line 4 (row 5, col {}): {:?}", line4_p_col, line4_p_color);
    eprintln!("  Line 5 (row 6, col {}): {:?}", line5_p_col, line5_p_color);
    eprintln!("  Line 6 (row 7, col {}): {:?}", line6_p_col, line6_p_color);

    // Also print what char is at each position
    eprintln!("Chars at 'p' position:");
    eprintln!(
        "  Line 1: '{}'",
        harness.get_cell(line1_p_col, 2).unwrap_or_default()
    );
    eprintln!(
        "  Line 2: '{}'",
        harness.get_cell(line2_p_col, 3).unwrap_or_default()
    );
    eprintln!(
        "  Line 3: '{}'",
        harness.get_cell(line3_p_col, 4).unwrap_or_default()
    );
    eprintln!(
        "  Line 4: '{}'",
        harness.get_cell(line4_p_col, 5).unwrap_or_default()
    );
    eprintln!(
        "  Line 5: '{}'",
        harness.get_cell(line5_p_col, 6).unwrap_or_default()
    );
    eprintln!(
        "  Line 6: '{}'",
        harness.get_cell(line6_p_col, 7).unwrap_or_default()
    );

    // Check color of number (should be different from keyword if highlighting works)
    // Format: "public int x = N;" - number is at col+15 from 'p'
    // p=0,u=1,b=2,l=3,i=4,c=5,space=6,i=7,n=8,t=9,space=10,x=11,space=12,==13,space=14,N=15
    let num_offset = 15;
    let line1_num_color = get_fg_color(&harness, 2, line1_p_col + num_offset);
    let line6_num_color = get_fg_color(&harness, 7, line6_p_col + num_offset);
    eprintln!("Number colors:");
    eprintln!(
        "  Line 1 number (col {}): {:?}, char: '{}'",
        line1_p_col + num_offset,
        line1_num_color,
        harness
            .get_cell(line1_p_col + num_offset, 2)
            .unwrap_or_default()
    );
    eprintln!(
        "  Line 6 number (col {}): {:?}, char: '{}'",
        line6_p_col + num_offset,
        line6_num_color,
        harness
            .get_cell(line6_p_col + num_offset, 7)
            .unwrap_or_default()
    );

    // Verify keyword and number have different colors (proves highlighting is working)
    assert_ne!(
        line1_p_color, line1_num_color,
        "Keyword 'pub' and number should have different colors. Both are {:?}. \
         This suggests syntax highlighting isn't working.",
        line1_p_color
    );

    // The key assertion: if CRLF highlighting is broken, the colors will differ
    // because the highlight spans are offset and will hit different characters.
    // With 5 CRLFs before line 6, offset drift would shift highlighting by 5 bytes.
    let all_p_colors = [
        line1_p_color,
        line2_p_color,
        line3_p_color,
        line4_p_color,
        line5_p_color,
        line6_p_color,
    ];

    for (i, color) in all_p_colors.iter().enumerate() {
        assert_eq!(
            *color,
            line1_p_color,
            "Line {} 'pub' keyword should have same highlight color as line 1. \
             Line 1: {:?}, Line {}: {:?}. \
             If colors differ, CRLF highlight offset is broken.",
            i + 1,
            line1_p_color,
            i + 1,
            color
        );
    }
}