vix-editor 1.7.1

Editor host: the `CodeEditor` widget wrapper and the pane tree.
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
//! Tabbed editor: a stack of buffers, each backed by an `editor_core`
//! widget (Tree-sitter syntax highlighting, history, selection, clipboard).
//!
//! The code editor addresses the cursor as a flat character offset; this module
//! converts to/from 1-based line/column for the status bar and go-to-line.

#![warn(clippy::pedantic)]

use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use ratatui::layout::Rect;
use ratatui::style::Style;
#[cfg(feature = "image")]
pub use ratatui_image::protocol::StatefulProtocol as ImageProtocol;

/// Stand-in for the terminal-graphics protocol in a build without the `image`
/// feature: it can never be constructed, so `Tab::image` is always `None`.
#[cfg(not(feature = "image"))]
pub enum ImageProtocol {}
use vix_editor_core::actions::{
    Delete, Duplicate, InsertText, MoveDown, MoveRight, MoveUp, SelectAll,
};
use vix_editor_core::code::Code;
pub use vix_editor_core::editor::Editor as CodeEditor;
use vix_editor_core::utils::get_lang;
// Sentence boundaries are shared with the Edit → Transpose → Sentences command,
// so navigation and transposition split text the same way.
use vix_textops::sentence_starts;

use vix_theme as theme;

/// Whether line `row` is blank — empty or only whitespace. Out-of-range rows are
/// treated as blank.
fn line_is_blank(code: &Code, row: usize) -> bool {
    if row >= code.len_lines() {
        return true;
    }
    let start = code.line_to_char(row);
    let len = code.line_len(row);
    code.char_slice(start, start + len)
        .chars()
        .all(|c: char| c.is_whitespace())
}

/// Whether `row` is part of a section break: a run of two or more consecutive
/// blank lines. `n` is the total line count.
fn is_section_break(code: &Code, row: usize, n: usize) -> bool {
    line_is_blank(code, row)
        && ((row > 0 && line_is_blank(code, row - 1))
            || (row + 1 < n && line_is_blank(code, row + 1)))
}

/// Char offsets where each word begins: a word char whose predecessor is not a
/// word char. Used by the Go → Word navigation.
fn word_starts(text: &str) -> Vec<usize> {
    let mut starts = Vec::new();
    let mut prev_word = false;
    for (i, c) in text.chars().enumerate() {
        let word = is_word_char(c);
        if word && !prev_word {
            starts.push(i);
        }
        prev_word = word;
    }
    starts
}

/// On-save text-normalization options (from `Settings` in `vix-settings`).
#[derive(Clone, Copy)]
pub struct SaveOptions {
    /// Strip trailing spaces/tabs from every line.
    pub trim_trailing_whitespace: bool,
    /// Append a final newline if the (non-empty) file lacks one.
    pub ensure_final_newline: bool,
}

/// Strip trailing spaces and tabs from each line, preserving the line structure
/// (including any final newline and any `\r` before a `\n`).
fn trim_trailing_whitespace(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut lines = text.split('\n');
    if let Some(first) = lines.next() {
        out.push_str(first.trim_end_matches([' ', '\t']));
    }
    for line in lines {
        out.push('\n');
        out.push_str(line.trim_end_matches([' ', '\t']));
    }
    out
}

/// File extensions opened as images rather than text.
#[must_use]
pub fn is_image_path(path: &Path) -> bool {
    matches!(
        path.extension()
            .and_then(|e| e.to_str())
            .map(str::to_ascii_lowercase)
            .as_deref(),
        Some("png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "ico" | "tiff" | "tif")
    )
}

/// Marker passed to the code editor for search hits. The monochrome theme
/// renders marks as underlines, so the specific value is not shown as a color.
pub const SEARCH_MARK: &str = "search";

/// Apply the current theme's styles to a code editor.
///
/// With a custom JSON theme active, the editor uses its per-region foreground,
/// its syntax colors, and its cursor color; otherwise everything is monochrome
/// (foreground only, no token colors) and the cursor is a reversed block.
fn apply_theme(ed: &mut CodeEditor) {
    ed.set_text_style(
        Style::default()
            .fg(theme::region_fg(theme::Region::Editor))
            .add_modifier(theme::region_modifiers(theme::Region::Editor)),
    );
    ed.set_line_number_style(theme::dim());
    ed.set_selection_style(theme::selected());
    ed.set_whitespace_style(theme::dim());
    ed.set_bracket_style(theme::selected());

    // Syntax token colors from the active custom theme (empty == monochrome).
    let syntax = theme::syntax_theme();
    let pairs: Vec<(&str, &str)> = syntax.iter().map(|(t, hex)| (*t, hex.as_str())).collect();
    ed.set_syntax_theme(&pairs);

    // Block cursor: the custom theme's cursor color (drawn as the cell bg, with
    // the editor background as fg so the glyph stays legible), else reversed.
    let cursor = match theme::editor_cursor() {
        Some(color) => Style::default()
            .bg(color)
            .fg(theme::region_bg(theme::Region::Editor)),
        None => theme::selected(),
    };
    ed.set_cursor_style(Some(cursor));
}

fn make_editor(path: Option<&Path>, text: &str, flags: Flags, indent: &str) -> CodeEditor {
    let name = path
        .and_then(|p| p.file_name())
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    let lang = if name.is_empty() {
        "text".to_string()
    } else {
        get_lang(&name)
    };
    // An empty syntax theme keeps the editor monochrome (no token colors), as the
    // theme spec requires. `CodeEditor::new` falls back to plain "text" on an
    // unknown grammar.
    let mut ed = CodeEditor::new(&lang, text, Vec::new())
        .or_else(|_| CodeEditor::new("text", text, Vec::new()))
        .expect("code editor init for plain text never fails");
    ed.show_line_numbers(flags.contains(Flags::LINE_NUMBERS));
    ed.show_whitespace(flags.contains(Flags::SHOW_WHITESPACE));
    ed.set_soft_wrap(flags.contains(Flags::SOFT_WRAP));
    ed.set_indent(Some(indent.to_string()));
    apply_theme(&mut ed);
    ed
}

/// Build a small, theme-styled, single-line text field holding `content`. Used by
/// the Vix menu's Website/Email dialogs so the text is selectable and copyable
/// from inside the TUI (select with the mouse or keyboard, then `Ctrl+C`).
///
/// # Panics
///
/// Never in practice: the underlying `"text"` grammar always initializes.
#[must_use]
pub fn text_field(content: &str) -> CodeEditor {
    let mut ed = CodeEditor::new("text", content, Vec::new())
        .expect("text field init for plain text never fails");
    ed.show_line_numbers(false);
    apply_theme(&mut ed);
    ed
}

/// Whether the OS lets this user write a tab's file (T572).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum FsAccess {
    /// The file can be written (or has no file yet).
    #[default]
    Writable,
    /// The OS won't let this user write the file.
    ReadOnly,
}

/// One open buffer shown as one tab.
pub struct Tab {
    /// The underlying code-editor widget/state.
    pub editor: CodeEditor,
    /// File path backing this buffer, or `None` for an untitled buffer.
    pub path: Option<PathBuf>,
    /// Set when the buffer has unsaved edits.
    pub dirty: bool,
    /// Ephemeral preview tab (single-click / arrow-scan from the explorer).
    pub preview: bool,
    /// When set, this tab shows an image instead of the text editor.
    pub image: Option<ImageProtocol>,
    /// When set, the buffer is locked against edits (view-only).
    pub read_only: bool,
    /// When set, the file on disk isn't writable by this user (T572).
    /// Separate from `read_only`: edits stay allowed (so Save As works) and
    /// toggling View-only never clears it.
    pub fs_access: FsAccess,
}

impl Tab {
    /// Whether this tab displays an image rather than editable text.
    pub fn is_image(&self) -> bool {
        self.image.is_some()
    }

    /// Whole buffer text.
    pub fn text(&self) -> String {
        self.editor.get_content()
    }

    /// Buffer split into lines (no trailing empty element).
    pub fn lines(&self) -> Vec<String> {
        self.text()
            .lines()
            .map(std::string::ToString::to_string)
            .collect()
    }

    /// Title shown on the tab and in the buffer switcher.
    pub fn title(&self) -> String {
        let name = self.path.as_ref().and_then(|p| p.file_name()).map_or_else(
            || "untitled".to_string(),
            |s| s.to_string_lossy().into_owned(),
        );
        let icon = theme::file_icon(&name);
        let flag = if self.dirty {
            format!(" {}", theme::icon::FILE_DIRTY)
        } else {
            String::new()
        };
        let lock = if self.fs_access == FsAccess::ReadOnly {
            " 🔒"
        } else {
            ""
        };
        format!("{icon} {name}{flag}{lock}")
    }

    /// Full path for display (status bar / buffer switcher), or `"untitled"`.
    pub fn display_path(&self) -> String {
        self.path
            .as_ref()
            .map_or_else(|| "untitled".to_string(), |p| p.display().to_string())
    }

    /// 1-based (line, column) of the cursor.
    pub fn cursor_1based(&self) -> (usize, usize) {
        let cur = self.editor.get_cursor();
        let code = self.editor.code_ref();
        let row = code.char_to_line(cur);
        let col = cur - code.line_to_char(row);
        (row + 1, col + 1)
    }

    /// Total line count of this buffer (for the scrollbar).
    #[must_use]
    pub fn line_count(&self) -> usize {
        self.editor.code_ref().len_lines()
    }
}

/// Orientation of an editor split.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SplitDir {
    /// Two panes side by side.
    Vertical,
    /// Two panes stacked top/bottom.
    Horizontal,
}

bitflags::bitflags! {
    /// [`Editor`]'s independent display toggles (T149): each bit is a
    /// distinct, freely-combinable preference, not one of several
    /// mutually-exclusive modes — a bitset with named accessors is what
    /// actually satisfies `clippy::struct_excessive_bools` here (grouping
    /// the same bools into a sub-struct would not: the lint counts `bool`
    /// fields anywhere, not just on `Editor` itself).
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Flags: u8 {
        /// The line-number gutter is shown.
        const LINE_NUMBERS = 1 << 0;
        /// Line numbers are shown relative to the cursor line.
        const RELATIVE_LINE_NUMBERS = 1 << 1;
        /// Visible-whitespace glyphs are shown.
        const SHOW_WHITESPACE = 1 << 2;
        /// Long lines soft-wrap.
        const SOFT_WRAP = 1 << 3;
    }
}

/// The tab strip: a stack of open buffers and the active index.
pub struct Editor {
    /// Open buffers, left to right.
    pub tabs: Vec<Tab>,
    /// Index of the active tab.
    pub active: usize,
    /// Display toggles (line numbers, relative line numbers, whitespace,
    /// soft wrap) — see [`Flags`] for what each bit means.
    pub flags: Flags,
    /// String Tab inserts in every buffer (spaces or a tab).
    pub indent: String,
    /// Split layout (a binary tree of panes), when the editor area is divided.
    /// `None` is the normal single-pane case.
    pub split_root: Option<crate::pane_tree::Pane>,
    /// In-order index of the focused leaf within `split_root` (0 when unsplit).
    pub focused_leaf: usize,
    /// The largest file [`Editor::open`] reads without being told to (T571); a
    /// bigger one is refused with a typed error the host can turn into a
    /// confirmation, then reopen with [`Editor::open_unbounded`].
    pub max_text_bytes: u64,
}

impl Default for Editor {
    fn default() -> Self {
        Editor::new(Flags::LINE_NUMBERS, "    ".to_string())
    }
}

impl Editor {
    /// Create an editor with one empty buffer and the given display /
    /// indentation settings.
    #[must_use]
    pub fn new(flags: Flags, indent: String) -> Self {
        let mut e = Editor {
            tabs: Vec::new(),
            active: 0,
            flags,
            indent,
            split_root: None,
            focused_leaf: 0,
            max_text_bytes: vix_fileops::MAX_TEXT_BYTES,
        };
        e.new_tab();
        e
    }

    /// The active tab, if any.
    #[must_use]
    pub fn active_tab(&self) -> Option<&Tab> {
        self.tabs.get(self.active)
    }

    /// Mutable access to the active tab, if any.
    pub fn active_tab_mut(&mut self) -> Option<&mut Tab> {
        self.tabs.get_mut(self.active)
    }

    /// Whether the editor area is split into more than one pane.
    #[must_use]
    pub fn is_split(&self) -> bool {
        self.split_root.is_some()
    }

    /// Split the focused pane in `dir`, showing another tab (the next one, else
    /// the active tab) in the new pane. Creates the split on the first call; later
    /// calls split the currently focused pane. Capped at `MAX_LEAVES` panes.
    pub fn set_split(&mut self, dir: SplitDir) {
        let other = (0..self.tabs.len())
            .find(|&i| i != self.active)
            .unwrap_or(self.active);
        match self.split_root.as_mut() {
            None => {
                self.split_root = Some(crate::pane_tree::Pane::Split {
                    dir,
                    ratio: 50,
                    first: Box::new(crate::pane_tree::Pane::Leaf(self.active)),
                    second: Box::new(crate::pane_tree::Pane::Leaf(other)),
                });
                self.focused_leaf = 0;
            }
            Some(root) => {
                root.set_leaf_tab(self.focused_leaf, self.active);
                root.split_leaf(self.focused_leaf, dir, other);
            }
        }
    }

    /// Remove the focused pane, collapsing the split; a single remaining pane
    /// returns to the unsplit state.
    pub fn unsplit(&mut self) {
        let Some(root) = self.split_root.take() else {
            return;
        };
        match root.remove_leaf(self.focused_leaf) {
            Some(tree) if tree.leaf_count() > 1 => {
                self.focused_leaf = self.focused_leaf.min(tree.leaf_count() - 1);
                if let Some(tab) = tree.leaf_tab(self.focused_leaf) {
                    self.active = tab.min(self.tabs.len().saturating_sub(1));
                }
                self.split_root = Some(tree);
            }
            Some(tree) => {
                if let Some(tab) = tree.leaf_tab(0) {
                    self.active = tab.min(self.tabs.len().saturating_sub(1));
                }
                self.split_root = None;
                self.focused_leaf = 0;
            }
            None => {
                self.split_root = None;
                self.focused_leaf = 0;
            }
        }
    }

    /// Sync the focused leaf to the active tab and clamp every leaf to the open
    /// tabs. Call before reading the layout so the focused pane follows `active`.
    fn sync_split(&mut self) {
        let count = self.tabs.len();
        if let Some(root) = self.split_root.as_mut() {
            root.set_leaf_tab(self.focused_leaf, self.active);
            root.clamp_tabs(count);
            self.focused_leaf = self.focused_leaf.min(root.leaf_count().saturating_sub(1));
        }
    }

    /// Focus the leaf at in-order index `i`, making its tab active.
    pub fn focus_leaf(&mut self, i: usize) {
        self.sync_split();
        let Some(root) = self.split_root.as_ref() else {
            return;
        };
        if let Some(tab) = root.leaf_tab(i) {
            self.focused_leaf = i;
            self.active = tab.min(self.tabs.len().saturating_sub(1));
        }
    }

    /// Move focus to the next pane (wrapping), making its tab active.
    pub fn focus_other_pane(&mut self) {
        self.sync_split();
        let Some(root) = self.split_root.as_ref() else {
            return;
        };
        let n = root.leaf_count();
        if n > 0 {
            self.focus_leaf((self.focused_leaf + 1) % n);
        }
    }

    /// The in-order index of the focused pane.
    #[must_use]
    pub fn focused_leaf(&self) -> usize {
        self.focused_leaf
    }

    /// Lay out the split panes into `area` (focused leaf synced to `active`).
    /// Empty when unsplit.
    pub fn split_layout(&mut self, area: Rect) -> Vec<crate::pane_tree::LeafBox> {
        self.sync_split();
        self.split_root
            .as_ref()
            .map(|r| r.layout(area))
            .unwrap_or_default()
    }

    /// The split divider rectangles for drawing, given the editor `area`.
    #[must_use]
    pub fn split_dividers(&self, area: Rect) -> Vec<(SplitDir, Rect)> {
        self.split_root
            .as_ref()
            .map(|r| r.dividers(area))
            .unwrap_or_default()
    }

    /// Focus the pane under `(col, row)` within `area`; returns whether a pane was
    /// hit.
    pub fn focus_pane_at(&mut self, area: Rect, col: u16, row: u16) -> bool {
        self.sync_split();
        let Some(leaf) = self
            .split_root
            .as_ref()
            .and_then(|r| r.leaf_at(area, col, row))
        else {
            return false;
        };
        self.focus_leaf(leaf);
        true
    }

    /// Drag a split divider under `(col, row)` within `area`; returns whether one
    /// was resized.
    pub fn resize_split_at(&mut self, area: Rect, col: u16, row: u16) -> bool {
        self.split_root
            .as_mut()
            .is_some_and(|r| r.resize_at(area, col, row))
    }

    /// Create an empty untitled buffer and focus it.
    pub fn new_tab(&mut self) {
        let editor = make_editor(None, "", self.flags, &self.indent);
        self.tabs.push(Tab {
            editor,
            path: None,
            dirty: false,
            preview: false,
            image: None,
            read_only: false,
            fs_access: FsAccess::Writable,
        });
        self.active = self.tabs.len() - 1;
    }

    /// Open a new untitled tab pre-filled with `content` (e.g. AI output), marked
    /// dirty so the user is reminded to save it. Becomes the active tab.
    pub fn new_tab_with_content(&mut self, content: &str) {
        let editor = make_editor(None, content, self.flags, &self.indent);
        self.tabs.push(Tab {
            editor,
            path: None,
            dirty: true,
            preview: false,
            image: None,
            read_only: false,
            fs_access: FsAccess::Writable,
        });
        self.active = self.tabs.len() - 1;
    }

    /// Open an image file in a tab, rendered with the given protocol.
    #[cfg(feature = "image")]
    pub fn open_image(&mut self, path: &Path, proto: ImageProtocol) {
        let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
        if let Some(i) = self
            .tabs
            .iter()
            .position(|t| t.path.as_deref() == Some(canon.as_path()))
        {
            self.tabs[i].image = Some(proto);
            self.active = i;
            return;
        }
        let editor = make_editor(Some(&canon), "", self.flags, &self.indent);
        self.tabs.push(Tab {
            editor,
            path: Some(canon),
            dirty: false,
            preview: false,
            image: Some(proto),
            read_only: false,
            fs_access: FsAccess::Writable,
        });
        self.active = self.tabs.len() - 1;
    }

    /// Apply the current line-number settings (visibility + relative) to every
    /// buffer.
    pub fn refresh_line_numbers(&mut self) {
        for tab in &mut self.tabs {
            tab.editor
                .show_line_numbers(self.flags.contains(Flags::LINE_NUMBERS));
            tab.editor
                .set_relative_line_numbers(self.flags.contains(Flags::RELATIVE_LINE_NUMBERS));
        }
    }

    /// Apply the current visible-whitespace setting to every buffer.
    pub fn refresh_whitespace(&mut self) {
        for tab in &mut self.tabs {
            tab.editor
                .show_whitespace(self.flags.contains(Flags::SHOW_WHITESPACE));
        }
    }

    /// Apply the current soft-wrap setting to every buffer.
    pub fn refresh_soft_wrap(&mut self) {
        for tab in &mut self.tabs {
            tab.editor
                .set_soft_wrap(self.flags.contains(Flags::SOFT_WRAP));
        }
    }

    /// Re-apply the current theme's styles to every buffer (after a theme switch).
    pub fn refresh_theme(&mut self) {
        for tab in &mut self.tabs {
            apply_theme(&mut tab.editor);
        }
    }

    /// Open a file: focus it if already open, otherwise load it. `preview`
    /// requests an ephemeral tab that the next preview reuses.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read.
    pub fn open(&mut self, path: &Path, preview: bool) -> io::Result<()> {
        self.open_with_limit(path, preview, self.max_text_bytes)
    }

    /// [`Editor::open`] past the size limit the user confirmed: only the hard
    /// ceiling (`vix_fileops::HARD_MAX_TEXT_BYTES`) still applies (T571).
    ///
    /// # Errors
    /// As [`Editor::open`].
    pub fn open_unbounded(&mut self, path: &Path, preview: bool) -> io::Result<()> {
        self.open_with_limit(path, preview, vix_fileops::HARD_MAX_TEXT_BYTES)
    }

    fn open_with_limit(&mut self, path: &Path, preview: bool, max_bytes: u64) -> io::Result<()> {
        let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
        if let Some(i) = self
            .tabs
            .iter()
            .position(|t| t.path.as_deref() == Some(canon.as_path()))
        {
            self.active = i;
            if !preview {
                self.tabs[i].preview = false;
            }
            return Ok(());
        }

        // Guarded (T571): a FIFO, huge file, or binary refuses with a typed
        // error; non-UTF-8 text opens lossily and read-only.
        let fs_read_only = vix_fileops::is_unwritable(&canon);
        let (content, lossy) = vix_fileops::read_text_guarded(&canon, max_bytes)?;
        let editor = make_editor(Some(&canon), &content, self.flags, &self.indent);
        let tab = Tab {
            editor,
            path: Some(canon),
            dirty: false,
            preview,
            image: None,
            read_only: lossy,
            fs_access: if fs_read_only {
                FsAccess::ReadOnly
            } else {
                FsAccess::Writable
            },
        };

        if preview && let Some(i) = self.tabs.iter().position(|t| t.preview) {
            self.tabs[i] = tab;
            self.active = i;
            return Ok(());
        }
        self.tabs.push(tab);
        self.active = self.tabs.len() - 1;
        Ok(())
    }

    /// Reload every clean (non-dirty) file-backed buffer from disk, preserving the
    /// cursor where it still fits. Used after an external change to the working
    /// tree (e.g. a git branch switch). Dirty buffers are left untouched so unsaved
    /// edits are never discarded. Returns the number of buffers reloaded.
    pub fn reload_clean_from_disk(&mut self) -> usize {
        let mut reloaded = 0;
        for tab in &mut self.tabs {
            if tab.dirty || tab.image.is_some() {
                continue;
            }
            let Some(path) = tab.path.clone() else {
                continue;
            };
            let Ok(content) = fs::read_to_string(&path) else {
                continue;
            };
            if content == tab.editor.get_content() {
                continue;
            }
            let cursor = tab.editor.get_cursor();
            tab.editor.set_content(&content);
            tab.editor.set_cursor(cursor.min(content.chars().count()));
            tab.dirty = false;
            reloaded += 1;
        }
        reloaded
    }

    /// Promote the active preview tab to a permanent tab.
    pub fn promote_active(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            t.preview = false;
        }
    }

    /// Save the active buffer to its existing path.
    ///
    /// # Errors
    ///
    /// Returns an error if the buffer has no path, or the write fails.
    pub fn save_active(&mut self, opts: SaveOptions) -> io::Result<PathBuf> {
        let idx = self.active;
        let path = self.tabs[idx]
            .path
            .clone()
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "buffer has no path"))?;
        self.write_to(idx, &path, opts)?;
        Ok(path)
    }

    /// Save the active buffer to `path` and adopt it as the buffer's path.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub fn save_active_as(&mut self, path: PathBuf, opts: SaveOptions) -> io::Result<PathBuf> {
        let idx = self.active;
        self.write_to(idx, &path, opts)?;
        self.tabs[idx].path = Some(path.clone());
        Ok(path)
    }

    fn write_to(&mut self, idx: usize, path: &Path, opts: SaveOptions) -> io::Result<()> {
        let mut data = self.tabs[idx].text();
        if opts.trim_trailing_whitespace {
            data = trim_trailing_whitespace(&data);
        }
        if opts.ensure_final_newline && !data.is_empty() && !data.ends_with('\n') {
            data.push('\n');
        }
        // Atomic, crash-safe save: a temp file is flushed and renamed over the
        // target, so a crash or full disk mid-write can't truncate the user's
        // file, and a concurrent reader never sees a half-written buffer.
        vix_fileops::write_atomic(path, data.as_bytes())?;
        self.tabs[idx].dirty = false;
        self.tabs[idx].preview = false;
        Ok(())
    }

    /// Close the active tab; keeps at least one empty buffer open. Returns the
    /// closed tab's file path, if it had one (for "reopen closed tab").
    pub fn close_active(&mut self) -> Option<PathBuf> {
        if self.tabs.is_empty() {
            return None;
        }
        let closed = self.tabs.remove(self.active).path;
        if self.tabs.is_empty() {
            self.new_tab();
        } else if self.active >= self.tabs.len() {
            self.active = self.tabs.len() - 1;
        }
        closed
    }

    /// Close every tab, leaving a single empty untitled buffer. Returns the file
    /// paths of the closed tabs, oldest first (for "reopen closed tab").
    pub fn close_all(&mut self) -> Vec<PathBuf> {
        let closed: Vec<PathBuf> = self.tabs.drain(..).filter_map(|t| t.path).collect();
        self.active = 0;
        self.new_tab();
        closed
    }

    /// Activate the next tab, wrapping around.
    pub fn next_tab(&mut self) {
        if !self.tabs.is_empty() {
            self.active = (self.active + 1) % self.tabs.len();
        }
    }

    /// Activate the previous tab, wrapping around.
    pub fn prev_tab(&mut self) {
        if !self.tabs.is_empty() {
            self.active = (self.active + self.tabs.len() - 1) % self.tabs.len();
        }
    }

    /// 1-based (line, column) of the active cursor, for the status bar.
    #[must_use]
    pub fn cursor_1based(&self) -> (usize, usize) {
        self.active_tab().map_or((1, 1), Tab::cursor_1based)
    }

    /// Total line count of the active buffer (for the scrollbar).
    #[must_use]
    pub fn active_line_count(&self) -> usize {
        self.active_tab()
            .map_or(1, |t| t.editor.code_ref().len_lines())
    }

    /// Jump the active buffer to a 1-based line and optional 1-based column,
    /// keeping the target visible within `area`. The line is clamped to the
    /// buffer's range (an out-of-range line would otherwise panic).
    pub fn goto(&mut self, line: usize, col: Option<usize>, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let last = t.editor.code_ref().len_lines().max(1);
            let line = line.clamp(1, last);
            let off = t
                .editor
                .code_ref()
                .offset(line - 1, col.unwrap_or(1).saturating_sub(1));
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Move the active cursor to the start of its current line.
    /// Smart Home: jump to the first non-blank character of the line; if already
    /// there (or the line is blank), jump to column 0. Pressing Home repeatedly
    /// toggles between the two.
    pub fn cursor_line_home(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            let cur = t.editor.get_cursor();
            let code = t.editor.code_ref();
            let row = code.char_to_line(cur);
            let line_start = code.line_to_char(row);
            let line_len = code.line_len(row);
            let cur_col = cur - line_start;
            let indent = code
                .char_slice(line_start, line_start + line_len)
                .chars()
                .take_while(|c| *c == ' ' || *c == '\t')
                .count();
            // A blank/all-whitespace line has no first non-blank: treat it as 0.
            let indent = if indent >= line_len { 0 } else { indent };
            let target = if cur_col == indent { 0 } else { indent };
            t.editor.set_cursor(line_start + target);
        }
    }

    /// Move the active cursor to the very start of the buffer and scroll it into
    /// `area`.
    pub fn cursor_document_start(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            t.editor.set_cursor(0);
            t.editor.focus(&area);
        }
    }

    /// Move the active cursor to the very end of the buffer (past the last
    /// character) and scroll it into `area`.
    pub fn cursor_document_end(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let code = t.editor.code_ref();
            let last = code.len_lines().saturating_sub(1);
            let off = code.line_to_char(last) + code.line_len(last);
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Move the active cursor to the end of its current line.
    pub fn cursor_line_end(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            let cur = t.editor.get_cursor();
            let code = t.editor.code_ref();
            let row = code.char_to_line(cur);
            let off = code.line_to_char(row) + code.line_len(row);
            t.editor.set_cursor(off);
        }
    }

    /// Move the active cursor to column 0 of its current line (the literal line
    /// start, unlike the smart-Home [`cursor_line_home`](Self::cursor_line_home)).
    pub fn cursor_line_start(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            let cur = t.editor.get_cursor();
            let code = t.editor.code_ref();
            let row = code.char_to_line(cur);
            let off = code.line_to_char(row);
            t.editor.set_cursor(off);
        }
    }

    /// Move the active cursor to the first line of the current paragraph and
    /// scroll it into `area`. Paragraphs are delimited by blank (empty or
    /// whitespace-only) lines; from a blank line, climbs to the paragraph above.
    pub fn cursor_paragraph_start(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let cur = t.editor.get_cursor();
            let off = {
                let code = t.editor.code_ref();
                let is_blank = |r: usize| line_is_blank(code, r);
                let mut r = code.char_to_line(cur);
                while r > 0 && is_blank(r) {
                    r -= 1;
                }
                while r > 0 && !is_blank(r - 1) {
                    r -= 1;
                }
                code.line_to_char(r)
            };
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Move the active cursor to the end of the last line of the current
    /// paragraph and scroll it into `area`. See [`Self::cursor_paragraph_start`].
    pub fn cursor_paragraph_end(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let cur = t.editor.get_cursor();
            let off = {
                let code = t.editor.code_ref();
                let n = code.len_lines().max(1);
                let is_blank = |r: usize| line_is_blank(code, r);
                let mut r = code.char_to_line(cur);
                while r + 1 < n && is_blank(r) {
                    r += 1;
                }
                while r + 1 < n && !is_blank(r + 1) {
                    r += 1;
                }
                code.line_to_char(r) + code.line_len(r)
            };
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Move the active cursor to the first line of the current section and scroll
    /// it into `area`. Sections are delimited by a run of two or more consecutive
    /// blank lines (a larger break than a paragraph).
    pub fn cursor_section_start(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let cur = t.editor.get_cursor();
            let off = {
                let code = t.editor.code_ref();
                let n = code.len_lines().max(1);
                let sep = |r: usize| is_section_break(code, r, n);
                let mut r = code.char_to_line(cur);
                while r > 0 && !sep(r - 1) {
                    r -= 1;
                }
                code.line_to_char(r)
            };
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Move the active cursor to the end of the last line of the current section
    /// and scroll it into `area`. See [`Self::cursor_section_start`].
    pub fn cursor_section_end(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let cur = t.editor.get_cursor();
            let off = {
                let code = t.editor.code_ref();
                let n = code.len_lines().max(1);
                let sep = |r: usize| is_section_break(code, r, n);
                let mut r = code.char_to_line(cur);
                while r + 1 < n && !sep(r + 1) {
                    r += 1;
                }
                code.line_to_char(r) + code.line_len(r)
            };
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Move the active cursor down one line (Go → Line → Next).
    pub fn cursor_line_down(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            t.editor.cursor_down();
            t.editor.focus(&area);
        }
    }

    /// Move the active cursor up one line (Go → Line → Previous).
    pub fn cursor_line_up(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            t.editor.cursor_up();
            t.editor.focus(&area);
        }
    }

    /// 0-based row of the active cursor (0 when there is no buffer).
    fn cursor_row(&self) -> usize {
        self.active_tab().map_or(0, |t| {
            let code = t.editor.code_ref();
            code.char_to_line(t.editor.get_cursor())
        })
    }

    /// 0-based line of the active cursor (0 when there is no buffer).
    #[must_use]
    pub fn cursor_line(&self) -> usize {
        self.cursor_row()
    }

    /// Install any completed background reparse for the active buffer (large
    /// files). Returns `true` if the syntax tree changed (request a redraw).
    pub fn poll_parse(&mut self) -> bool {
        self.active_tab_mut().is_some_and(|t| t.editor.poll_parse())
    }

    /// Whether a background reparse is in flight for the active buffer.
    #[must_use]
    pub fn parse_pending(&self) -> bool {
        self.active_tab().is_some_and(|t| t.editor.parse_pending())
    }

    /// Cycle which undo-tree branch the next redo follows in the active buffer.
    /// Returns `true` if the current state has more than one branch.
    pub fn switch_undo_branch(&mut self) -> bool {
        self.active_tab_mut()
            .is_some_and(|t| t.editor.switch_undo_branch())
    }

    /// The 0-based index of the active buffer's first visible line (vertical
    /// scroll offset), or 0 when there is no buffer.
    #[must_use]
    pub fn top_visible_line(&self) -> usize {
        self.active_tab().map_or(0, |t| t.editor.top_line())
    }

    /// Set the passive word-occurrence marks on the active buffer.
    pub fn set_word_marks(&mut self, marks: Vec<(usize, usize)>) {
        if let Some(t) = self.active_tab_mut() {
            t.editor.set_word_marks(marks);
        }
    }

    /// The 0-based start rows of every paragraph (`section == false`) or section
    /// (`section == true`) in the active buffer. A paragraph is a run of non-blank
    /// lines; a section is a run separated by a section break (2+ blank lines).
    fn block_starts(&self, section: bool) -> Vec<usize> {
        let Some(t) = self.active_tab() else {
            return Vec::new();
        };
        let code = t.editor.code_ref();
        let n = code.len_lines().max(1);
        (0..n)
            .filter(|&r| {
                if section {
                    !is_section_break(code, r, n) && (r == 0 || is_section_break(code, r - 1, n))
                } else {
                    !line_is_blank(code, r) && (r == 0 || line_is_blank(code, r - 1))
                }
            })
            .collect()
    }

    /// Move the active cursor to the start of line `row` and scroll it into view.
    fn goto_row(&mut self, row: usize, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let off = t.editor.code_ref().line_to_char(row);
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Move to the start of the next paragraph (Go → Paragraph → Next).
    pub fn cursor_paragraph_next(&mut self, area: Rect) {
        let row = self.cursor_row();
        if let Some(&next) = self.block_starts(false).iter().find(|&&r| r > row) {
            self.goto_row(next, area);
        }
    }

    /// Move to the start of the previous paragraph (Go → Paragraph → Previous).
    pub fn cursor_paragraph_prev(&mut self, area: Rect) {
        let row = self.cursor_row();
        if let Some(&prev) = self.block_starts(false).iter().rev().find(|&&r| r < row) {
            self.goto_row(prev, area);
        }
    }

    /// Jump to the 1-based `n`th paragraph (Go → Paragraph → Number).
    pub fn goto_paragraph(&mut self, n: usize, area: Rect) {
        if let Some(&row) = self.block_starts(false).get(n.saturating_sub(1)) {
            self.goto_row(row, area);
        }
    }

    /// Move to the start of the next section (Go → Section → Next).
    pub fn cursor_section_next(&mut self, area: Rect) {
        let row = self.cursor_row();
        if let Some(&next) = self.block_starts(true).iter().find(|&&r| r > row) {
            self.goto_row(next, area);
        }
    }

    /// Move to the start of the previous section (Go → Section → Previous).
    pub fn cursor_section_prev(&mut self, area: Rect) {
        let row = self.cursor_row();
        if let Some(&prev) = self.block_starts(true).iter().rev().find(|&&r| r < row) {
            self.goto_row(prev, area);
        }
    }

    /// Jump to the 1-based `n`th section (Go → Section → Number).
    pub fn goto_section(&mut self, n: usize, area: Rect) {
        if let Some(&row) = self.block_starts(true).get(n.saturating_sub(1)) {
            self.goto_row(row, area);
        }
    }

    /// Move the active cursor to char offset `off` and scroll it into view.
    /// Move the active cursor to char offset `off` and scroll it into view.
    pub fn goto_offset(&mut self, off: usize, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Move to the start of the current sentence (Go → Sentence → Start).
    pub fn cursor_sentence_start(&mut self, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let cur = t.editor.get_cursor();
        let off = sentence_starts(&t.editor.get_content())
            .into_iter()
            .rev()
            .find(|&s| s <= cur)
            .unwrap_or(0);
        self.goto_offset(off, area);
    }

    /// Move to the end of the current sentence — its last non-blank char (Go →
    /// Sentence → End).
    pub fn cursor_sentence_end(&mut self, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let cur = t.editor.get_cursor();
        let text = t.editor.get_content();
        let chars: Vec<char> = text.chars().collect();
        let off = match sentence_starts(&text).into_iter().find(|&s| s > cur) {
            Some(mut e) => {
                while e > 0 && chars.get(e - 1).is_some_and(|c| c.is_whitespace()) {
                    e -= 1;
                }
                e
            }
            None => chars.len(),
        };
        self.goto_offset(off, area);
    }

    /// Move to the start of the next sentence (Go → Sentence → Next).
    pub fn cursor_sentence_next(&mut self, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let cur = t.editor.get_cursor();
        if let Some(next) = sentence_starts(&t.editor.get_content())
            .into_iter()
            .find(|&s| s > cur)
        {
            self.goto_offset(next, area);
        }
    }

    /// Move to the start of the previous sentence (Go → Sentence → Previous).
    pub fn cursor_sentence_prev(&mut self, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let cur = t.editor.get_cursor();
        if let Some(prev) = sentence_starts(&t.editor.get_content())
            .into_iter()
            .rev()
            .find(|&s| s < cur)
        {
            self.goto_offset(prev, area);
        }
    }

    /// Jump to the 1-based `n`th sentence (Go → Sentence → Number).
    pub fn goto_sentence(&mut self, n: usize, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let starts = sentence_starts(&t.editor.get_content());
        if let Some(&off) = starts.get(n.saturating_sub(1)) {
            self.goto_offset(off, area);
        }
    }

    /// Move to the start of the current word — or the previous word's start if the
    /// cursor is not on a word (Go → Word → Start).
    pub fn cursor_word_start(&mut self, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let cur = t.editor.get_cursor();
        let off = word_starts(&t.editor.get_content())
            .into_iter()
            .rev()
            .find(|&s| s <= cur)
            .unwrap_or(0);
        self.goto_offset(off, area);
    }

    /// Move to the end of the current word (Go → Word → End).
    pub fn cursor_word_end(&mut self, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let cur = t.editor.get_cursor();
        let chars: Vec<char> = t.editor.get_content().chars().collect();
        // Skip any non-word chars under the cursor, then run to the word's end.
        let mut e = cur;
        while e < chars.len() && !is_word_char(chars[e]) {
            e += 1;
        }
        while e < chars.len() && is_word_char(chars[e]) {
            e += 1;
        }
        self.goto_offset(e, area);
    }

    /// Move to the start of the next word (Go → Word → Next).
    pub fn cursor_word_next(&mut self, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let cur = t.editor.get_cursor();
        if let Some(next) = word_starts(&t.editor.get_content())
            .into_iter()
            .find(|&s| s > cur)
        {
            self.goto_offset(next, area);
        }
    }

    /// Move to the start of the previous word (Go → Word → Previous).
    pub fn cursor_word_prev(&mut self, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let cur = t.editor.get_cursor();
        if let Some(prev) = word_starts(&t.editor.get_content())
            .into_iter()
            .rev()
            .find(|&s| s < cur)
        {
            self.goto_offset(prev, area);
        }
    }

    /// Jump to the 1-based `n`th word (Go → Word → Number).
    pub fn goto_word(&mut self, n: usize, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let starts = word_starts(&t.editor.get_content());
        if let Some(&off) = starts.get(n.saturating_sub(1)) {
            self.goto_offset(off, area);
        }
    }

    /// Jump to `pct`% through the file (by line), clamped to 0..=100.
    pub fn goto_percent(&mut self, pct: usize, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let total = t.editor.code_ref().len_lines().max(1);
        let line = pct.min(100) * total.saturating_sub(1) / 100;
        self.goto(line + 1, None, area); // goto is 1-based
    }

    /// Jump to the character at byte offset `byte` (clamped to the buffer end).
    pub fn goto_byte(&mut self, byte: usize, area: Rect) {
        let Some(t) = self.active_tab() else { return };
        let code = t.editor.code_ref();
        let off = code.byte_to_char(byte.min(code.len_bytes()));
        self.goto_offset(off, area);
    }

    /// Select the current line, including its trailing newline (so it can be cut
    /// as a whole line), and scroll it into `area`.
    pub fn select_line(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let (start, end) = {
                let code = t.editor.code_ref();
                let row = code.char_to_line(t.editor.get_cursor());
                let start = code.line_to_char(row);
                let end = if row + 1 < code.len_lines() {
                    code.line_to_char(row + 1)
                } else {
                    start + code.line_len(row)
                };
                (start, end)
            };
            t.editor.set_selection_range(start, end);
            t.editor.focus(&area);
        }
    }

    /// Select the whole paragraph under the cursor (blank-line delimited) and
    /// scroll it into `area`.
    pub fn select_paragraph(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let (start, end) = {
                let code = t.editor.code_ref();
                let n = code.len_lines().max(1);
                let is_blank = |r: usize| line_is_blank(code, r);
                let row = code.char_to_line(t.editor.get_cursor());
                let mut s = row;
                while s > 0 && is_blank(s) {
                    s -= 1;
                }
                while s > 0 && !is_blank(s - 1) {
                    s -= 1;
                }
                let mut e = row;
                while e + 1 < n && is_blank(e) {
                    e += 1;
                }
                while e + 1 < n && !is_blank(e + 1) {
                    e += 1;
                }
                (
                    code.line_to_char(s),
                    code.line_to_char(e) + code.line_len(e),
                )
            };
            t.editor.set_selection_range(start, end);
            t.editor.focus(&area);
        }
    }

    /// Select the whole section under the cursor (delimited by runs of two or
    /// more blank lines) and scroll it into `area`.
    pub fn select_section(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            let (start, end) = {
                let code = t.editor.code_ref();
                let n = code.len_lines().max(1);
                let sep = |r: usize| is_section_break(code, r, n);
                let row = code.char_to_line(t.editor.get_cursor());
                let mut s = row;
                while s > 0 && !sep(s - 1) {
                    s -= 1;
                }
                let mut e = row;
                while e + 1 < n && !sep(e + 1) {
                    e += 1;
                }
                (
                    code.line_to_char(s),
                    code.line_to_char(e) + code.line_len(e),
                )
            };
            t.editor.set_selection_range(start, end);
            t.editor.focus(&area);
        }
    }

    /// Insert `text` at the active buffer's cursor and scroll it into `area`.
    /// Returns whether the text was inserted (false when there is no editable
    /// buffer, e.g. an image tab). Marks the buffer dirty and promotes a preview.
    pub fn insert_str(&mut self, text: &str, area: Rect) -> bool {
        if let Some(t) = self.active_tab_mut() {
            if t.is_image() || t.read_only {
                return false;
            }
            t.editor.apply(InsertText {
                text: text.to_string(),
            });
            t.editor.focus(&area);
            t.dirty = true;
            t.preview = false;
            return true;
        }
        false
    }

    /// Paste `text` into the active buffer at the cursor as **one** edit — one
    /// undo step — replacing the selection and re-indenting the block to the
    /// cursor, exactly as pasting the clipboard does. Scrolls the cursor into
    /// `area`. Returns whether the text was pasted (false when there is no
    /// editable buffer: no tab, an image, or a read-only one). Used for the
    /// terminal's bracketed paste.
    pub fn paste_str(&mut self, text: &str, area: Rect) -> bool {
        if let Some(t) = self.active_tab_mut() {
            if t.is_image() || t.read_only {
                return false;
            }
            t.editor.paste_text(text);
            t.editor.focus(&area);
            t.dirty = true;
            t.preview = false;
            return true;
        }
        false
    }

    /// Select the entire active buffer.
    pub fn select_all(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            t.editor.apply(SelectAll {});
        }
    }

    /// Duplicate the cursor line (or the selection) in the active buffer.
    pub fn duplicate_line(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            if t.is_image() {
                return;
            }
            t.editor.apply(Duplicate {});
            t.dirty = true;
            t.preview = false;
        }
    }

    /// Join the active buffer's current line with the next (or all selected
    /// lines into one).
    pub fn join_lines(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            if t.is_image() {
                return;
            }
            t.editor.join_lines();
            t.dirty = true;
            t.preview = false;
        }
    }

    /// Sort the active buffer's selected lines ascending, or the whole buffer
    /// when nothing is selected.
    pub fn sort_lines(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            if t.is_image() {
                return;
            }
            t.editor.sort_lines();
            t.dirty = true;
            t.preview = false;
        }
    }

    /// Strip trailing whitespace from the selected lines (or the whole buffer).
    pub fn trim_trailing_whitespace(&mut self) {
        self.edit_active_lines(CodeEditor::trim_trailing_whitespace);
    }

    /// Remove duplicate lines in the selection (or the whole buffer).
    pub fn remove_duplicate_lines(&mut self) {
        self.edit_active_lines(CodeEditor::remove_duplicate_lines);
    }

    /// Reverse the order of the selected lines (or the whole buffer).
    pub fn reverse_lines(&mut self) {
        self.edit_active_lines(CodeEditor::reverse_lines);
    }

    /// Sort the selected lines ascending and drop duplicates (or the whole buffer).
    pub fn sort_unique(&mut self) {
        self.edit_active_lines(CodeEditor::sort_unique);
    }

    /// Randomly reorder the selected lines (or the whole buffer).
    pub fn shuffle_lines(&mut self) {
        self.edit_active_lines(CodeEditor::shuffle_lines);
    }

    /// Run a line-editing op on the active (non-image) buffer, marking it dirty.
    fn edit_active_lines(&mut self, f: impl FnOnce(&mut CodeEditor)) {
        if let Some(t) = self.active_tab_mut() {
            if t.is_image() {
                return;
            }
            f(&mut t.editor);
            t.dirty = true;
            t.preview = false;
        }
    }

    /// Move the active buffer's cursor line up or down by one row, scrolling it
    /// into `area`.
    pub fn move_line(&mut self, down: bool, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            if t.is_image() {
                return;
            }
            if down {
                t.editor.move_line_down();
            } else {
                t.editor.move_line_up();
            }
            t.editor.focus(&area);
            t.dirty = true;
            t.preview = false;
        }
    }

    /// Extend the selection by one word: `forward` grows the active end to the
    /// next word boundary on the right ("Select More"), otherwise to the previous
    /// word boundary on the left ("Select Less").
    pub fn select_word(&mut self, forward: bool, area: Rect) {
        if let Some(t) = self.active_tab_mut() {
            if t.is_image() {
                return;
            }
            let text: Vec<char> = t.text().chars().collect();
            let cur = t.editor.get_cursor();
            let target = if forward {
                next_word(&text, cur)
            } else {
                prev_word(&text, cur)
            };
            if target != cur {
                t.editor.extend_selection(target);
                t.editor.set_cursor(target);
                t.editor.focus(&area);
            }
        }
    }

    /// Jump the cursor to the partner of the bracket at (or just before) it,
    /// scrolling it into `area`. No-op when the cursor is not on a bracket.
    pub fn jump_matching_bracket(&mut self, area: Rect) {
        if let Some(t) = self.active_tab_mut()
            && let Some(off) = t.editor.matching_bracket_offset()
        {
            t.editor.set_cursor(off);
            t.editor.focus(&area);
        }
    }

    /// Forward-delete (the `Delete` key): step right, then delete back.
    ///
    /// At the very end of the buffer there is nothing ahead to delete: the step
    /// right would be a no-op and the delete would eat the character *behind*
    /// the cursor, turning forward delete into a backspace. Guard against that,
    /// unless a selection is pending — that is what gets deleted then.
    pub fn delete_forward(&mut self) {
        if let Some(t) = self.active_tab_mut() {
            let at_end = t.editor.get_cursor() >= t.editor.code_ref().len_chars();
            let selecting = t.editor.get_selection().is_some_and(|s| !s.is_empty());
            if at_end && !selecting {
                return;
            }
            t.editor.apply(MoveRight { shift: false });
            t.editor.apply(Delete {});
        }
    }

    /// Move the cursor up by `lines` (`PageUp`).
    pub fn page_up(&mut self, lines: usize) {
        if let Some(t) = self.active_tab_mut() {
            for _ in 0..lines.max(1) {
                t.editor.apply(MoveUp { shift: false });
            }
        }
    }

    /// Move the cursor down by `lines` (`PageDown`).
    pub fn page_down(&mut self, lines: usize) {
        if let Some(t) = self.active_tab_mut() {
            for _ in 0..lines.max(1) {
                t.editor.apply(MoveDown { shift: false });
            }
        }
    }
}

/// Whether `c` is part of a word (alphanumeric or underscore).
fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

/// The next word-boundary char index at or after `pos`: skip any non-word
/// characters, then the following word run.
fn next_word(text: &[char], pos: usize) -> usize {
    let n = text.len();
    let mut i = pos.min(n);
    while i < n && !is_word_char(text[i]) {
        i += 1;
    }
    while i < n && is_word_char(text[i]) {
        i += 1;
    }
    i
}

/// The previous word-boundary char index at or before `pos`: skip any non-word
/// characters to the left, then the preceding word run.
fn prev_word(text: &[char], pos: usize) -> usize {
    let mut i = pos.min(text.len());
    while i > 0 && !is_word_char(text[i - 1]) {
        i -= 1;
    }
    while i > 0 && is_word_char(text[i - 1]) {
        i -= 1;
    }
    i
}

#[cfg(test)]
mod nav_tests {
    use super::{sentence_starts, word_starts};

    #[test]
    fn word_starts_finds_each_word() {
        // "foo  bar_baz qux" — words at 0, 5, 13 (underscore stays in one word).
        assert_eq!(word_starts("foo  bar_baz qux"), vec![0, 5, 13]);
        assert_eq!(word_starts("   leading"), vec![3]);
        assert_eq!(word_starts("..."), [] as [usize; 0]);
    }

    #[test]
    fn sentence_starts_splits_on_terminators() {
        let text = "One. Two! Three?  Four.";
        // Starts at "One"(0), "Two"(5), "Three"(10), "Four"(18).
        assert_eq!(sentence_starts(text), vec![0, 5, 10, 18]);
        // A period not followed by whitespace (e.g. a decimal) is not a boundary.
        assert_eq!(sentence_starts("pi is 3.14 today"), vec![0]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// T572: a filesystem-read-only tab shows a lock in its title; a
    /// writable one doesn't, and toggling View-only doesn't touch it.
    #[test]
    fn title_shows_a_lock_only_for_filesystem_read_only_tabs() {
        let mut e = Editor::new(Flags::LINE_NUMBERS, "    ".into());
        let tab = e.active_tab_mut().unwrap();
        assert!(!tab.title().contains('🔒'));
        tab.fs_access = FsAccess::ReadOnly;
        assert!(tab.title().contains('🔒'));
        tab.read_only = true;
        tab.read_only = false;
        assert_eq!(tab.fs_access, FsAccess::ReadOnly);
    }
}