edamame 0.1.6

A Terminal Markdown editor that stays rendered while you edit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
/// Integration tests for the editing layer.
///
/// These construct an `EditorState`, dispatch sequences of `Action`s, then
/// assert on buffer content and cursor position. They serve as TDD anchors for
/// core editing functionality: insert, delete, newline, undo, redo, cursor movement,
/// mode transitions, save, and clipboard.
use edamame::config::{Action, Theme};
use edamame::document::Buffer;
use edamame::editor::{edit_ops, EditorState, Mode};

const VP: usize = 40; // viewport height for most tests
const VW: usize = 80; // viewport width for most tests

fn theme() -> &'static Theme {
    Box::leak(Box::new(Theme::default()))
}

fn state(text: &str) -> EditorState {
    EditorState::new(Buffer::from_str(text), theme())
}

fn apply(st: &mut EditorState, action: Action) -> bool {
    edit_ops::apply(st, action, VP, VW)
}

fn apply_all(st: &mut EditorState, actions: &[Action]) {
    for a in actions {
        apply(st, a.clone());
    }
}

// ── InsertChar / Newline / DeleteChar ────────────────────────────────────────

#[test]
fn insert_char_enters_edit_mode() {
    // First InsertChar from Preview: mode switches to Rendered but nothing is
    // written (the keystroke is consumed as a mode-activation signal).
    let mut st = state("");
    assert_eq!(st.mode, Mode::Preview);
    apply(&mut st, Action::InsertChar('a'));
    assert_eq!(st.mode, Mode::Rendered);
    assert_eq!(st.contents(), ""); // no char inserted on mode transition
    assert_eq!(st.cursor.offset, 0);

    // Second InsertChar: now in Rendered mode, 'a' is actually inserted.
    apply(&mut st, Action::InsertChar('a'));
    assert_eq!(st.contents(), "a");
    assert_eq!(st.cursor.offset, 1);
}

#[test]
fn insert_multiple_chars() {
    let mut st = state("");
    st.mode = Mode::Rendered; // start in edit mode
    apply_all(
        &mut st,
        &[
            Action::InsertChar('h'),
            Action::InsertChar('e'),
            Action::InsertChar('l'),
            Action::InsertChar('l'),
            Action::InsertChar('o'),
        ],
    );
    assert_eq!(st.contents(), "hello");
    assert_eq!(st.cursor.offset, 5);
}

#[test]
fn newline_splits_line() {
    let mut st = state("");
    st.mode = Mode::Rendered;
    apply_all(
        &mut st,
        &[
            Action::InsertChar('a'),
            Action::InsertChar('b'),
            Action::Newline,
            Action::InsertChar('c'),
        ],
    );
    assert_eq!(st.contents(), "ab\nc");
    assert_eq!(st.cursor.offset, 4);
}

#[test]
fn delete_char_back_basic() {
    let mut st = state("hello");
    st.cursor.offset = 5;
    st.mode = Mode::Rendered;
    apply(&mut st, Action::DeleteCharBack);
    assert_eq!(st.contents(), "hell");
    assert_eq!(st.cursor.offset, 4);
}

#[test]
fn delete_char_back_at_start_is_noop() {
    let mut st = state("hello");
    st.cursor.offset = 0;
    st.mode = Mode::Rendered;
    apply(&mut st, Action::DeleteCharBack);
    assert_eq!(st.contents(), "hello");
    assert_eq!(st.cursor.offset, 0);
}

#[test]
fn delete_char_forward_basic() {
    let mut st = state("hello");
    st.cursor.offset = 2;
    st.mode = Mode::Rendered;
    apply(&mut st, Action::DeleteCharForward);
    assert_eq!(st.contents(), "helo");
    assert_eq!(st.cursor.offset, 2);
}

#[test]
fn delete_char_forward_at_end_is_noop() {
    let mut st = state("hello");
    st.cursor.offset = 5;
    st.mode = Mode::Rendered;
    apply(&mut st, Action::DeleteCharForward);
    assert_eq!(st.contents(), "hello");
    assert_eq!(st.cursor.offset, 5);
}

// ── PR1 — coalesced run entrypoints ─────────────────────────────────────────

#[test]
fn burst_of_inserts_coalesces_into_one_delta() {
    // Holding a key produces a burst of `InsertChar` actions that the
    // run loop collapses into a single `apply_insert_run` call.  One
    // delta, one history entry, one `parsed_version` bump.
    let mut st = state("");
    st.mode = Mode::Rendered;
    let history_before = st.history.undo_depth();
    let version_before = st.parsed_version;

    let chars: Vec<char> = "aaaaaaaaaa".chars().collect();
    edit_ops::apply_insert_run(&mut st, &chars, VP, VW);

    assert_eq!(st.contents(), "aaaaaaaaaa");
    assert_eq!(
        st.history.undo_depth() - history_before,
        1,
        "one history entry for the whole run"
    );
    // The coalesced path bumps `parsed_version` at most twice — once
    // for the in-line apply_delta (so per-frame snapshot caches
    // invalidate at the next draw) and once for the batch-end
    // `flush_parsed_if_dirty` reparse.  Crucially this is O(1) in the
    // run length, not O(N), which is the load-bearing PR1 invariant.
    let bumps = st.parsed_version.wrapping_sub(version_before);
    assert!(bumps <= 2, "expected ≤ 2 parsed_version bumps, got {bumps}");
}

#[test]
fn burst_breaks_on_kind_change() {
    // Alternating Insert / Backspace / Insert is three distinct
    // single-kind runs.  Each goes through its own apply call so the
    // total history depth advances by three, not one.
    let mut st = state("");
    st.mode = Mode::Rendered;
    let history_before = st.history.undo_depth();

    apply(&mut st, Action::InsertChar('a'));
    apply(&mut st, Action::DeleteCharBack);
    apply(&mut st, Action::InsertChar('b'));

    assert_eq!(st.contents(), "b");
    assert_eq!(st.history.undo_depth() - history_before, 3);
}

#[test]
fn delete_run_coalesces_into_one_delta() {
    // A held-Backspace burst removes N graphemes via a single
    // `apply_delete_run` call.
    let mut st = state("abcdef");
    st.mode = Mode::Rendered;
    st.cursor.offset = 6;
    let history_before = st.history.undo_depth();

    edit_ops::apply_delete_run(&mut st, 4, /*backward=*/ true, VP, VW);

    assert_eq!(st.contents(), "ab");
    assert_eq!(st.cursor.offset, 2);
    assert_eq!(st.history.undo_depth() - history_before, 1);
}

#[test]
fn forward_delete_run_coalesces_into_one_delta() {
    let mut st = state("abcdef");
    st.mode = Mode::Rendered;
    st.cursor.offset = 1;
    let history_before = st.history.undo_depth();

    edit_ops::apply_delete_run(&mut st, 3, /*backward=*/ false, VP, VW);

    assert_eq!(st.contents(), "aef");
    assert_eq!(st.cursor.offset, 1);
    assert_eq!(st.history.undo_depth() - history_before, 1);
}

#[test]
fn insert_run_escapes_pipe_inside_table() {
    // Inside a table the per-keystroke `InsertChar('|')` path inserts
    // `\|` so the cell doesn't split.  The coalesced run honours the
    // same rule.
    let mut st = state("|h|w|\n|-|-|\n|a|b|\n");
    st.mode = Mode::Rendered;
    // Position the cursor inside the first body cell ("a").
    st.cursor.offset = 14;
    let before = st.contents();
    edit_ops::apply_insert_run(&mut st, &['|', 'x'], VP, VW);
    let after = st.contents();
    assert!(
        after.contains("\\|x"),
        "expected \\| escape; got: before={:?} after={:?}",
        before,
        after
    );
}

#[test]
fn insert_tab_inserts_four_spaces() {
    let mut st = state("");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::InsertTab);
    assert_eq!(st.contents(), "    ");
    assert_eq!(st.cursor.offset, 4);
}

// ── Undo / Redo ───────────────────────────────────────────────────────────────

#[test]
fn undo_reverses_insert() {
    // Adjacent alphanumeric inserts merge into one undo entry, so "ab" is
    // undone in a single step.  Non-adjacent or non-alphanumeric inserts are
    // treated as separate entries (covered by other tests).
    let mut st = state("");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::InsertChar('a'));
    apply(&mut st, Action::InsertChar('b'));
    assert_eq!(st.contents(), "ab");

    apply(&mut st, Action::Undo);
    assert_eq!(st.contents(), "");
}

#[test]
fn undo_merges_contiguous_inserts_across_character_classes() {
    // Post-PR1: merge-by-contiguity means a held-key burst spanning
    // any character class (letters, punctuation, spaces) is one undo
    // step.  Cursor motion (= non-contiguous offsets) is the boundary.
    let mut st = state("");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::InsertChar('a'));
    apply(&mut st, Action::InsertChar(' '));
    apply(&mut st, Action::InsertChar('b'));
    assert_eq!(st.contents(), "a b");

    apply(&mut st, Action::Undo);
    assert_eq!(st.contents(), "");
}

#[test]
fn undo_past_empty_stack_is_noop() {
    let mut st = state("hello");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::Undo); // no-op, stack is empty
    assert_eq!(st.contents(), "hello");
}

#[test]
fn redo_after_undo() {
    let mut st = state("");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::InsertChar('x'));
    apply(&mut st, Action::Undo);
    assert_eq!(st.contents(), "");

    apply(&mut st, Action::Redo);
    assert_eq!(st.contents(), "x");
    assert_eq!(st.cursor.offset, 1);
}

#[test]
fn redo_cleared_by_new_edit() {
    let mut st = state("");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::InsertChar('a'));
    apply(&mut st, Action::Undo);
    apply(&mut st, Action::InsertChar('b')); // new edit clears redo
    apply(&mut st, Action::Redo); // no-op
    assert_eq!(st.contents(), "b");
}

#[test]
fn undo_delete() {
    let mut st = state("hello");
    st.cursor.offset = 5;
    st.mode = Mode::Rendered;
    apply(&mut st, Action::DeleteCharBack); // "hell"
    assert_eq!(st.contents(), "hell");
    apply(&mut st, Action::Undo);
    assert_eq!(st.contents(), "hello");
}

// ── Cursor movement ───────────────────────────────────────────────────────────

#[test]
fn move_left_right() {
    let mut st = state("hello");
    st.cursor.offset = 2;
    st.mode = Mode::Rendered;

    apply(&mut st, Action::MoveRight);
    assert_eq!(st.cursor.offset, 3);

    apply(&mut st, Action::MoveLeft);
    assert_eq!(st.cursor.offset, 2);
}

#[test]
fn move_up_down() {
    let mut st = state("hello\nworld\n");
    st.cursor.offset = 2; // 'l' in "hello"
    st.cursor.preferred_col = 2;
    st.mode = Mode::Rendered;

    apply(&mut st, Action::MoveDown);
    assert_eq!(st.cursor.offset, 8); // 'r' in "world"

    apply(&mut st, Action::MoveUp);
    assert_eq!(st.cursor.offset, 2); // back to 'l' in "hello"
}

#[test]
fn move_up_in_preview_mode_scrolls() {
    let mut st = state("Hello\nWorld\n");
    assert_eq!(st.mode, Mode::Preview);
    st.scroll = 1;
    apply(&mut st, Action::MoveUp);
    assert_eq!(st.scroll, 0); // scrolled up
    assert_eq!(st.mode, Mode::Preview); // still in preview
}

#[test]
fn move_down_in_preview_mode_scrolls() {
    let mut st = state("Hello\nWorld\n");
    assert_eq!(st.mode, Mode::Preview);
    apply(&mut st, Action::MoveDown);
    // scroll increased (content may not be long enough to scroll, but no panic)
    // Mode should still be Preview.
    assert_eq!(st.mode, Mode::Preview);
}

#[test]
fn move_line_start_end() {
    let mut st = state("hello world");
    st.cursor.offset = 5;
    st.mode = Mode::Rendered;

    apply(&mut st, Action::MoveLineEnd);
    assert_eq!(st.cursor.offset, 11);

    apply(&mut st, Action::MoveLineStart);
    assert_eq!(st.cursor.offset, 0);
}

#[test]
fn move_word_left_right() {
    let mut st = state("hello world");
    st.cursor.offset = 11;
    st.mode = Mode::Rendered;

    apply(&mut st, Action::MoveWordLeft);
    assert_eq!(st.cursor.offset, 6); // start of "world"

    apply(&mut st, Action::MoveWordRight);
    assert_eq!(st.cursor.offset, 11); // past "world"
}

#[test]
fn move_doc_start_end() {
    let mut st = state("hello\nworld\n");
    st.cursor.offset = 6;
    st.mode = Mode::Rendered;

    apply(&mut st, Action::MoveDocEnd);
    assert_eq!(st.cursor.offset, 12); // past trailing newline

    apply(&mut st, Action::MoveDocStart);
    assert_eq!(st.cursor.offset, 0);
}

// ── Mode transitions ─────────────────────────────────────────────────────────

#[test]
fn escape_exits_to_preview() {
    // ExitToPreview action still works when dispatched directly even though
    // Escape is no longer bound to it by default in the keymap.
    let mut st = state("hello");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::InsertChar('x'));
    assert_eq!(st.mode, Mode::Rendered);

    apply(&mut st, Action::ExitToPreview);
    assert_eq!(st.mode, Mode::Preview);
}

#[test]
fn toggle_raw_mode_cycles() {
    let mut st = state("hello");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::InsertChar('x'));
    assert_eq!(st.mode, Mode::Rendered);

    apply(&mut st, Action::ToggleRawMode);
    assert_eq!(st.mode, Mode::Raw);

    apply(&mut st, Action::ToggleRawMode);
    assert_eq!(st.mode, Mode::Rendered);
}

#[test]
fn enter_edit_mode_from_preview() {
    let mut st = state("hello");
    assert_eq!(st.mode, Mode::Preview);

    apply(&mut st, Action::EnterEditMode);
    assert_eq!(st.mode, Mode::Rendered);
}

// ── Delete word / line ────────────────────────────────────────────────────────

#[test]
fn delete_word_back() {
    let mut st = state("hello world");
    st.cursor.offset = 11;
    st.mode = Mode::Rendered;

    apply(&mut st, Action::DeleteWordBack);
    assert_eq!(st.contents(), "hello ");
    assert_eq!(st.cursor.offset, 6);
}

#[test]
fn delete_word_forward() {
    // Emacs-style: deletes the word AND the trailing whitespace (up to the
    // start of the next word).
    let mut st = state("hello world");
    st.cursor.offset = 0;
    st.mode = Mode::Rendered;

    apply(&mut st, Action::DeleteWordForward);
    assert_eq!(st.contents(), "world");
    assert_eq!(st.cursor.offset, 0);
}

#[test]
fn delete_line() {
    let mut st = state("line1\nline2\nline3\n");
    st.cursor.offset = 6; // inside "line2"
    st.mode = Mode::Rendered;

    apply(&mut st, Action::DeleteLine);
    assert_eq!(st.contents(), "line1\nline3\n");
}

// ── SelectAll / clipboard ─────────────────────────────────────────────────────

#[test]
fn select_all_covers_buffer() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;

    apply(&mut st, Action::SelectAll);
    let sel = st.selection.unwrap();
    assert_eq!(sel.anchor, 0);
    assert_eq!(sel.active, 11);
}

#[test]
fn copy_sets_kill_ring() {
    // Copy updates the kill ring regardless of OS clipboard availability.
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::SelectAll);
    apply(&mut st, Action::Copy);
    assert_eq!(st.kill_ring, "hello world");
}

#[test]
fn cut_deletes_selection() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::SelectAll);
    apply(&mut st, Action::Cut);
    assert_eq!(st.contents(), "");
    // Kill ring should have the text.
    assert_eq!(st.kill_ring, "hello world");
}

#[test]
fn paste_from_kill_ring() {
    // Set kill_ring directly; paste falls back to kill ring when OS clipboard is
    // unavailable or doesn't match (tested via kill_ring since clipboard is global
    // and can be noisy in parallel test runs).
    let mut st = state("world");
    st.mode = Mode::Rendered;
    // Copy a known value so kill_ring is set.
    apply(&mut st, Action::SelectAll);
    apply(&mut st, Action::Copy); // kill_ring = "world"
    apply(&mut st, Action::MoveDocEnd);
    st.selection = None;
    // The paste should reproduce what was just copied.
    // We verify kill_ring is correct; actual paste uses kill_ring fallback.
    assert_eq!(st.kill_ring, "world");
}

// ── Dirty flag / Save ─────────────────────────────────────────────────────────

#[test]
fn dirty_flag_set_on_insert() {
    let mut st = state("hello");
    st.mode = Mode::Rendered;
    assert!(!st.dirty);
    apply(&mut st, Action::InsertChar('!'));
    assert!(st.dirty);
}

#[test]
fn save_clears_dirty_flag() {
    // `Action::Save` is intercepted at the App layer
    // (`App::handle_app_action` → `App::save_buffer`) and no longer
    // routes through `edit_ops::apply` — so this integration test
    // drives `Buffer::save_file` directly and mirrors the dirty-flag
    // clear that `App::save_buffer` performs.  The App-level
    // dispatch unification is covered by unit tests in
    // `src/app/actions.rs` and `src/app/modal/command_palette.rs`,
    // which have access to `make_app`.
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("test.md");
    std::fs::write(&path, "hello").unwrap();

    let buf = Buffer::load_file(&path).unwrap();
    let mut st = EditorState::new(buf, theme());
    st.mode = Mode::Rendered;
    // Move cursor to end, then insert.
    apply(&mut st, Action::MoveDocEnd);
    apply(&mut st, Action::InsertChar('!'));
    assert!(st.dirty);
    assert_eq!(st.contents(), "hello!");

    st.buffer.save_file().unwrap();

    // Verify the file was actually written.
    let saved = std::fs::read_to_string(&path).unwrap();
    assert_eq!(saved, "hello!");
}

// ── Replace selection on insert ───────────────────────────────────────────────

#[test]
fn insert_replaces_selection() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    // Select "world"
    use edamame::document::Selection;
    st.selection = Some(Selection {
        anchor: 6,
        active: 11,
    });
    st.cursor.offset = 11;

    apply(&mut st, Action::InsertChar('X'));
    assert_eq!(st.contents(), "hello X");
}

// ── Scroll actions ────────────────────────────────────────────────────────────

#[test]
fn scroll_actions_work_in_preview() {
    // Use separated paragraphs (blank line between) so they render as separate
    // blocks with a blank line each, giving enough rendered lines to scroll.
    let text = "hello\n\nhello\n\n".repeat(30);
    let mut st = state(&text);
    assert_eq!(st.scroll, 0);

    apply(&mut st, Action::ScrollDown);
    assert_eq!(st.scroll, 1);

    apply(&mut st, Action::ScrollUp);
    assert_eq!(st.scroll, 0);

    apply(&mut st, Action::ScrollToBottom);
    assert!(st.scroll > 0);

    apply(&mut st, Action::ScrollToTop);
    assert_eq!(st.scroll, 0);
}

// ── Multi-step editing sequence ───────────────────────────────────────────────

#[test]
fn complex_edit_sequence() {
    let mut st = state("The quick brown fox\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 4; // before "quick"

    // Delete the word "quick "
    apply(&mut st, Action::DeleteWordForward);
    assert_eq!(st.contents(), "The brown fox\n");

    // Insert "slow " in its place
    for ch in "slow ".chars() {
        apply(&mut st, Action::InsertChar(ch));
    }
    assert_eq!(st.contents(), "The slow brown fox\n");

    // Undo all the inserts (5 chars + the delete = 6 undo steps)
    for _ in 0..6 {
        apply(&mut st, Action::Undo);
    }
    assert_eq!(st.contents(), "The quick brown fox\n");
}

// ── Cursor navigation across blank lines ─────────────────────────────────────

/// Pressing MoveDown from the last line of a paragraph that is followed by a
/// blank line should land the cursor on that blank line, and the cursor's
/// buffer-line index should advance by one.  Each blank line is a distinct
/// "virtual block" in the source map, so the cursor must not silently skip it.
#[test]
fn cursor_lands_on_blank_line_between_paragraphs() {
    let mut st = state("First\n\nSecond\n");
    st.mode = Mode::Rendered;
    // Cursor at the end of "First" (buffer line 0, col 5).
    st.cursor.offset = 5;

    apply(&mut st, Action::MoveDown);

    let (line, _col) = st.cursor.line_col(&st.buffer);
    assert_eq!(
        line, 1,
        "cursor should be on the blank line (buffer line 1)"
    );

    // One more MoveDown lands on "Second" (buffer line 2).
    apply(&mut st, Action::MoveDown);
    let (line, _col) = st.cursor.line_col(&st.buffer);
    assert_eq!(line, 2, "cursor should reach 'Second' (buffer line 2)");
}

/// Navigating down through a run of consecutive blank lines should land on
/// each blank line in turn, not skip over them.
#[test]
fn cursor_steps_through_each_blank_line() {
    let mut st = state("A\n\n\nB\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 1; // end of "A" (line 0)

    apply(&mut st, Action::MoveDown);
    assert_eq!(st.cursor.line_col(&st.buffer).0, 1);

    apply(&mut st, Action::MoveDown);
    assert_eq!(st.cursor.line_col(&st.buffer).0, 2);

    apply(&mut st, Action::MoveDown);
    assert_eq!(
        st.cursor.line_col(&st.buffer).0,
        3,
        "should land on 'B' line"
    );
}

// ── Raw mode: cursor is plain-text and doesn't skip table structure ─────────

#[test]
fn raw_mode_cursor_walks_through_table_pipes_one_char_at_a_time() {
    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n";
    let mut st = state(src);
    st.mode = Mode::Raw;
    st.cursor.offset = 0;

    // Walk five chars forward: |, ' ', 'a', ' ', '|'.
    for expected in 1..=5 {
        apply(&mut st, Action::MoveRight);
        assert_eq!(
            st.cursor.offset, expected,
            "raw mode MoveRight should advance one char at a time (got {} at step {expected})",
            st.cursor.offset
        );
    }
}

#[test]
fn raw_mode_down_lands_on_alignment_row() {
    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n";
    let mut st = state(src);
    st.mode = Mode::Raw;
    st.cursor.offset = 2; // inside 'a' in header

    apply(&mut st, Action::MoveDown);
    // In Rendered mode this would skip the alignment row; in Raw it lands on it.
    assert_eq!(st.cursor.line_col(&st.buffer).0, 1);
}

#[test]
fn raw_mode_insert_pipe_is_literal_not_escaped() {
    let src = "| a | b |\n|---|---|\n| 1 | 2 |\n";
    let mut st = state(src);
    st.mode = Mode::Raw;
    // Place cursor inside the first cell and type `|`.
    st.cursor.offset = 2; // just before 'a'
    apply(&mut st, Action::InsertChar('|'));
    // Raw mode: the `|` must appear literally (no `\|` escape).
    assert!(st.contents().contains("| |a | b |"));
    assert!(!st.contents().contains(r"\|"));
}

// ── Image block navigation and source-map stability ──────────────────────────

#[test]
fn cursor_traverses_image_block_as_one_line() {
    // An `![alt](url)` line is ONE logical buffer line, regardless of how
    // many rows its `Block::ImageBlock` reserves in the rendered view.
    // MoveDown from the line before should land on the image's source line,
    // and MoveDown again should land on the next line.
    let src = "Above.\n![cat](cat.png)\nBelow.\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;
    // Start at end of first line.
    st.cursor.offset = st.buffer.line_to_char(0) + 6; // "Above." (6 chars) + 0
    let line_before = st.cursor.line_col(&st.buffer).0;
    assert_eq!(line_before, 0);

    apply(&mut st, Action::MoveDown);
    let line_image = st.cursor.line_col(&st.buffer).0;
    assert_eq!(line_image, 1, "MoveDown should land on image source line");

    apply(&mut st, Action::MoveDown);
    let line_after = st.cursor.line_col(&st.buffer).0;
    assert_eq!(line_after, 2, "MoveDown should land on line below image");
}

/// Rows the block holding `byte` owns in the rendered view.
fn image_block_rows(st: &EditorState, byte: usize) -> usize {
    let idx = st
        .parsed
        .source_map
        .block_for_byte(byte)
        .expect("byte inside a block");
    st.parsed.block_own_line_count(idx)
}

/// An image block reserves its picture's rows, but the source it hides is a
/// single `![alt](url)` line — so while the cursor rests in it the reveal
/// leaves the rest of the reservation as dead blank space unless the block
/// collapses.  Same reflow the mermaid reveal gets, in the other direction.
#[test]
fn revealed_image_collapses_to_its_source_line() {
    let src = "Above.\n\n![cat](cat.png)\n\nBelow.\n";
    let byte = src.find("![cat]").expect("image in fixture");
    // Twelve reserved rows: the decode is Idle in a test, so the renderer
    // falls back to `image_max_height` for stable layout.
    let mut st = EditorState::new_with_config(Buffer::from_str(src), theme(), true, true, 12);
    st.mode = Mode::Rendered;
    assert_eq!(image_block_rows(&st, byte), 12);

    st.cursor.offset = st.buffer.rope().byte_to_char(byte);
    st.update_cursor_block();
    // `update_cursor_block` arms the reveal timer; the reflow is what
    // happens once it elapses, so skip the delay rather than sleep it.
    st.cursor_block_entered_at = None;
    assert!(st.sync_image_reveal(), "entering the block re-lays out");
    assert_eq!(
        image_block_rows(&st, byte),
        1,
        "a revealed image reserves one row for its one source line"
    );
}

#[test]
fn leaving_an_image_restores_its_reservation() {
    let src = "Above.\n\n![cat](cat.png)\n\nBelow.\n";
    let byte = src.find("![cat]").expect("image in fixture");
    let mut st = EditorState::new_with_config(Buffer::from_str(src), theme(), true, true, 12);
    st.mode = Mode::Rendered;
    st.cursor.offset = st.buffer.rope().byte_to_char(byte);
    st.update_cursor_block();
    st.cursor_block_entered_at = None;
    st.sync_image_reveal();
    assert_eq!(image_block_rows(&st, byte), 1);

    let below = src.find("Below.").expect("trailer in fixture");
    st.cursor.offset = st.buffer.rope().byte_to_char(below);
    st.update_cursor_block();
    st.cursor_block_entered_at = None;
    assert!(st.sync_image_reveal(), "leaving the block re-lays out");
    assert_eq!(
        image_block_rows(&st, byte),
        12,
        "the picture's rows come back once the cursor leaves"
    );
}

#[test]
fn preview_mode_never_collapses_an_image() {
    // Preview is browse-only: no reveal, so no reflow.
    let src = "Above.\n\n![cat](cat.png)\n\nBelow.\n";
    let byte = src.find("![cat]").expect("image in fixture");
    let mut st = EditorState::new_with_config(Buffer::from_str(src), theme(), true, true, 12);
    st.mode = Mode::Preview;
    st.cursor.offset = st.buffer.rope().byte_to_char(byte);
    st.update_cursor_block();
    st.cursor_block_entered_at = None;
    assert!(!st.sync_image_reveal());
    assert_eq!(image_block_rows(&st, byte), 12);
}

/// The reveal names its block by ordinal *and* URL, because a document can
/// use one image twice (a logo in a header and a footer).  Keyed on the URL
/// alone, revealing either copy collapsed both — the untouched one's picture
/// squeezed into a single row, and every line below it jumping up for as
/// long as the cursor rested in the other.
#[test]
fn revealing_one_image_leaves_a_duplicate_of_it_alone() {
    let src = "![cat](cat.png)\n\nMiddle.\n\n![cat](cat.png)\n\nBelow.\n";
    let first = src.find("![cat]").expect("first image in fixture");
    let second = src.rfind("![cat]").expect("second image in fixture");
    let mut st = EditorState::new_with_config(Buffer::from_str(src), theme(), true, true, 12);
    st.mode = Mode::Rendered;
    assert_eq!(image_block_rows(&st, first), 12);
    assert_eq!(image_block_rows(&st, second), 12);

    st.cursor.offset = st.buffer.rope().byte_to_char(first);
    st.update_cursor_block();
    st.cursor_block_entered_at = None;
    assert!(st.sync_image_reveal(), "entering the block re-lays out");
    assert_eq!(
        image_block_rows(&st, first),
        1,
        "the revealed copy collapses"
    );
    assert_eq!(
        image_block_rows(&st, second),
        12,
        "the duplicate keeps its picture's rows"
    );

    // And the other way round, so the ordinal isn't just pinned at 0.
    st.cursor.offset = st.buffer.rope().byte_to_char(second);
    st.update_cursor_block();
    st.cursor_block_entered_at = None;
    assert!(st.sync_image_reveal(), "moving between them re-lays out");
    assert_eq!(image_block_rows(&st, first), 12);
    assert_eq!(image_block_rows(&st, second), 1);
}

#[test]
fn typing_next_to_image_block_keeps_source_map_consistent() {
    // Editing text adjacent to an image block must not corrupt the source
    // map — every buffer byte must map to some rendered line.
    let src = "Intro.\n\n![cat](cat.png)\n\nEnd.\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;
    // Move cursor to end of "End." and append more text.
    let last_line = st.buffer.line_count() - 2; // "End." (last line before trailing newline)
    let line_start = st.buffer.line_to_char(last_line);
    st.cursor.offset = line_start + 4; // after "End."
    apply_all(
        &mut st,
        &[
            Action::InsertChar('!'),
            Action::InsertChar(' '),
            Action::InsertChar('X'),
        ],
    );
    // Source map should still map every byte of the buffer.
    let src_now = st.contents();
    for b in 0..src_now.len() {
        let range = st.parsed.source_map.rendered_lines_for_byte(b);
        assert!(
            !range.is_empty(),
            "byte {} in {src_now:?} lost its rendered-line mapping",
            b,
        );
    }
}

#[test]
fn editor_state_tracks_image_block_urls_in_parsed_doc() {
    // EditorState::parsed.image_blocks is populated from the parse and
    // used by the App to dispatch decodes.  Verify round-trip.
    let src = "![a](a.png)\n\n![b](http://example.com/b.jpg)\n\nplain paragraph\n";
    let st = state(src);
    let urls: Vec<&str> = st
        .parsed
        .image_blocks
        .iter()
        .map(|b| b.url.as_str())
        .collect();
    assert_eq!(urls, vec!["a.png", "http://example.com/b.jpg"]);
}

#[test]
fn image_cache_survives_reparse_on_unrelated_edit() {
    // Architectural invariant: the decoded-image cache lives on
    // EditorState::images (URL-keyed) rather than ParsedDoc, so editing
    // text elsewhere in the document does not invalidate expensive
    // image decodes / protocol encodings.
    use edamame::image::DecodeStatus;
    let src = "Intro.\n\n![cat](cat.png)\n\nEnd.\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;

    // Simulate a completed decode by inserting a fake entry.
    st.images.request("cat.png");
    st.images
        .set_decoded("cat.png", image::DynamicImage::new_rgba8(1, 1));
    assert!(matches!(
        st.images.status("cat.png"),
        Some(DecodeStatus::Ready(_))
    ));

    // Perform an edit that reparses — append a char at the document end.
    st.cursor.offset = st.buffer.len_chars();
    apply(&mut st, Action::InsertChar('Z'));

    // The cache entry for cat.png should still be there.
    assert!(matches!(
        st.images.status("cat.png"),
        Some(DecodeStatus::Ready(_))
    ));
    // And the image block is still in the reparsed doc.
    assert_eq!(st.parsed.image_blocks.len(), 1);
    assert_eq!(st.parsed.image_blocks[0].url, "cat.png");
}

// ── HTML comment hiding ───────────────────────────────────────────────────────

/// Pressing Down from the line immediately preceding a hidden HTML comment
/// must skip over the comment's source bytes: the comment block has zero
/// rendered lines, so stopping there would leave the cursor on a line the
/// user can't see in hybrid view.  The cursor should emerge on or past
/// the next visible block.
#[test]
fn down_arrow_past_block_comment_skips_hidden_bytes() {
    let src = "Alpha.\n\n<!-- hidden -->\n\nBeta.\n";
    let mut st = state(src);
    apply(&mut st, Action::EnterEditMode);

    // Park the cursor on the blank line just before the comment (byte just
    // before `<!--`).  That position is "visible" — a blank-line virtual
    // block owning one rendered row — so the down step fires against a
    // normal starting point.
    let comment_byte = src.find("<!--").unwrap();
    let blank_before_byte = comment_byte.saturating_sub(1);
    st.cursor.offset = st.buffer.rope().byte_to_char(blank_before_byte);
    st.update_cursor_block();

    apply(&mut st, Action::MoveDown);

    // After one Down, the cursor must NOT be sitting inside the comment's
    // source bytes — either because we jumped straight past it or landed
    // on the trailing blank line.  Either way the block under the cursor
    // has non-zero rendered-line count.
    let rope = st.buffer.rope();
    let cursor_byte = rope.char_to_byte(st.cursor.offset);
    let block_idx = st
        .parsed
        .source_map
        .block_for_byte(cursor_byte)
        .expect("cursor byte must map to a block");
    assert!(
        st.parsed.block_own_line_count(block_idx) > 0,
        "cursor landed in a hidden block at byte {cursor_byte}"
    );
    // The cursor must have advanced past the comment's start byte too —
    // otherwise "skipping" degenerated into "staying put".
    assert!(
        cursor_byte > comment_byte,
        "cursor did not move past the comment: at byte {cursor_byte}, comment starts at {comment_byte}"
    );
}

/// Toggling Raw → Rendered with the cursor sitting inside a hidden comment
/// block should snap the cursor to the start of the next visible block so
/// `RenderedView` has a well-defined cursor position to draw against.
#[test]
fn toggle_raw_to_rendered_snaps_cursor_out_of_comment() {
    let src = "Alpha.\n\n<!-- hidden -->\n\nBeta.\n";
    let mut st = state(src);
    // Enter Rendered, then Raw.
    apply(&mut st, Action::EnterEditMode);
    apply(&mut st, Action::ToggleRawMode);
    assert_eq!(st.mode, Mode::Raw);

    // Park the cursor on the first char of the comment — visible in Raw.
    let comment_byte = src.find("<!--").unwrap();
    st.cursor.offset = st.buffer.rope().byte_to_char(comment_byte);
    st.update_cursor_block();

    // Toggle back to Rendered: the mode-switch handler must detect that the
    // cursor is inside a hidden block and move it forward to a visible one.
    apply(&mut st, Action::ToggleRawMode);
    assert_eq!(st.mode, Mode::Rendered);

    let rope = st.buffer.rope();
    let cursor_byte = rope.char_to_byte(st.cursor.offset);
    let block_idx = st
        .parsed
        .source_map
        .block_for_byte(cursor_byte)
        .expect("cursor byte must map to a block");
    assert!(
        st.parsed.block_own_line_count(block_idx) > 0,
        "cursor landed in a zero-own block after Raw→Rendered snap (byte {cursor_byte})"
    );
}

/// Switching between Rendered and Raw must keep the cursor on the same
/// screen row.  The two modes use different scroll units (rendered lines
/// vs. buffer lines), so without an adjustment the same `scroll` value
/// often pushes the cursor far away from where it was — sometimes
/// off-screen entirely.
#[test]
fn toggle_raw_mode_preserves_cursor_screen_row() {
    let mut src = String::new();
    for i in 0..30 {
        src.push_str(&format!("line {i}\n"));
    }
    let mut st = state(&src);
    // Enter Rendered with the cursor near the middle of the document.
    apply(&mut st, Action::EnterEditMode);
    st.cursor.offset = st.buffer.line_to_char(15);
    st.update_cursor_block();
    st.scroll = 12; // cursor at screen row 3.

    let row_before_first_toggle = st.cursor_screen_row(VW);

    apply(&mut st, Action::ToggleRawMode);
    assert_eq!(st.mode, Mode::Raw);
    assert_eq!(st.cursor_screen_row(VW), row_before_first_toggle);

    apply(&mut st, Action::ToggleRawMode);
    assert_eq!(st.mode, Mode::Rendered);
    assert_eq!(st.cursor_screen_row(VW), row_before_first_toggle);
}

/// When the cursor sits at the bottom of the visible viewport and the user
/// types a `\n`, the new cursor position is on a fresh line that's one
/// row below the previous bottom.  The viewport must scroll one row down
/// so the cursor stays visible.
#[test]
fn newline_at_viewport_bottom_scrolls_to_keep_cursor_visible() {
    let mut src = String::new();
    for i in 0..40 {
        src.push_str(&format!("line {i}\n"));
    }
    let vp_h = 10;
    let vp_w = 40;
    let mut st = state(&src);
    st.mode = Mode::Raw;
    // Park the cursor at the end of the bottom-most visible line.
    st.scroll = 5;
    let cursor_line = st.scroll + vp_h - 1; // last visible line
    let line_start = st.buffer.line_to_char(cursor_line);
    let line_text = st.buffer.line(cursor_line).unwrap_or_default();
    let line_len = line_text.trim_end_matches('\n').chars().count();
    st.cursor.offset = line_start + line_len;
    st.cursor.preferred_col = line_len;
    st.update_cursor_block();

    let scroll_before = st.scroll;
    edit_ops::apply(&mut st, Action::Newline, vp_h, vp_w);

    assert!(
        st.scroll > scroll_before,
        "scroll {} did not advance after newline at viewport bottom",
        st.scroll
    );

    // Cursor must remain inside the viewport.
    let (cursor_line_after, _) = st.cursor.line_col(&st.buffer);
    assert!(cursor_line_after >= st.scroll && cursor_line_after < st.scroll + vp_h);
}

/// In Raw mode, typing a character that extends a line past the viewport
/// width — pushing the cursor onto a new VISUAL row (wrap), without
/// adding a `\n` — must scroll the document so the cursor remains
/// visible.  Previously `ensure_cursor_visible` only checked buffer-line
/// coordinates and missed the wrap.
#[test]
fn type_at_viewport_bottom_wraps_and_scrolls_in_raw_mode() {
    // Document of identical short lines, with the bottom-most visible line
    // intentionally long enough that one more keystroke wraps it.
    let mut src = String::new();
    for _ in 0..40 {
        src.push_str("short\n");
    }
    let vp_h = 10;
    let vp_w = 20;
    let mut st = state(&src);
    st.mode = Mode::Raw;
    st.scroll = 0;

    // Pad the bottom-most visible line to exactly vp_w chars so that the
    // next typed char overflows and wraps onto a new visual row.
    let cursor_line = vp_h - 1;
    let pad = "X".repeat(vp_w - "short".len());
    let line_start = st.buffer.line_to_char(cursor_line);
    st.buffer.insert(line_start + "short".len(), &pad);
    // Cursor at end of that line.
    let line_text = st.buffer.line(cursor_line).unwrap_or_default();
    let line_len = line_text.trim_end_matches('\n').chars().count();
    st.cursor.offset = line_start + line_len;
    st.cursor.preferred_col = line_len;
    st.update_cursor_block();

    let scroll_before = st.scroll;
    edit_ops::apply(&mut st, Action::InsertChar('Y'), vp_h, vp_w);

    assert!(
        st.scroll > scroll_before,
        "scroll {} did not advance after a wrap-inducing keystroke (cursor on visual row past viewport bottom)",
        st.scroll
    );
}

/// Same scenario as `type_at_viewport_bottom_wraps_and_scrolls_in_raw_mode`,
/// but in Rendered mode.  The deferred-reparse optimization leaves
/// `parsed.lines` and the visual-row cache stale after an in-line edit, so
/// without an explicit flush the wrap check would miss the new visual row.
#[test]
fn type_at_viewport_bottom_wraps_and_scrolls_in_rendered_mode() {
    let vp_h = 10;
    let vp_w = 20;
    // 40-line paragraph (single block via soft breaks).  The bottom-most
    // visible line is padded to exactly `vp_w` chars so one more typed
    // char wraps it onto a new visual row.
    let mut src = String::new();
    for i in 0..40 {
        let prefix = format!("s{i}");
        if i == vp_h - 1 {
            src.push_str(&prefix);
            src.push_str(&"X".repeat(vp_w - prefix.len()));
            src.push('\n');
        } else {
            src.push_str(&prefix);
            src.push('\n');
        }
    }
    let mut st = state(&src);
    // This exercises scroll-on-wrap with the deferred-reparse flush, using a soft-broken block as
    // a stack of one-per-source-line rendered rows.  Reflow (default on) would instead join them
    // into one flow, changing the geometry the setup depends on — disable it, the mechanic under
    // test is independent of reflow.
    st.set_reflow(false);
    apply(&mut st, Action::EnterEditMode);
    st.scroll = 0;

    let cursor_buf_line = vp_h - 1;
    let line_start = st.buffer.line_to_char(cursor_buf_line);
    let line_text = st.buffer.line(cursor_buf_line).unwrap_or_default();
    let line_len = line_text.trim_end_matches('\n').chars().count();
    assert_eq!(line_len, vp_w, "line padding length is wrong");
    st.cursor.offset = line_start + line_len;
    st.cursor.preferred_col = line_len;
    st.update_cursor_block();

    let scroll_before = st.scroll;
    edit_ops::apply(&mut st, Action::InsertChar('Y'), vp_h, vp_w);

    assert!(
        st.scroll > scroll_before,
        "scroll {} did not advance after wrap-inducing keystroke in Rendered mode",
        st.scroll
    );
}

// ── Grapheme-aware editing on multi-codepoint clusters ───────────────────────

/// Sit the cursor immediately after the family-emoji cluster and Backspace.
/// The whole 7-char ZWJ sequence must vanish in one keystroke — leaving any
/// fragment behind would render as garbage.
#[test]
fn delete_char_back_removes_full_zwj_grapheme() {
    let mut st = state("a👨\u{200D}👩\u{200D}👧\u{200D}👦b");
    st.mode = Mode::Rendered;
    st.cursor.offset = 8; // after the family, before 'b'
    apply(&mut st, Action::DeleteCharBack);
    assert_eq!(st.contents(), "ab");
    assert_eq!(st.cursor.offset, 1);
}

#[test]
fn delete_char_forward_removes_full_zwj_grapheme() {
    let mut st = state("a👨\u{200D}👩\u{200D}👧\u{200D}👦b");
    st.mode = Mode::Rendered;
    st.cursor.offset = 1; // before the family
    apply(&mut st, Action::DeleteCharForward);
    assert_eq!(st.contents(), "ab");
    assert_eq!(st.cursor.offset, 1);
}

/// Combining mark deletes with the base character — "é" (e + U+0301) is one
/// grapheme even though it's two chars.
#[test]
fn delete_char_back_removes_combining_mark_with_base() {
    let mut st = state("e\u{0301}!");
    st.mode = Mode::Rendered;
    st.cursor.offset = 2; // after the combining mark
    apply(&mut st, Action::DeleteCharBack);
    assert_eq!(st.contents(), "!");
    assert_eq!(st.cursor.offset, 0);
}

/// MoveLeft / MoveRight in Raw mode must also step by grapheme — the user
/// wanted Raw mode for raw *Markdown*, not raw codepoints.
#[test]
fn move_right_in_raw_mode_steps_over_grapheme() {
    let mut st = state("a👨\u{200D}👩\u{200D}👧\u{200D}👦b");
    st.mode = Mode::Raw;
    st.cursor.offset = 1; // before the family
    apply(&mut st, Action::MoveRight);
    assert_eq!(st.cursor.offset, 8); // landed past the whole grapheme
}

// ── Bold / italic formatting ──────────────────────────────────────────────────

fn select(st: &mut EditorState, anchor: usize, active: usize) {
    use edamame::document::Selection;
    st.selection = Some(Selection { anchor, active });
    st.cursor.offset = active;
}

#[test]
fn bold_wraps_selection_and_reselects_inner() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    select(&mut st, 6, 11); // "world"
    apply(&mut st, Action::BoldSelection);
    assert_eq!(st.contents(), "hello **world**");
    // Inner text stays selected (now shifted past the opening markers) so a
    // follow-up format can be chained.
    let sel = st.selection.expect("selection retained");
    assert_eq!(sel.range(), (8, 13));
    assert_eq!(sel.selected_text(&st.buffer), "world");
}

#[test]
fn italic_wraps_selection() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    select(&mut st, 6, 11);
    apply(&mut st, Action::ItalicizeSelection);
    assert_eq!(st.contents(), "hello *world*");
}

#[test]
fn bold_then_italic_chains() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    select(&mut st, 6, 11);
    apply(&mut st, Action::BoldSelection);
    apply(&mut st, Action::ItalicizeSelection);
    assert_eq!(st.contents(), "hello ***world***");
}

#[test]
fn bold_toggles_off_when_selection_includes_markers() {
    let mut st = state("hello **world**");
    st.mode = Mode::Rendered;
    select(&mut st, 6, 15); // "**world**"
    apply(&mut st, Action::BoldSelection);
    assert_eq!(st.contents(), "hello world");
    assert_eq!(st.selection.unwrap().range(), (6, 11));
}

#[test]
fn bold_strips_markers_just_outside_selection() {
    let mut st = state("hello **world**");
    st.mode = Mode::Rendered;
    select(&mut st, 8, 13); // inner "world" only
    apply(&mut st, Action::BoldSelection);
    assert_eq!(st.contents(), "hello world");
    assert_eq!(st.selection.unwrap().range(), (6, 11));
}

#[test]
fn italic_over_bold_wraps_rather_than_strips() {
    // Italic must not mistake bold's `**` markers for its own `*` and strip
    // one layer — it wraps, producing bold+italic.
    let mut st = state("**bar**");
    st.mode = Mode::Rendered;
    select(&mut st, 2, 5); // inner "bar"
    apply(&mut st, Action::ItalicizeSelection);
    assert_eq!(st.contents(), "***bar***");
}

#[test]
fn bold_without_selection_is_noop() {
    let mut st = state("hello");
    st.mode = Mode::Rendered;
    apply(&mut st, Action::BoldSelection);
    assert_eq!(st.contents(), "hello");
}

#[test]
fn bold_refuses_multiline_selection() {
    // Emphasis can't span a block boundary; a multi-line selection is left
    // untouched rather than producing literal asterisks.
    let mut st = state("foo\nbar");
    st.mode = Mode::Rendered;
    select(&mut st, 0, 7);
    apply(&mut st, Action::BoldSelection);
    assert_eq!(st.contents(), "foo\nbar");
}

#[test]
fn bold_with_interior_markers_wraps_not_unwraps() {
    // A selection that merely starts and ends with `**` but has more emphasis
    // inside must not be mis-unwrapped (which would strip only the outer pair
    // and emit malformed markdown). It is wrapped verbatim instead.
    let mut st = state("**a** and **b**");
    st.mode = Mode::Rendered;
    select(&mut st, 0, 15);
    apply(&mut st, Action::BoldSelection);
    assert_eq!(st.contents(), "****a** and **b****");
}

#[test]
fn bold_wraps_mixed_selection_verbatim() {
    // A selection that already contains inline formatting is wrapped as-is —
    // AST-aware merging is intentionally out of scope for this convenience
    // action.
    let mut st = state("foo **x** baz");
    st.mode = Mode::Rendered;
    select(&mut st, 0, 13);
    apply(&mut st, Action::BoldSelection);
    assert_eq!(st.contents(), "**foo **x** baz**");
}

// ── Inline code / strikethrough / highlight formatting ──────────────────────

#[test]
fn inline_code_wraps_selection_and_reselects_inner() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    select(&mut st, 6, 11); // "world"
    apply(&mut st, Action::InlineCodeSelection);
    assert_eq!(st.contents(), "hello `world`");
    let sel = st.selection.expect("selection retained");
    assert_eq!(sel.selected_text(&st.buffer), "world");
}

#[test]
fn inline_code_toggles_off_when_selection_includes_markers() {
    let mut st = state("hello `world`");
    st.mode = Mode::Rendered;
    select(&mut st, 6, 13); // "`world`"
    apply(&mut st, Action::InlineCodeSelection);
    assert_eq!(st.contents(), "hello world");
    assert_eq!(st.selection.unwrap().range(), (6, 11));
}

#[test]
fn strikethrough_wraps_selection() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    select(&mut st, 6, 11);
    apply(&mut st, Action::StrikethroughSelection);
    assert_eq!(st.contents(), "hello ~~world~~");
}

#[test]
fn strikethrough_strips_markers_just_outside_selection() {
    let mut st = state("hello ~~world~~");
    st.mode = Mode::Rendered;
    select(&mut st, 8, 13); // inner "world" only
    apply(&mut st, Action::StrikethroughSelection);
    assert_eq!(st.contents(), "hello world");
    assert_eq!(st.selection.unwrap().range(), (6, 11));
}

#[test]
fn highlight_wraps_and_unwraps_selection() {
    let mut st = state("hello world");
    st.mode = Mode::Rendered;
    select(&mut st, 6, 11);
    apply(&mut st, Action::HighlightSelection);
    assert_eq!(st.contents(), "hello ==world==");
    // Inner text is reselected — a second press toggles back off.
    apply(&mut st, Action::HighlightSelection);
    assert_eq!(st.contents(), "hello world");
}

#[test]
fn inline_code_refuses_multiline_selection() {
    let mut st = state("foo\nbar");
    st.mode = Mode::Rendered;
    select(&mut st, 0, 7);
    apply(&mut st, Action::InlineCodeSelection);
    assert_eq!(st.contents(), "foo\nbar");
}

// ── Footnotes ────────────────────────────────────────────────────────────────

fn put_cursor(st: &mut EditorState, byte: usize) {
    st.cursor.offset = st.buffer.rope().byte_to_char(byte);
}

#[test]
fn insert_footnote_auto_numbers_and_undoes_atomically() {
    let mut st = state("Claim.\n\n[^1]: prior note.\n");
    st.mode = Mode::Rendered;
    put_cursor(&mut st, "Claim.".len());
    edit_ops::insert_footnote_at_cursor(&mut st, VP, VW);
    assert!(
        st.contents().starts_with("Claim.[^2]"),
        "got: {:?}",
        st.contents()
    );
    apply(&mut st, Action::Undo);
    assert!(
        st.contents().starts_with("Claim.\n"),
        "got: {:?}",
        st.contents()
    );
}

#[test]
fn renumber_footnotes_action_reorders_by_reference() {
    let mut st = state("A[^2] B[^1]\n\n[^2]: two\n[^1]: one\n");
    st.mode = Mode::Rendered;
    let changed = edit_ops::renumber_footnotes(&mut st, VP, VW);
    assert!(changed);
    assert_eq!(st.contents(), "A[^1] B[^2]\n\n[^1]: two\n[^2]: one\n");
    // No-op when already sequential.
    assert!(!edit_ops::renumber_footnotes(&mut st, VP, VW));
}

#[test]
fn delete_footnote_action_removes_renumbers_and_undoes_atomically() {
    let original = "A[^1] B[^2]\n\n[^1]: one\n[^2]: two\n";
    let mut st = state(original);
    st.mode = Mode::Rendered;
    put_cursor(&mut st, 1); // on the `[` of `[^1]`
    let removed = edit_ops::delete_footnote_at_cursor(&mut st, VP, VW);
    assert!(removed);
    assert_eq!(st.contents(), "A B[^1]\n\n[^1]: two\n");
    // The whole delete+renumber reverses in a single undo.
    apply(&mut st, Action::Undo);
    assert_eq!(st.contents(), original);
}

#[test]
fn delete_footnote_off_a_footnote_is_noop() {
    let mut st = state("plain text\n");
    st.mode = Mode::Rendered;
    put_cursor(&mut st, 3);
    assert!(!edit_ops::delete_footnote_at_cursor(&mut st, VP, VW));
    assert_eq!(st.contents(), "plain text\n");
}

// ── Insert image / link snippets ─────────────────────────────────────────────

#[test]
fn insert_link_snippet_selects_text_placeholder() {
    let mut st = state("hello world\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 6; // just before "world"
    edit_ops::insert_link_at_cursor(&mut st, VP, VW);
    assert_eq!(st.contents(), "hello [link text](file path or URL)world\n");
    let (s, e) = st
        .selection
        .expect("placeholder should be selected")
        .range();
    assert_eq!(st.buffer.slice_to_string(s, e), "link text");
    // Typing replaces the selected placeholder in place.
    apply(&mut st, Action::InsertChar('x'));
    assert_eq!(st.contents(), "hello [x](file path or URL)world\n");
}

#[test]
fn insert_image_wraps_selection_and_selects_url_placeholder() {
    use edamame::document::Selection;
    let mut st = state("hello world\n");
    st.mode = Mode::Rendered;
    st.selection = Some(Selection {
        anchor: 6,
        active: 11, // "world"
    });
    st.cursor.offset = 11;
    edit_ops::insert_image_at_cursor(&mut st, VP, VW);
    assert_eq!(st.contents(), "hello ![world](file path or URL)\n");
    let (s, e) = st
        .selection
        .expect("URL placeholder should be selected")
        .range();
    assert_eq!(st.buffer.slice_to_string(s, e), "file path or URL");
}

#[test]
fn insert_image_reference_lands_as_its_own_paragraph() {
    // The parse promotes an image to a block only when it is a
    // paragraph's sole content, so a pasted reference is framed with the
    // blank line it needs — left flush it stays inline and paints as a
    // text placeholder instead of the image.
    let mut st = state("prose\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 6;
    edit_ops::insert_image_reference_at_cursor(&mut st, "C:/x/y.png", VP, VW);
    assert_eq!(st.contents(), "prose\n\n![](C:/x/y.png)\n");
}

#[test]
fn insert_image_reference_splits_the_line_it_lands_on() {
    let mut st = state("alpha\nbeta\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 2; // mid-word, after "al"
    edit_ops::insert_image_reference_at_cursor(&mut st, "img.png", VP, VW);
    assert_eq!(st.contents(), "al\n\n![](img.png)\n\npha\nbeta\n");
    assert_eq!(
        st.cursor.offset,
        "al\n\n![".len(),
        "the cursor waits in the empty alt text"
    );
}

#[test]
fn insert_image_reference_at_the_start_lands_in_the_alt_text() {
    let mut st = state("");
    st.mode = Mode::Rendered;
    edit_ops::insert_image_reference_at_cursor(&mut st, "img.png", VP, VW);
    assert_eq!(st.contents(), "![](img.png)\n");
    assert_eq!(st.cursor.offset, "![".len());
    assert!(st.selection.is_none());
}

#[test]
fn insert_image_reference_with_a_selection_lands_past_it() {
    // The selection became the alt text, so there is nothing left to type into the brackets.
    use edamame::document::Selection;
    let mut st = state("a shot\n");
    st.mode = Mode::Rendered;
    st.selection = Some(Selection {
        anchor: 0,
        active: 6,
    });
    st.cursor.offset = 6;
    edit_ops::insert_image_reference_at_cursor(&mut st, "img.png", VP, VW);
    assert_eq!(st.contents(), "![a shot](img.png)\n");
    assert_eq!(st.cursor.offset, "![a shot](img.png)".len());
}

#[test]
fn insert_image_reference_is_separated_from_the_paragraph_below() {
    let mut st = state("prose\n\nnext\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 7; // start of "next"
    edit_ops::insert_image_reference_at_cursor(&mut st, "img.png", VP, VW);
    assert_eq!(st.contents(), "prose\n\n![](img.png)\n\nnext\n");
}

#[test]
fn insert_image_reference_at_a_line_end_adds_the_blank_line_below() {
    let mut st = state("prose\nnext\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 5; // end of "prose"
    edit_ops::insert_image_reference_at_cursor(&mut st, "img.png", VP, VW);
    assert_eq!(st.contents(), "prose\n\n![](img.png)\n\nnext\n");
}

#[test]
fn insert_image_reference_escapes_the_destination() {
    let mut st = state("");
    st.mode = Mode::Rendered;
    edit_ops::insert_image_reference_at_cursor(&mut st, "a b/image (1).png", VP, VW);
    assert_eq!(st.contents(), "![](<a b/image (1).png>)\n");
}

#[test]
fn insert_image_reference_in_a_table_goes_inline_in_the_cell() {
    // A cell holds only inline content, so the blank lines that make a block image would split
    // the table; an inline image in a cell is valid GFM.
    let src = "| a | b |\n|---|---|\n| c | d |\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;
    st.cursor.offset = src.find("d |").unwrap();
    edit_ops::insert_image_reference_at_cursor(&mut st, "img.png", VP, VW);
    assert_eq!(
        st.contents(),
        "| a | b |\n|---|---|\n| c | ![](img.png)d |\n"
    );
    assert_eq!(
        st.cursor.offset,
        src.find("d |").unwrap() + "![".len(),
        "the cursor waits in the empty alt text"
    );
}

#[test]
fn insert_image_reference_in_a_container_goes_inline_and_keeps_it_whole() {
    // Framing with blank lines would end the container: an unindented paragraph after a blank
    // line leaves a list, a quote or a footnote, taking the rest of the line with it.
    for (src, at, expected) in [
        ("- item\n- two\n", "em", "- it![](img.png)em\n- two\n"),
        ("- item\n- two\n", "\n- two", "- item![](img.png)\n- two\n"),
        (
            "1. one\n   more\n",
            "\n   more",
            "1. one![](img.png)\n   more\n",
        ),
        ("> quote text\n", " text", "> quote![](img.png) text\n"),
        (
            "Note[^1].\n\n[^1]: the note\n",
            " note",
            "Note[^1].\n\n[^1]: the![](img.png) note\n",
        ),
    ] {
        let mut st = state(src);
        st.mode = Mode::Rendered;
        st.cursor.offset = src.find(at).unwrap();
        assert!(edit_ops::insert_image_reference_at_cursor(
            &mut st, "img.png", VP, VW
        ));
        assert_eq!(st.contents(), expected, "source was {src:?}");
        assert_eq!(
            st.cursor.offset,
            src.find(at).unwrap() + "![".len(),
            "the cursor waits in the empty alt text: {src:?}"
        );
    }
}

#[test]
fn can_insert_image_reference_in_preview_judges_the_synced_spot_without_moving() {
    // Off screen in Preview, the insert would sync the cursor to the top of the view — a code
    // block here — so the check refuses, and must leave the cursor where it was.
    let src = "```\ncode\n```\n\nprose\n";
    let mut st = state(src);
    st.mode = Mode::Preview;
    st.scroll = 0;
    let offset = src.find("prose").unwrap();
    st.cursor.offset = offset;
    assert!(!edit_ops::can_insert_image_reference(&mut st, 1));
    assert_eq!(st.cursor.offset, offset);
    assert_eq!(st.mode, Mode::Preview);
}

#[test]
fn can_insert_image_reference_on_the_blank_line_after_a_block_that_absorbs_it() {
    // pulldown-cmark's range for an indented code block or an HTML block runs past the blank
    // line after it.  The blank is still a blank line, where an image becomes its own paragraph;
    // inside the block itself the insert stays refused.
    for (src, inside) in [
        ("    code\n\nprose\n", "code"),
        ("<div>x</div>\n\nprose\n", "x"),
    ] {
        let mut st = state(src);
        st.mode = Mode::Rendered;
        st.cursor.offset = src.find("\n\n").unwrap() + 1;
        assert!(
            edit_ops::can_insert_image_reference(&mut st, 24),
            "on the blank line in {src:?}"
        );
        st.cursor.offset = src.find(inside).unwrap();
        assert!(
            !edit_ops::can_insert_image_reference(&mut st, 24),
            "inside the block in {src:?}"
        );
    }
}

#[test]
fn insert_image_reference_in_a_table_nested_in_a_quote_escapes_pipes() {
    // The block lookup sees the quote, not the table inside it, so every container escapes `|`.
    let src = "> | a |\n> |---|\n> | c |\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;
    st.cursor.offset = src.find("c |").unwrap() + 1;
    edit_ops::insert_image_reference_at_cursor(&mut st, "a|b.png", VP, VW);
    assert_eq!(st.contents(), "> | a |\n> |---|\n> | c![](a\\|b.png) |\n");
}

#[test]
fn insert_image_reference_in_a_table_escapes_pipes() {
    let src = "| a |\n|---|\n| c |\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;
    st.cursor.offset = src.find("c |").unwrap() + 1;
    edit_ops::insert_image_reference_at_cursor(&mut st, "a|b.png", VP, VW);
    assert_eq!(st.contents(), "| a |\n|---|\n| c![](a\\|b.png) |\n");
}

#[test]
fn insert_image_reference_outside_a_table_leaves_pipes_alone() {
    let mut st = state("");
    st.mode = Mode::Rendered;
    edit_ops::insert_image_reference_at_cursor(&mut st, "a|b.png", VP, VW);
    assert_eq!(st.contents(), "![](a|b.png)\n");
}

#[test]
fn insert_image_reference_needs_no_extra_break_after_a_blank_line() {
    let mut st = state("prose\n\n");
    st.mode = Mode::Rendered;
    st.cursor.offset = 7;
    edit_ops::insert_image_reference_at_cursor(&mut st, "img.png", VP, VW);
    assert_eq!(st.contents(), "prose\n\n![](img.png)\n");
}

#[test]
fn insert_link_wraps_multibyte_selection() {
    use edamame::document::Selection;
    let mut st = state("héllo wörld\n");
    st.mode = Mode::Rendered;
    st.selection = Some(Selection {
        anchor: 6,
        active: 11, // "wörld" (char offsets)
    });
    st.cursor.offset = 11;
    edit_ops::insert_link_at_cursor(&mut st, VP, VW);
    assert_eq!(st.contents(), "héllo [wörld](file path or URL)\n");
    let (s, e) = st
        .selection
        .expect("URL placeholder should be selected")
        .range();
    assert_eq!(st.buffer.slice_to_string(s, e), "file path or URL");
}

#[test]
fn insert_link_ignores_multiline_selection_without_destroying_it() {
    use edamame::document::Selection;
    let mut st = state("one\ntwo\n");
    st.mode = Mode::Rendered;
    st.selection = Some(Selection {
        anchor: 0,
        active: 7, // spans the newline
    });
    st.cursor.offset = 7;
    edit_ops::insert_link_at_cursor(&mut st, VP, VW);
    // The selection is dropped, not replaced: no buffer text is lost.
    assert_eq!(st.contents(), "one\ntwo[link text](file path or URL)\n");
}

#[test]
fn inline_snippet_guard_classifies_blocks() {
    let src = "para\n\n```\ncode\n```\n\n![a](b.png)\n\n---\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;

    // Inside the paragraph — allowed (inline images/links are legal).
    st.cursor.offset = 2;
    assert!(edit_ops::cursor_block_allows_inline_markdown(&mut st));

    // On the blank line after it — allowed (snippet becomes its own block).
    st.cursor.offset = 5;
    assert!(edit_ops::cursor_block_allows_inline_markdown(&mut st));

    // Inside the fenced code block — denied.
    st.cursor.offset = src.find("code").unwrap() + 1;
    assert!(!edit_ops::cursor_block_allows_inline_markdown(&mut st));

    // On the existing image block — denied.
    st.cursor.offset = src.find("![a]").unwrap() + 2;
    assert!(!edit_ops::cursor_block_allows_inline_markdown(&mut st));

    // On the horizontal rule — denied.
    st.cursor.offset = src.find("---").unwrap() + 1;
    assert!(!edit_ops::cursor_block_allows_inline_markdown(&mut st));
}

#[test]
fn insert_image_from_preview_enters_rendered_mode() {
    let mut st = state("\n");
    assert_eq!(st.mode, Mode::Preview);
    edit_ops::insert_image_at_cursor(&mut st, VP, VW);
    assert_eq!(st.mode, Mode::Rendered);
    assert_eq!(st.contents(), "![alt text](file path or URL)\n");
}

#[test]
fn insert_link_denied_in_code_block_leaves_state_untouched() {
    use edamame::document::Selection;
    let src = "```\ncode\n```\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;
    st.selection = Some(Selection {
        anchor: 4,
        active: 8, // "code"
    });
    st.cursor.offset = 8;
    assert!(!edit_ops::insert_link_at_cursor(&mut st, VP, VW));
    // A denied insert is a full no-op: buffer, mode, and selection all keep
    // their prior values.
    assert_eq!(st.contents(), src);
    assert_eq!(st.mode, Mode::Rendered);
    assert_eq!(st.selection.map(|s| s.range()), Some((4, 8)));
}

#[test]
fn insert_link_denied_when_selection_starts_in_code_block() {
    use edamame::document::Selection;
    // Cursor sits past the fence on the trailing blank line, but the
    // wrapped selection starts inside the code block — the pre-flight
    // classifies the insert offset (the selection start), not the cursor.
    let src = "```\ncode\n```\n\n";
    let mut st = state(src);
    st.mode = Mode::Rendered;
    st.selection = Some(Selection {
        anchor: 4,
        active: 8, // "code"
    });
    st.cursor.offset = 13;
    assert!(!edit_ops::insert_link_at_cursor(&mut st, VP, VW));
    assert_eq!(st.contents(), src);
}