basalt-tui 0.12.7

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

use ratatui::{layout::Size, style::Color};

use crate::{
    config::{Symbols, Theme},
    note_editor::{
        ast::{self},
        cursor::{self, Cursor},
        motion::{Direction, TextObjectKind},
        parser,
        rich_text::RichText,
        text_buffer::TextBuffer,
        viewport::Viewport,
        virtual_document::VirtualDocument,
    },
};

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum EditMode {
    #[default]
    /// Shows the markdown exactly as written
    Source,
    // TODO:
    // /// Hides most of the markdown syntax
    // LivePreview
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum View {
    #[default]
    Read,
    Edit(EditMode),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SelectionMode {
    Char,
    Line,
}

/// `anchor` is the source byte offset where selection began; the moving end is
/// the cursor's current source offset.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Selection {
    pub anchor: usize,
    pub mode: SelectionMode,
}

/// An armed find (`f`/`F`/`t`/`T`) waiting for its target character.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FindKind {
    pub direction: Direction,
    pub till: bool,
}

/// The last completed find, replayed by `;` and `,`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FindMotion {
    target: char,
    kind: FindKind,
}

/// A keypress the editor is armed to consume next: the target of a find, the
/// object of a text object, or the replacement of `r`. At most one is armed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Pending {
    Find(FindKind),
    TextObject(TextObjectKind),
    Replace,
}

/// A pending vim operator awaiting a motion (or a doubled key for linewise).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Operator {
    Delete,
    Change,
    Yank,
}

/// The unnamed register: text captured by `d`/`c`/`y`/`x`, pasted by `p`/`P`.
#[derive(Clone, Debug, Default)]
pub struct Register {
    pub text: String,
    pub linewise: bool,
}

/// A full-content undo point.
#[derive(Clone, Debug)]
struct Snapshot {
    content: String,
    offset: usize,
}

const YANK_FLASH_DURATION: Duration = Duration::from_millis(150);

#[derive(Clone, Debug)]
struct YankFlash {
    range: Range<usize>,
    started: Instant,
}

impl fmt::Display for View {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            View::Read => write!(f, "READ"),
            View::Edit(..) => write!(f, "EDIT"),
        }
    }
}

/// The editor's current mode, shown as the status-bar indicator.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Mode {
    Insert,
    Normal,
    Visual,
    VisualLine,
    Edit,
    #[default]
    Read,
}

impl Mode {
    pub fn label(self) -> &'static str {
        match self {
            Mode::Insert => "INSERT",
            Mode::Normal => "NORMAL",
            Mode::Visual => "VISUAL",
            Mode::VisualLine => "V-LINE",
            Mode::Edit => "EDIT",
            Mode::Read => "READ",
        }
    }

    /// Indicator colour for the mode, from the active theme.
    pub fn color(self, theme: &Theme) -> Color {
        match self {
            Mode::Insert | Mode::Edit => theme.mode_insert,
            Mode::Normal => theme.mode_normal,
            Mode::Visual | Mode::VisualLine => theme.accent,
            Mode::Read => theme.mode_read,
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct NoteEditorState<'a> {
    // FIXME: Use Rope instead of String for O(log n) instead of O(n).
    pub content: String,
    pub view: View,
    pub cursor: Cursor,
    pub ast_nodes: Vec<ast::Node>,
    pub virtual_document: VirtualDocument<'a>,
    pub symbols: Symbols,
    theme: Theme,
    filepath: PathBuf,
    filename: String,
    active: bool,
    insert_mode: bool,
    vim_mode: bool,
    editor_enabled: bool,
    modified: bool,
    viewport: Viewport,
    selection: Option<Selection>,
    yank_flash: Option<YankFlash>,
    pending_count: Option<usize>,
    pending: Option<Pending>,
    last_find: Option<FindMotion>,
    pending_operator: Option<Operator>,
    register: Register,
    undo_stack: Vec<Snapshot>,
    redo_stack: Vec<Snapshot>,
    text_buffer: Option<TextBuffer>,
    /// Which block is currently in raw/edit mode. Stored explicitly so
    /// the layout always matches the text_buffer, even when the cursor
    /// position would temporarily resolve to a different block.
    editing_block: Option<usize>,
}

impl<'a> NoteEditorState<'a> {
    pub fn new(content: &str, filename: &str, filepath: &Path, symbols: &Symbols) -> Self {
        let ast_nodes = parser::from_str(content);
        let content = content.to_string();
        Self {
            text_buffer: None,
            content,
            view: View::Read,
            cursor: Cursor::default(),
            viewport: Viewport::default(),
            symbols: symbols.clone(),
            theme: Theme::default(),
            virtual_document: VirtualDocument::new(symbols),
            filename: filename.to_string(),
            filepath: filepath.to_path_buf(),
            ast_nodes,
            active: false,
            insert_mode: false,
            vim_mode: false,
            editor_enabled: false,
            modified: false,
            selection: None,
            yank_flash: None,
            pending_count: None,
            pending: None,
            last_find: None,
            pending_operator: None,
            register: Register::default(),
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            editing_block: None,
        }
    }

    pub fn viewport(&self) -> &Viewport {
        &self.viewport
    }

    pub fn is_editing(&self) -> bool {
        matches!(self.view, View::Edit(..))
    }

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

    pub fn set_insert_mode(&mut self, mode: bool) {
        self.insert_mode = mode;
    }

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

    /// The current editor mode for the status-bar indicator.
    pub fn mode(&self) -> Mode {
        match self.view {
            View::Edit(..) if self.vim_mode && self.insert_mode => Mode::Insert,
            View::Edit(..) if self.vim_mode && self.is_selecting() => {
                match self.selection().map(|selection| selection.mode) {
                    Some(SelectionMode::Line) => Mode::VisualLine,
                    _ => Mode::Visual,
                }
            }
            View::Edit(..) if self.vim_mode => Mode::Normal,
            View::Edit(..) => Mode::Edit,
            View::Read => Mode::Read,
        }
    }

    pub fn set_vim_mode(&mut self, mode: bool) {
        self.vim_mode = mode;
    }

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

    pub fn set_editor_enabled(&mut self, enabled: bool) {
        self.editor_enabled = enabled;
    }

    pub fn text_buffer(&self) -> Option<&TextBuffer> {
        self.text_buffer.as_ref()
    }

    pub fn enter_insert(&mut self, block_idx: usize) {
        // Commit any pending edits from the previous block before switching.
        self.commit_text_buffer();

        self.editing_block = Some(block_idx);
        if let Some(node) = self.ast_nodes.get(block_idx) {
            let source_range = node.source_range();
            if let Some(content) = self.content.get(source_range.clone()) {
                self.text_buffer = Some(TextBuffer::new(content, source_range.clone()));
            }
        } else if self.content.is_empty() {
            // Only create an empty node for genuinely empty files, not when
            // blocks haven't been laid out yet.
            let empty_node = ast::Node::Paragraph {
                text: RichText::empty(),
                source_range: 0..0,
            };
            self.text_buffer = Some(TextBuffer::new("", empty_node.source_range().clone()));
            self.ast_nodes.push(empty_node);
        }
    }

    pub fn exit_insert(&mut self) {
        if matches!(self.view, View::Read) {
            return;
        }

        self.commit_text_buffer();
        self.text_buffer = None;
        self.editing_block = None;
    }

    /// Write the current text_buffer back to self.content if it was modified,
    /// re-parse AST nodes. Returns Some if content changed.
    pub fn commit_text_buffer(&mut self) -> Option<()> {
        let buffer = self.text_buffer()?;
        if buffer.modified {
            let new_content = buffer.write(&self.content);
            let changed = self.content != new_content;
            self.content = new_content;
            self.ast_nodes = parser::from_str(&self.content);
            self.modified = self.modified || changed;
            Some(())
        } else {
            None
        }
    }

    pub fn set_filename(&mut self, name: &str) {
        self.filename = name.to_string();
    }

    pub fn set_filepath(&mut self, path: &Path) {
        self.filepath = path.to_path_buf();
    }

    pub fn insert_char(&mut self, c: char) {
        if let Some(buffer) = &mut self.text_buffer {
            let source_pos = self.cursor.source_offset();
            buffer.insert_char(c, source_pos);

            // Shift source ranges of all nodes after the insertion point by the character's byte length
            let char_byte_len = c.len_utf8();
            self.shift_source_ranges(source_pos, char_byte_len as isize);

            // Move the cursor to the inserted character before laying out so the
            // active (raw) line tracks the cursor's new position.
            self.cursor.update(
                cursor::Message::Jump(source_pos + char_byte_len),
                self.virtual_document.lines(),
                &self.text_buffer,
            );

            self.update_layout();

            self.ensure_cursor_visible();
        }
    }

    pub fn delete_char(&mut self) -> Option<()> {
        // Comments for my own sanity :)
        // 1. Check if we have a text buffer return if not
        let buffer = self.text_buffer()?;

        // 2. Check if we are at the start of range, which means we need to merge with previous
        //    block
        let at_buffer_start = buffer.source_range.start == self.cursor.source_offset();

        // 3. Get previous and current block idx
        let previous_block_idx = self.previous_block_idx();
        let current_block_idx = self.current_block_idx();

        let should_merge = at_buffer_start && previous_block_idx < current_block_idx;

        if should_merge {
            let prev_start = self.ast_nodes.get(previous_block_idx)?.source_range().start;
            let buffer_start = self.text_buffer.as_ref()?.source_range.start;

            let prefix = self.content.get(prev_start..buffer_start)?;
            // 4. Extend the current text buffer to contain the prev node
            self.text_buffer
                .as_mut()?
                .insert_at_start(prev_start, prefix);
            // 5. Set the previous block as the current editing block
            self.editing_block = Some(previous_block_idx);
            // 6. Delete current ast node
            self.ast_nodes.remove(current_block_idx);
        }

        // 7. Get the buffer again since it might have been updated
        let buffer = self.text_buffer.as_mut()?;

        let source_pos = self.cursor.source_offset();
        let deleted_char_byte_len = buffer.delete_char(source_pos)?;

        // The removed byte sits just before the cursor; shift from there (not the
        // cursor) so a node boundary ending at the cursor shrinks with it.
        let deleted_at = source_pos.saturating_sub(deleted_char_byte_len);
        self.shift_source_ranges(deleted_at, -(deleted_char_byte_len as isize));

        // Position the cursor where the deleted character was before laying out
        // so the active (raw) line tracks the cursor's new position.
        self.cursor.update(
            cursor::Message::Jump(deleted_at),
            self.virtual_document.lines(),
            &self.text_buffer,
        );

        self.update_layout();

        self.ensure_cursor_visible();

        Some(())
    }

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

    pub fn previous_block_idx(&self) -> usize {
        let prev_line = self.cursor.virtual_row().saturating_sub(1);
        self.virtual_document.line_to_block_idx(prev_line)
    }

    pub fn current_block_idx(&self) -> usize {
        let current_line = self.cursor.virtual_row();
        self.virtual_document.line_to_block_idx(current_line)
    }

    pub fn set_view(&mut self, view: View) {
        let block_idx = self.current_block_idx();

        self.view = view;

        use cursor::Message::*;

        match self.view {
            View::Read => {
                self.exit_insert();
                self.update_layout();
                self.cursor.update(
                    SwitchMode(cursor::CursorMode::Read),
                    self.virtual_document.lines(),
                    &None,
                );
                // Read mode never pans horizontally; reset so its width-sized
                // fills (code backgrounds, rules) line up with the viewport.
                self.ensure_cursor_visible();
            }
            View::Edit(..) => {
                self.enter_insert(block_idx);
                self.update_layout();
                self.cursor.update(
                    SwitchMode(cursor::CursorMode::Edit),
                    self.virtual_document.lines(),
                    &self.text_buffer,
                );
            }
        }
    }

    pub fn resize_viewport(&mut self, size: Size) {
        if self.viewport.size_changed(size) {
            use cursor::Message::*;

            let current_block_idx = self.editing_block;

            self.virtual_document.layout(
                &self.filename,
                &self.content,
                &self.view,
                current_block_idx,
                self.cursor.source_offset(),
                &self.ast_nodes,
                size.width.into(),
                self.viewport.left().into(),
                self.text_buffer.clone(),
            );

            self.viewport.resize(size);

            self.cursor.update(
                Jump(self.cursor.source_offset()),
                self.virtual_document.lines(),
                &self.text_buffer,
            );

            self.ensure_cursor_visible();
        }
    }

    /// Cursor row in viewport coordinates: its virtual row offset past the meta lines.
    fn cursor_screen_row(&self) -> i32 {
        (self.cursor.virtual_row() + self.virtual_document.meta().len()) as i32
    }

    /// Ensures the cursor is visible within the viewport by scrolling if necessary.
    /// This method should be called after any operation that might cause the cursor
    /// to move outside the visible area (e.g., resize, cursor movement).
    fn ensure_cursor_visible(&mut self) {
        let cursor_row = self.cursor_screen_row();
        let cursor_column = self.cursor.virtual_column() as i32;

        let vertical = if cursor_row < self.viewport.top() as i32 {
            cursor_row - self.viewport.top() as i32
        } else if cursor_row >= self.viewport.bottom() as i32 {
            cursor_row - self.viewport.bottom() as i32 + 1
        } else {
            0
        };

        let line_width = self
            .virtual_document
            .lines()
            .get(self.cursor.virtual_row())
            .map(|line| {
                line.virtual_spans()
                    .iter()
                    .map(|span| span.width())
                    .sum::<usize>()
            })
            .unwrap_or(0);

        let horizontal = if line_width <= self.viewport.width as usize {
            -(self.viewport.left() as i32)
        } else if cursor_column < self.viewport.left() as i32 {
            cursor_column - self.viewport.left() as i32
        } else if cursor_column >= self.viewport.right() as i32 {
            cursor_column - self.viewport.right() as i32 + 1
        } else {
            0
        };

        if (vertical, horizontal) != (0, 0) {
            self.viewport.scroll_by((vertical, horizontal));
        }
    }

    /// Clamped so the last line never rises above the viewport bottom, leaving no
    /// blank tail when the cursor is near the end of the document.
    fn scroll_cursor_to_top(&mut self) {
        let cursor_row = self.cursor_screen_row();
        let total_rows =
            (self.virtual_document.meta().len() + self.virtual_document.lines().len()) as i32;

        let max_top = (total_rows - self.viewport.height as i32).max(0);
        let vertical = cursor_row.min(max_top) - self.viewport.top() as i32;
        let horizontal = -(self.viewport.left() as i32);

        if (vertical, horizontal) != (0, 0) {
            self.viewport.scroll_by((vertical, horizontal));
        }
    }

    pub fn set_active(&mut self, active: bool) {
        self.active = active;
    }

    pub fn theme(&self) -> Theme {
        self.theme
    }

    /// Swaps the colour theme and re-lays out so the new colours take effect.
    pub fn set_theme(&mut self, theme: &Theme) {
        self.theme = *theme;
        self.virtual_document.set_theme(theme);
        self.update_layout();
    }

    pub fn modified(&self) -> bool {
        self.modified || self.text_buffer().is_some_and(|buffer| buffer.modified)
    }

    pub fn selection(&self) -> Option<Selection> {
        self.selection
    }

    pub fn is_selecting(&self) -> bool {
        self.selection.is_some()
    }

    /// Enters visual selection in `mode`, or exits if that mode is already active.
    pub fn toggle_selection(&mut self, mode: SelectionMode) {
        self.selection = match self.selection {
            Some(selection) if selection.mode == mode => None,
            _ => Some(Selection {
                anchor: self.cursor.source_offset(),
                mode,
            }),
        };
    }

    pub fn clear_selection(&mut self) {
        self.selection = None;
    }

    pub fn has_pending_count(&self) -> bool {
        self.pending_count.is_some()
    }

    pub fn push_count_digit(&mut self, digit: u8) {
        self.pending_count = Some(
            self.pending_count
                .unwrap_or(0)
                .saturating_mul(10)
                .saturating_add(digit as usize),
        );
    }

    /// Consumes the pending count. `None` means no explicit count was given.
    pub fn take_count(&mut self) -> Option<usize> {
        self.pending_count.take()
    }

    pub fn reset_count(&mut self) {
        self.pending_count = None;
    }

    pub fn awaiting_find_target(&self) -> bool {
        matches!(self.pending, Some(Pending::Find(_)))
    }

    pub fn arm_find(&mut self, direction: Direction, till: bool) {
        self.pending = Some(Pending::Find(FindKind { direction, till }));
    }

    pub fn clear_pending_find(&mut self) {
        if self.awaiting_find_target() {
            self.pending = None;
        }
    }

    pub fn take_pending_find(&mut self) -> Option<FindKind> {
        match self.pending {
            Some(Pending::Find(kind)) => {
                self.pending = None;
                Some(kind)
            }
            _ => None,
        }
    }

    /// Records a completed find so `;` and `,` can replay it.
    pub fn remember_find(&mut self, target: char, kind: FindKind) {
        self.last_find = Some(FindMotion { target, kind });
    }

    pub fn last_find(&self) -> Option<(char, FindKind)> {
        self.last_find.map(|find| (find.target, find.kind))
    }

    pub fn awaiting_text_object(&self) -> bool {
        matches!(self.pending, Some(Pending::TextObject(_)))
    }

    pub fn arm_text_object(&mut self, kind: TextObjectKind) {
        self.pending = Some(Pending::TextObject(kind));
    }

    pub fn take_text_object(&mut self) -> Option<TextObjectKind> {
        match self.pending {
            Some(Pending::TextObject(kind)) => {
                self.pending = None;
                Some(kind)
            }
            _ => None,
        }
    }

    pub fn clear_pending_text_object(&mut self) {
        if self.awaiting_text_object() {
            self.pending = None;
        }
    }

    pub fn awaiting_replace(&self) -> bool {
        matches!(self.pending, Some(Pending::Replace))
    }

    pub fn arm_replace(&mut self) {
        self.pending = Some(Pending::Replace);
    }

    pub fn clear_pending_replace(&mut self) {
        if self.awaiting_replace() {
            self.pending = None;
        }
    }

    pub fn pending_operator(&self) -> Option<Operator> {
        self.pending_operator
    }

    /// A short hint of the in-flight command (e.g. `3d`) for the mode indicator.
    pub fn pending_hint(&self) -> String {
        let count = self
            .pending_count
            .map(|c| c.to_string())
            .unwrap_or_default();
        let operator = match self.pending_operator {
            Some(Operator::Delete) => "d",
            Some(Operator::Change) => "c",
            Some(Operator::Yank) => "y",
            None => "",
        };
        format!("{count}{operator}")
    }

    pub fn set_operator(&mut self, operator: Operator) {
        self.pending_operator = Some(operator);
    }

    pub fn take_operator(&mut self) -> Option<Operator> {
        self.pending_operator.take()
    }

    pub fn clear_operator(&mut self) {
        self.pending_operator = None;
    }

    pub fn register(&self) -> &Register {
        &self.register
    }

    pub fn set_register(&mut self, text: String, linewise: bool) {
        self.register = Register { text, linewise };
    }

    fn snapshot(&self) -> Snapshot {
        Snapshot {
            content: self.content.clone(),
            offset: self.cursor.source_offset(),
        }
    }

    /// Records the current content as an undo point, discarding the redo stack.
    pub fn mark_undo_point(&mut self) {
        self.undo_stack.push(self.snapshot());
        self.redo_stack.clear();
    }

    pub fn undo(&mut self) -> bool {
        match self.undo_stack.pop() {
            Some(previous) => {
                self.redo_stack.push(self.snapshot());
                self.restore(previous);
                true
            }
            None => false,
        }
    }

    pub fn redo(&mut self) -> bool {
        match self.redo_stack.pop() {
            Some(next) => {
                self.undo_stack.push(self.snapshot());
                self.restore(next);
                true
            }
            None => false,
        }
    }

    fn restore(&mut self, snapshot: Snapshot) {
        self.content = snapshot.content;
        self.ast_nodes = parser::from_str(&self.content);
        self.modified = true;
        self.text_buffer = None;
        self.editing_block = None;
        self.jump_to_offset(snapshot.offset.min(self.content.len()));
    }

    /// Replaces `range` with `replacement`, re-parses, and leaves the cursor at
    /// the edit site. Records an undo point first.
    pub fn splice(&mut self, range: Range<usize>, replacement: &str) {
        self.commit_text_buffer();
        self.mark_undo_point();
        self.content.replace_range(range.clone(), replacement);
        self.ast_nodes = parser::from_str(&self.content);
        self.modified = true;
        self.text_buffer = None;
        self.editing_block = None;
        let target = (range.start + replacement.len()).min(self.content.len());
        self.jump_to_offset(target);
    }

    /// Pastes the register at (or after) the cursor. Linewise registers land on
    /// their own line below (`p`) or above (`P`).
    pub fn paste(&mut self, after: bool) {
        if self.register.text.is_empty() {
            return;
        }
        let cursor = self.cursor.source_offset();

        if self.register.linewise {
            let insert_at = if after {
                self.content[cursor..]
                    .find('\n')
                    .map_or(self.content.len(), |i| cursor + i + 1)
            } else {
                self.content[..cursor].rfind('\n').map_or(0, |i| i + 1)
            };
            let mut text = self.register.text.clone();
            if !text.ends_with('\n') {
                text.push('\n');
            }
            self.splice(insert_at..insert_at, &text);
            let landing = self.content[insert_at..]
                .char_indices()
                .find(|&(_, c)| !c.is_whitespace())
                .map_or(insert_at, |(i, _)| insert_at + i);
            self.jump_to_offset(landing);
        } else {
            let char_len = self.content[cursor..]
                .chars()
                .next()
                .map_or(0, char::len_utf8);
            let insert_at = if after { cursor + char_len } else { cursor };
            let text = self.register.text.clone();
            self.splice(insert_at..insert_at, &text);
        }
    }

    /// Source content as currently displayed, accounting for unsaved edits.
    fn live_content(&self) -> Cow<'_, str> {
        self.text_buffer
            .as_ref()
            .filter(|buffer| buffer.modified)
            .map(|buffer| Cow::Owned(buffer.write(&self.content)))
            .unwrap_or(Cow::Borrowed(&self.content))
    }

    /// Source byte range from anchor to cursor. Charwise includes the character
    /// under the cursor; linewise rounds out to whole lines.
    pub fn selection_range(&self) -> Option<Range<usize>> {
        let selection = self.selection?;
        let content = self.live_content();
        let cursor = self.cursor.source_offset().min(content.len());
        let anchor = selection.anchor.min(content.len());
        let (lo, hi) = (anchor.min(cursor), anchor.max(cursor));

        let range = match selection.mode {
            SelectionMode::Char => {
                let end = hi + content[hi..].chars().next().map_or(0, char::len_utf8);
                lo..end
            }
            SelectionMode::Line => {
                let start = content[..lo].rfind('\n').map_or(0, |i| i + 1);
                let end = content[hi..]
                    .find('\n')
                    .map_or(content.len(), |i| hi + i + 1);
                start..end
            }
        };

        Some(range)
    }

    pub fn selected_text(&self) -> Option<String> {
        let range = self.selection_range()?;
        self.live_content().get(range).map(str::to_string)
    }

    /// Flashes `range` to acknowledge a yank. The highlight fades on its own
    /// after [`YANK_FLASH_DURATION`].
    pub fn flash_yank(&mut self, range: Range<usize>) {
        self.yank_flash = Some(YankFlash {
            range,
            started: Instant::now(),
        });
    }

    /// The range to flash right now, or `None` once the flash has elapsed.
    pub fn yank_flash_range(&self) -> Option<Range<usize>> {
        self.yank_flash
            .as_ref()
            .filter(|flash| flash.started.elapsed() < YANK_FLASH_DURATION)
            .map(|flash| flash.range.clone())
    }

    pub fn cursor_left(&mut self, amount: usize) {
        use cursor::Message::*;

        let prev_block_idx = self.current_block_idx();
        self.cursor.update(
            MoveLeft(amount),
            self.virtual_document.lines(),
            &self.text_buffer,
        );

        self.relayout_on_block_change(prev_block_idx);
        self.ensure_cursor_visible();
    }

    pub fn cursor_right(&mut self, amount: usize) {
        use cursor::Message::*;

        let prev_block_idx = self.current_block_idx();
        self.cursor.update(
            MoveRight(amount),
            self.virtual_document.lines(),
            &self.text_buffer,
        );

        self.relayout_on_block_change(prev_block_idx);
        self.ensure_cursor_visible();
    }

    pub fn cursor_to_end(&mut self) {
        let last_block = self.virtual_document.blocks().len().saturating_sub(1);
        self.cursor_jump(last_block);
        // After jumping to the last block (which lands on its first line),
        // move down to reach the actual last line within that block.
        self.cursor_down(usize::MAX);
    }

    pub fn cursor_jump(&mut self, idx: usize) {
        let prev_block_idx = self.current_block_idx();

        if let Some(block) = self.virtual_document.blocks().get(idx) {
            self.cursor.update(
                cursor::Message::Jump(block.source_range.start),
                self.virtual_document.lines(),
                &self.text_buffer,
            );
        }

        self.relayout_on_block_change(prev_block_idx);
        self.scroll_cursor_to_top();
    }

    /// Move the cursor to an arbitrary source byte offset, switching the active
    /// block (and its text buffer) when the target lies in another block. Unlike
    /// [`Self::relayout_on_block_change`] this preserves a precise mid-block
    /// target, so it is the primitive every vim motion moves through.
    pub fn jump_to_offset(&mut self, offset: usize) {
        let offset = cursor::snap_to_char_boundary(&self.content, offset);

        if matches!(self.view, View::Edit(..)) {
            let target_block = self
                .ast_nodes
                .iter()
                .position(|node| node.source_range().contains(&offset))
                .or_else(|| {
                    self.ast_nodes
                        .iter()
                        .position(|node| node.source_range().start >= offset)
                })
                .or_else(|| {
                    self.ast_nodes
                        .iter()
                        .rposition(|node| node.source_range().end <= offset)
                });
            if let Some(block) = target_block {
                if self.editing_block != Some(block) {
                    self.enter_insert(block);
                }
                // The leading whitespace a change leaves before a block is not
                // inside any block's range; extend the buffer back over that gap so
                // inserts land at the cursor. Only bridge whitespace — never block
                // markers (list bullets, quote glyphs).
                if let Some(start) = self.text_buffer.as_ref().map(|b| b.source_range.start) {
                    let end = self
                        .text_buffer
                        .as_ref()
                        .map_or(start, |b| b.source_range.end);
                    let gap_is_blank = self
                        .content
                        .get(offset..start)
                        .is_some_and(|gap| gap.chars().all(|c| c == ' ' || c == '\t'));
                    if offset < start && gap_is_blank {
                        if let Some(text) = self.content.get(offset..end) {
                            self.text_buffer = Some(TextBuffer::new(text, offset..end));
                        }
                    }
                }
            }
        }

        self.cursor.update(
            cursor::Message::Jump(offset),
            self.virtual_document.lines(),
            &self.text_buffer,
        );
        self.update_layout();
        self.ensure_cursor_visible();
    }

    pub fn update_layout(&mut self) {
        use cursor::Message::*;

        // Deferred initialization: if Edit mode was set before the viewport was
        // sized (e.g. vim_mode at note open), initialize the text buffer now that
        // the virtual document has been laid out.
        //
        // When re-entering insert mode after an exit_insert (e.g. ESC then `i`
        // again in vim mode), the virtual_document still reflects the layout
        // from before commit_text_buffer re-parsed `ast_nodes`, so
        // `current_block_idx` derived from `cursor.virtual_row` would point at
        // a stale block. Instead pick the block whose source range contains
        // the cursor's source offset, so the new buffer starts where the
        // cursor actually is.
        if matches!(self.view, View::Edit(..)) && self.text_buffer.is_none() {
            let offset = self.cursor.source_offset();
            let block_idx = self
                .ast_nodes
                .iter()
                .position(|node| node.source_range().contains(&offset))
                .or_else(|| {
                    self.ast_nodes
                        .iter()
                        .rposition(|node| node.source_range().end <= offset)
                })
                .unwrap_or_else(|| self.current_block_idx());
            self.enter_insert(block_idx);
            self.cursor.update(
                SwitchMode(cursor::CursorMode::Edit),
                self.virtual_document.lines(),
                &self.text_buffer,
            );
        }

        let current_block_idx = self.editing_block;

        self.virtual_document.layout(
            &self.filename,
            &self.content,
            &self.view,
            current_block_idx,
            self.cursor.source_offset(),
            &self.ast_nodes,
            self.viewport.area().width.into(),
            self.viewport.left().into(),
            self.text_buffer.clone(),
        );

        self.cursor.update(
            Jump(self.cursor.source_offset()),
            self.virtual_document.lines(),
            &self.text_buffer,
        );
    }

    pub fn cursor_up(&mut self, amount: usize) {
        let prev_block_idx = self.current_block_idx();
        let prev_row = self.cursor.virtual_row();

        self.cursor.update(
            cursor::Message::MoveUp(amount),
            self.virtual_document.lines(),
            &self.text_buffer,
        );
        let consumed = prev_row.saturating_sub(self.cursor.virtual_row());
        self.viewport.scroll_up(amount.saturating_sub(consumed));

        self.relayout_on_block_change(prev_block_idx);
        self.ensure_cursor_visible();
    }

    pub fn cursor_down(&mut self, amount: usize) {
        let prev_block_idx = self.current_block_idx();

        self.cursor.update(
            cursor::Message::MoveDown(amount),
            self.virtual_document.lines(),
            &self.text_buffer,
        );

        self.relayout_on_block_change(prev_block_idx);
        self.ensure_cursor_visible();
    }

    /// Re-layout while editing so the raw (source) line tracks the cursor.
    ///
    /// Within a block only the cursor's line is shown raw, so any move that
    /// lands on a different line re-runs the layout. Crossing a block boundary
    /// additionally switches the text_buffer to the new block.
    ///
    /// After re-layout the source offset from the old layout may not
    /// correspond to the same logical position (e.g. code-block visual
    /// vs raw source ranges differ).  We determine whether the cursor
    /// entered the block from above or below by comparing block indices
    /// and whether the jump crossed more than one block (multi-block
    /// jumps like gg/G always go to the entry edge).
    fn relayout_on_block_change(&mut self, prev_block_idx: usize) {
        if !matches!(self.view, View::Edit(..)) {
            return;
        }

        let target_block_idx = self.current_block_idx();
        if target_block_idx == prev_block_idx {
            self.update_layout();
            return;
        }

        let adjacent = prev_block_idx.abs_diff(target_block_idx) == 1;
        let moved_up = target_block_idx < prev_block_idx;
        let use_end = adjacent && moved_up;

        let target_offset = self.ast_nodes.get(target_block_idx).map(|node| {
            let range = node.source_range();
            if use_end {
                range.end.saturating_sub(1).max(range.start)
            } else {
                range.start
            }
        });

        self.enter_insert(target_block_idx);

        self.virtual_document.layout(
            &self.filename,
            &self.content,
            &self.view,
            self.editing_block,
            target_offset.unwrap_or_else(|| self.cursor.source_offset()),
            &self.ast_nodes,
            self.viewport.area().width.into(),
            self.viewport.left().into(),
            self.text_buffer.clone(),
        );

        if let Some(offset) = target_offset {
            self.cursor.update(
                cursor::Message::Jump(offset),
                self.virtual_document.lines(),
                &self.text_buffer,
            );
        }
    }

    pub fn save_to_file(&mut self) -> io::Result<()> {
        if self.modified() {
            let mut file = File::create(&self.filepath)?;
            file.write_all(self.content.as_bytes())?;
            self.modified = false;
        }
        Ok(())
    }

    /// The shift amount can be positive (insertion) or negative (deletion).
    fn shift_source_ranges(&mut self, offset: usize, shift: isize) {
        self.ast_nodes
            .iter_mut()
            .for_each(|node| shift_node(node, offset, shift));
    }
}

/// Shifts source ranges of top-level AST nodes and any nested children.
///
/// This function is a helper function intended to shift the source ranges when editing the
/// document. After exiting the edit mode, the source ranges are calculated by the parser, so
/// we don't have to be precise here.
fn shift_node(node: &mut ast::Node, offset: usize, shift: isize) {
    let shift_value = |v: usize| v.checked_add_signed(shift).unwrap_or(0);
    let range = node.source_range();

    if range.end <= offset {
        return;
    }

    let shifted_range = if range.start > offset {
        shift_value(range.start)..shift_value(range.end)
    } else {
        range.start..shift_value(range.end)
    };
    node.set_source_range(shifted_range);

    if let Some(children) = node.children_as_mut() {
        children
            .iter_mut()
            .for_each(|child| shift_node(child, offset, shift));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::layout::Size;
    use std::path::Path;

    fn assert_cursor_visible(state: &NoteEditorState, context: &str) {
        let cursor_screen_row = state.cursor_screen_row();
        let top = state.viewport().top() as i32;
        let bottom = state.viewport().bottom() as i32;
        assert!(
            cursor_screen_row >= top && cursor_screen_row < bottom,
            "{context}: cursor screen row {cursor_screen_row} outside viewport [{top}, {bottom})",
        );

        let cursor_column = state.cursor.virtual_column() as i32;
        let left = state.viewport().left() as i32;
        let right = state.viewport().right() as i32;
        assert!(
            cursor_column >= left && cursor_column < right,
            "{context}: cursor column {cursor_column} outside viewport [{left}, {right})",
        );
    }

    fn line_texts(state: &NoteEditorState) -> Vec<String> {
        state
            .virtual_document
            .lines()
            .iter()
            .map(|line| {
                line.clone()
                    .spans()
                    .iter()
                    .map(|span| span.content.to_string())
                    .collect()
            })
            .collect()
    }

    /// Editing a block quote shows raw `>` markers line by line: the cursor's
    /// line is raw, the rest keep the rendered `┃` marker (read mode renders all
    /// lines with `┃`). Ref: issue #486.
    #[test]
    fn test_block_quote_raw_marker_line_by_line() {
        let mut state = NoteEditorState::new(
            "> quote line one\n> quote line two\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(50, 14));

        let read = line_texts(&state);
        assert!(
            read.iter().any(|line| line.contains("┃ quote line one")),
            "read mode renders the quote marker, got {read:?}",
        );

        state.set_view(View::Edit(EditMode::Source));
        let edit = line_texts(&state);
        // Cursor on the first line: it is raw, the second stays rendered.
        assert!(
            edit.iter().any(|line| line.contains("> quote line one")),
            "cursor line shows the raw marker, got {edit:?}",
        );
        assert!(
            edit.iter().any(|line| line.contains("┃ quote line two")),
            "non-cursor line keeps the rendered marker, got {edit:?}",
        );

        // Move to the second line: now it is the raw one.
        state.cursor_down(1);
        let edit = line_texts(&state);
        assert!(
            edit.iter().any(|line| line.contains("┃ quote line one")),
            "first line now rendered, got {edit:?}",
        );
        assert!(
            edit.iter().any(|line| line.contains("> quote line two")),
            "second line now raw, got {edit:?}",
        );
    }

    /// A callout (`> [!NOTE]`) renders an icon + label header above its body in
    /// read mode, accented in the kind's colour. Ref: #79.
    #[test]
    fn test_callout_renders_icon_and_label() {
        use ratatui::style::Color;

        let mut state = NoteEditorState::new(
            "> [!warning]\n> Mind the gap.\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(50, 14));

        let read = line_texts(&state);
        assert!(
            read.iter().any(|line| line.contains("⚠ Warning")),
            "callout header shows the icon and label, got {read:?}",
        );
        assert!(
            read.iter().any(|line| line.contains("Mind the gap.")),
            "callout body follows the header, got {read:?}",
        );

        let header_colored = state
            .virtual_document
            .lines()
            .iter()
            .flat_map(|line| line.clone().spans())
            .any(|span| span.content.contains("Warning") && span.style.fg == Some(Color::Yellow));
        assert!(header_colored, "warning callout header is yellow");
    }

    /// Obsidian's titled/foldable callouts (`[!note]- Title`), which pulldown
    /// does not recognise, render with the custom title and drop the raw marker
    /// line from the body. Ref: #79.
    #[test]
    fn test_obsidian_callout_with_title() {
        let mut state = NoteEditorState::new(
            "> [!note]- A word on moving your vault folder\n> Body text.\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(60, 14));

        let read = line_texts(&state);
        assert!(
            read.iter()
                .any(|line| line.contains("✎ A word on moving your vault folder")),
            "callout header shows the custom title, got {read:?}",
        );
        assert!(
            read.iter().any(|line| line.contains("Body text.")),
            "callout body follows the header, got {read:?}",
        );
        assert!(
            !read.iter().any(|line| line.contains("[!note]")),
            "raw marker line must not leak into the body, got {read:?}",
        );
    }

    /// The full Obsidian type set is supported, including aliases (`summary` is
    /// an alias of `abstract`) and types beyond GitHub's five. Ref: #79.
    #[test]
    fn test_obsidian_callout_aliases_and_types() {
        let mut state = NoteEditorState::new(
            "> [!summary] Overview\n> Body.\n\n> [!bug]\n> Squashed.\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(60, 20));

        let read = line_texts(&state);
        assert!(
            read.iter().any(|line| line.contains("▤ Overview")),
            "summary alias renders as an abstract callout, got {read:?}",
        );
        assert!(
            read.iter().any(|line| line.contains("⊙ Bug")),
            "bug is a first-class Obsidian callout type, got {read:?}",
        );
    }

    /// While editing, a callout keeps its per-kind accent colour instead of
    /// falling back to the magenta plain-quote bar. Ref: #79.
    #[test]
    fn test_callout_keeps_color_when_editing() {
        use ratatui::style::Color;

        let mut state = NoteEditorState::new(
            "> [!warning]\n> Mind the gap.\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(50, 14));
        state.set_view(View::Edit(EditMode::Source));

        let bars: Vec<_> = state
            .virtual_document
            .lines()
            .iter()
            .flat_map(|line| line.clone().spans())
            .filter(|span| span.content.contains('') || span.content.contains('>'))
            .collect();
        assert!(!bars.is_empty(), "callout bars/markers should be present");
        assert!(
            bars.iter().all(|span| span.style.fg == Some(Color::Yellow)),
            "callout keeps its yellow accent while editing, got {bars:?}",
        );
    }

    /// The block-quote markers are coloured even on the raw cursor line — and
    /// every nesting level, not just the first. Ref: #486.
    #[test]
    fn test_block_quote_cursor_marker_is_colored() {
        use ratatui::style::Color;

        let mut state = NoteEditorState::new(
            "> > deep\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(40, 8));
        state.set_view(View::Edit(EditMode::Source)); // cursor on the quote line

        let markers: Vec<_> = state
            .virtual_document
            .lines()
            .iter()
            .flat_map(|line| line.clone().spans())
            .filter(|span| span.content.contains('>'))
            .collect();
        assert!(!markers.is_empty(), "quote markers should be present");
        assert!(
            markers
                .iter()
                .all(|span| span.style.fg == Some(Color::Magenta)),
            "every `>` marker (all nesting levels) should be coloured",
        );
    }

    /// Lines inside a fenced code block are rendered literally while editing —
    /// never decorated as markdown (list bullets, headings, etc.). Ref: #486.
    #[test]
    fn test_code_block_content_not_decorated_when_editing() {
        let mut state = NoteEditorState::new(
            "```\n- not a list\n# not a heading\n```\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(40, 10));
        state.set_view(View::Edit(EditMode::Source));

        let lines = line_texts(&state);
        assert!(
            lines.iter().any(|line| line.contains("- not a list")),
            "code content stays literal, got {lines:?}",
        );
        assert!(
            !lines.iter().any(|line| line.contains('')),
            "code content must not get a list bullet, got {lines:?}",
        );
        assert!(
            lines.iter().any(|line| line.contains("# not a heading")),
            "code content keeps its `#`, got {lines:?}",
        );
    }

    /// A heading keeps its rendered style and underline while editing; the `#`
    /// markers stay visible (and editable). Ref: issue #486.
    #[test]
    fn test_heading_keeps_underline_when_editing() {
        let mut state = NoteEditorState::new(
            "## Title\n\npara\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(40, 10));
        state.set_view(View::Edit(EditMode::Source)); // cursor on the heading

        let lines = line_texts(&state);
        assert!(
            lines.iter().any(|line| line.contains("## Title")),
            "heading markers stay visible, got {lines:?}",
        );
        assert!(
            lines
                .iter()
                .any(|line| !line.is_empty() && line.chars().all(|c| c == '')),
            "heading keeps its underline, got {lines:?}",
        );
    }

    /// When the active block's range swallows the blank lines before the next
    /// block (a list does this), those blanks must still render as editable
    /// lines instead of vanishing. Ref: issue #486.
    #[test]
    fn test_multiple_blank_lines_after_active_block_render() {
        // The list's source range includes the three trailing blank lines.
        let mut state = NoteEditorState::new(
            "- item one\n\n\n\npara2\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(50, 14));
        state.set_view(View::Edit(EditMode::Source));

        let lines = line_texts(&state);
        let item = lines
            .iter()
            .position(|line| line.contains("item one"))
            .unwrap();
        let para = lines
            .iter()
            .position(|line| line.contains("para2"))
            .unwrap();
        assert_eq!(
            para - item,
            4,
            "expected three blank lines between the list and the paragraph, got {lines:?}",
        );
    }

    /// Merging a block into the previous one (delete at the buffer start) must
    /// keep the merged text visible — the active block renders from a fresh
    /// parse of the buffer, not the stale (pre-merge) AST. Ref: issue #486.
    #[test]
    fn test_merge_into_previous_block_keeps_text() {
        let mut state = NoteEditorState::new(
            "- item one\n\nsecond paragraph\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(50, 12));
        state.set_view(View::Edit(EditMode::Source));

        // Down to the blank, then onto "second paragraph", then merge it up.
        state.cursor_down(1);
        state.cursor_down(1);
        assert_eq!(state.cursor.source_offset(), 12);
        state.delete_char();

        let lines = line_texts(&state);
        assert!(
            lines.iter().any(|line| line.contains("second paragraph")),
            "merged text must stay visible, got {lines:?}",
        );
        state.commit_text_buffer();
        assert_eq!(state.content, "- item one\nsecond paragraph\n");
    }

    /// An empty list item (`- ` with no text) must still render its marker row
    /// instead of vanishing — otherwise splitting an item or adding a line looks
    /// like nothing happened. Ref: issue #486.
    #[test]
    fn test_empty_list_item_renders_marker() {
        let mut state = NoteEditorState::new(
            "- one\n- \n- three\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(40, 12));
        state.set_view(View::Edit(EditMode::Source));

        // Cursor on "- one"; the empty middle item still occupies a row.
        let lines = line_texts(&state);
        assert!(
            lines.iter().any(|line| line == ""),
            "empty item must render its marker, got {lines:?}",
        );
        assert!(lines.iter().any(|line| line.contains("three")), "{lines:?}");
    }

    /// On a tab-indented line the cursor column must line up with the displayed
    /// (tab-expanded) text: a tab is one byte but two columns. Ref: issue #486.
    #[test]
    fn test_cursor_column_aligns_on_tab_indented_line() {
        let mut state = NoteEditorState::new(
            "- a\n\t- b\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(40, 12));
        state.set_view(View::Edit(EditMode::Source));
        state.cursor_down(1); // onto "\t- b" -> raw "  - b", cursor on 'b'

        // 'b' is byte offset 7; the tab (1 byte) renders as 2 columns, so 'b'
        // sits at display column 4, not 3.
        assert_eq!(state.cursor.source_offset(), 7);
        assert_eq!(state.cursor.virtual_column(), 4);

        // Stepping left onto the marker stays aligned with the display.
        state.cursor_left(2);
        assert_eq!(state.cursor.source_offset(), 5); // the '-'
        assert_eq!(state.cursor.virtual_column(), 2); // after the 2-col tab
    }

    /// A tab-indented nested list keeps its indentation when the list is the
    /// active (editing) block — raw tabs are expanded to spaces so the terminal
    /// doesn't collapse them. Ref: issue #486.
    #[test]
    fn test_tab_indented_nested_list_keeps_indentation_when_editing() {
        let mut state = NoteEditorState::new(
            "1. one\n2. two\n\t- nested\n\t\t- deep\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(50, 12));
        state.set_view(View::Edit(EditMode::Source));
        // Onto the list (cursor on "1. one"); the nested items render decorated.
        let lines = line_texts(&state);
        assert!(lines.iter().any(|line| line == "  ○ nested"), "{lines:?}");
        assert!(lines.iter().any(|line| line == "    ◆ deep"), "{lines:?}");
    }

    /// A nested list renders cleanly while editing: the cursor's line is raw,
    /// deeper items keep their indentation and rendered bullet, and no spurious
    /// indent-only lines appear. Ref: issue #486.
    #[test]
    fn test_nested_list_renders_cleanly_when_editing() {
        let mut state = NoteEditorState::new(
            "- item one\n  - nested one\n  - nested two\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(50, 12));
        state.set_view(View::Edit(EditMode::Source));

        let lines = line_texts(&state);
        // Cursor on item one: raw marker.
        assert_eq!(lines.first().map(String::as_str), Some("- item one"));
        // Nested items: indentation preserved, rendered bullet.
        assert!(
            lines.iter().any(|line| line == "  ○ nested one"),
            "{lines:?}"
        );
        assert!(
            lines.iter().any(|line| line == "  ○ nested two"),
            "{lines:?}"
        );
        // No stray indent-only line (the bug this redesign fixes).
        assert!(
            !lines
                .iter()
                .any(|line| !line.is_empty() && line.trim().is_empty()),
            "spurious whitespace line: {lines:?}",
        );
    }

    /// Reaching a list item via `jump_to_offset` (a vim motion) must not corrupt
    /// the markers of the other items — the gap-bridging in `jump_to_offset` only
    /// applies to whitespace, never a list bullet.
    #[test]
    fn test_jump_to_offset_to_list_keeps_markers() {
        let mut state = NoteEditorState::new(
            "# Title\n\n- alpha bravo\n- charlie delta\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.set_vim_mode(true);
        state.resize_viewport(Size::new(40, 12));
        state.set_view(View::Edit(EditMode::Source));

        let charlie = state.content.find("charlie").unwrap();
        state.jump_to_offset(charlie);

        let lines = line_texts(&state);
        assert!(
            lines.iter().any(|line| line == "- charlie delta"),
            "cursor line is raw: {lines:?}",
        );
        assert!(
            lines.iter().any(|line| line == "● alpha bravo"),
            "other item keeps its rendered bullet: {lines:?}",
        );
    }

    /// Deleting the blank line before a list item must pull the whole item up
    /// intact — its marker and text stay on one row. Ref: issue #486.
    #[test]
    fn test_delete_blank_before_item_keeps_item_intact() {
        let mut state = NoteEditorState::new(
            "- first\n\n- second item text\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(50, 12));
        state.set_view(View::Edit(EditMode::Source));

        // Onto the blank line between the items, then delete it.
        state.cursor_down(1);
        state.delete_char();

        let lines = line_texts(&state);
        assert!(
            lines.iter().any(|line| line.contains("second item text")),
            "item must stay intact on one row, got {lines:?}",
        );
        state.commit_text_buffer();
        assert_eq!(state.content, "- first\n- second item text\n");
    }

    /// A loose list (blank line between items) must render a single blank line
    /// between items even when the cursor is on an item rendered raw — the raw
    /// item's trailing blank and the list's empty-line preservation must not
    /// stack. The blank must stay editable (the cursor can land on it). Ref:
    /// issue #486.
    #[test]
    fn test_loose_list_blank_not_doubled_when_item_raw() {
        let mut state = NoteEditorState::new(
            "- a\n\n- b\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(40, 12));
        state.set_view(View::Edit(EditMode::Source));

        // Cursor lands on item "a", which renders raw.
        let lines = line_texts(&state);
        let a = lines.iter().position(|line| line.contains("- a")).unwrap();
        let b = lines.iter().position(|line| line.contains("b")).unwrap();
        assert_eq!(
            b - a,
            2,
            "expected exactly one blank line between items, got {lines:?}",
        );

        // The blank between the items is reachable, so it can be edited away.
        state.cursor_down(1);
        assert_eq!(
            state.cursor.source_offset(),
            4,
            "cursor should land on the blank line between the items",
        );
        state.delete_char();
        state.commit_text_buffer();
        assert_eq!(state.content, "- a\n- b\n");
    }

    /// Pressing Enter at the very start of a list item must insert a blank line
    /// and push the item down, not drop the item's text. Ref: issue #486.
    #[test]
    fn test_newline_at_start_of_list_item_preserves_text() {
        let mut state = NoteEditorState::new(
            "- hello world\n",
            "test",
            Path::new("test.md"),
            &Symbols::unicode(),
        );
        state.resize_viewport(Size::new(40, 10));
        state.set_view(View::Edit(EditMode::Source));

        state.insert_char('\n');

        let lines = line_texts(&state);
        assert!(
            lines.iter().any(|line| line.contains("- hello world")),
            "item text must survive the newline, got {lines:?}",
        );
        // Cursor lands on the item, now on the second line, at its start.
        assert_eq!(state.cursor.source_offset(), 1);
        assert_eq!(state.cursor.virtual_row(), 1);
        assert_eq!(state.cursor.virtual_column(), 0);
    }

    #[test]
    fn test_viewport_scrolls_with_cursor_in_edit_mode() {
        let content = "# Title\n\nLine 1\n\nLine 2\n\nLine 3\n\nLine 4\n\nLine 5\n";

        let mut state =
            NoteEditorState::new(content, "test", Path::new("test.md"), &Symbols::unicode());
        state.resize_viewport(Size::new(40, 4));

        state.cursor_down(2);
        state.set_view(View::Edit(EditMode::Source));

        state.insert_char('\n');
        state.insert_char('\n');
        state.insert_char('\n');
        state.insert_char('\n');
        assert_cursor_visible(&state, "after insert_char");

        state.cursor_right(20);
        assert_cursor_visible(&state, "after cursor_right");

        state.cursor_left(20);
        assert_cursor_visible(&state, "after cursor_left");

        state.cursor_down(5);
        assert_cursor_visible(&state, "after cursor_down");

        state.cursor_up(5);
        assert_cursor_visible(&state, "after cursor_up");
    }

    #[test]
    fn test_jump_to_heading_scrolls_it_to_top() {
        // A heading below the viewport, jumped to from the outline, should land
        // on the first visible line so its content stays visible. Ref: issue #615.
        let filler = "\nparagraph\n".repeat(10);
        let content = format!("# Intro\n{filler}# Target\n{filler}");

        let mut state =
            NoteEditorState::new(&content, "test", Path::new("test.md"), &Symbols::unicode());
        state.resize_viewport(Size::new(40, 6));

        let target_offset = content.find("# Target").unwrap();
        let target_block = state
            .virtual_document
            .blocks()
            .iter()
            .position(|block| block.source_range().contains(&target_offset))
            .unwrap();

        state.cursor_jump(target_block);

        assert_eq!(
            state.cursor_screen_row(),
            state.viewport().top() as i32,
            "heading should sit at the top of the viewport",
        );
    }

    #[test]
    fn test_viewport_scrolls_horizontally_on_long_code_line() {
        // Code-block lines are not wrapped, so a long one overflows the viewport
        // and the cursor must pan it horizontally to stay visible.
        let long = "x".repeat(100);
        let content = format!("```\n{long}\n```\n");

        let mut state =
            NoteEditorState::new(&content, "test", Path::new("test.md"), &Symbols::unicode());
        state.resize_viewport(Size::new(20, 10));
        state.set_view(View::Edit(EditMode::Source));

        // Land on the code line and walk to its end.
        state.cursor_down(1);
        assert_eq!(state.viewport().left(), 0, "no scroll at line start");

        state.cursor_right(80);
        let panned = state.viewport().left();
        assert!(panned > 0, "viewport should pan right to follow the cursor");
        assert_cursor_visible(&state, "after cursor_right on long line");

        state.cursor_left(80);
        assert!(
            state.viewport().left() < panned,
            "viewport should pan back toward the start",
        );
        assert_cursor_visible(&state, "after cursor_left on long line");
    }

    fn widest_line_in_range(state: &NoteEditorState, range: std::ops::Range<usize>) -> usize {
        state
            .virtual_document
            .lines()
            .iter()
            .filter(|line| {
                line.source_range()
                    .is_some_and(|r| range.contains(&r.start))
            })
            .map(|line| line.virtual_spans().iter().map(|span| span.width()).sum())
            .max()
            .expect("a line in the given source range")
    }

    #[test]
    fn test_code_background_extends_past_horizontal_scroll() {
        // The active code block has a short line and a long one. Panning right to
        // follow the long line must keep the short line's background reaching the
        // viewport's right edge (left + width), not stop at its own content.
        let content = format!("```\nshort\n{}\n```\n", "x".repeat(100));

        let mut state =
            NoteEditorState::new(&content, "", Path::new("test.md"), &Symbols::unicode());
        let width = 20;
        state.resize_viewport(Size::new(width, 10));
        state.set_view(View::Edit(EditMode::Source));

        // Step onto the long line and pan into it.
        state.cursor_down(2);
        state.cursor_right(80);
        state.update_layout(); // editor.rs re-lays out against the scroll each frame.

        let left = state.viewport().left() as usize;
        assert!(left > 0, "expected a horizontal scroll");

        let short_line_width = widest_line_in_range(&state, 4..10);
        assert!(
            short_line_width >= left + width as usize,
            "code background ({short_line_width}) must cover the viewport \
             ({left} + {width})",
        );
    }

    #[test]
    fn test_non_active_block_fills_extend_past_horizontal_scroll() {
        // Editing a long line in one block pans the whole viewport. The fills of
        // the *other* visible blocks must extend too, even though those blocks
        // are not the one being edited. Here a second, non-active code block.
        let long = "x".repeat(100);
        let content = format!("```\n{long}\n```\n\n```\nbbb\n```\n");
        // The second code block opens at the fence after the blank line.
        let second_block_start = content.find("\n\n").unwrap() + 2;

        let mut state =
            NoteEditorState::new(&content, "", Path::new("test.md"), &Symbols::unicode());
        let width = 20;
        state.resize_viewport(Size::new(width, 10));
        state.set_view(View::Edit(EditMode::Source));

        // Pan into the long line of the first (active) code block.
        state.cursor_down(1);
        state.cursor_right(80);
        state.update_layout();

        let left = state.viewport().left() as usize;
        assert!(left > 0, "expected a horizontal scroll");

        let non_active_width = widest_line_in_range(&state, second_block_start..content.len());
        assert!(
            non_active_width >= left + width as usize,
            "non-active code background ({non_active_width}) must cover the \
             viewport ({left} + {width})",
        );
    }

    fn edit_state(content: &str) -> NoteEditorState<'static> {
        let mut state =
            NoteEditorState::new(content, "test", Path::new("test.md"), &Symbols::unicode());
        state.resize_viewport(Size::new(40, 10));
        state.set_view(View::Edit(EditMode::Source));
        state
    }

    #[test]
    fn test_typing_wrapping_paragraph_never_pans_horizontally() {
        let mut state =
            NoteEditorState::new("hello\n", "test", Path::new("test.md"), &Symbols::unicode());
        state.resize_viewport(Size::new(12, 20));
        state.set_view(View::Edit(EditMode::Source));
        state.cursor_right(100);

        for c in " world foobar".chars() {
            state.insert_char(c);
            assert_eq!(
                state.viewport().left(),
                0,
                "wrapped text must not pan; left stayed non-zero after typing {c:?}",
            );
        }

        assert!(
            state.cursor.virtual_row() > 0,
            "the word should have wrapped"
        );
        assert_cursor_visible(&state, "after the word wrapped");
    }

    #[test]
    fn test_charwise_selection_is_inclusive() {
        let mut state = edit_state("hello world\n");

        state.toggle_selection(SelectionMode::Char);
        state.cursor_right(4);

        assert_eq!(state.selected_text().as_deref(), Some("hello"));
    }

    #[test]
    fn test_charwise_selection_extends_backwards() {
        let mut state = edit_state("hello world\n");

        state.cursor_right(4);
        state.toggle_selection(SelectionMode::Char);
        state.cursor_left(4);

        assert_eq!(state.selected_text().as_deref(), Some("hello"));
    }

    #[test]
    fn test_linewise_selection_covers_whole_line() {
        let mut state = edit_state("line one\nline two\n");

        state.cursor_right(3);
        state.toggle_selection(SelectionMode::Line);

        assert_eq!(state.selected_text().as_deref(), Some("line one\n"));
    }

    #[test]
    fn test_toggle_same_mode_clears_selection() {
        let mut state = edit_state("hello\n");

        state.toggle_selection(SelectionMode::Char);
        assert!(state.is_selecting());

        state.toggle_selection(SelectionMode::Char);
        assert!(!state.is_selecting());
        assert_eq!(state.selection_range(), None);
    }
}