strop-editor 0.3.4

strop — a modal text editor in Rust: see the cut before you make it
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
//! Git memory surfaces (M3, reworked 0010): commit browser, changed-files
//! dive, diff view, blame card, permalinks. Every surface is a real
//! readonly buffer (0001 §3: motions, /, yank work); jobs post onto the
//! event loop (0001 §5.6: no blocking the input path on shell git).

use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Receiver, Sender};

use strop_core::Buffer;
use strop_git::memory::{self, BlameCard, BlameLine, ChangedFile, LogRow};
use strop_git::{Hunk, LineOrigin};

use super::{Editor, Key, Mode};

/// What a readonly buffer is — drives Enter/q and per-row rendering.
#[derive(Debug, Clone)]
pub enum Surface {
    CommitLog {
        rows: Vec<LogRow>,
        /// Sha to land the cursor on once rows arrive (the blame dive
        /// opens the browser *at* a commit, 0011 §3).
        focus: Option<String>,
        return_to: Option<ReturnPoint>,
    },
    ChangedFiles {
        sha: String,
        files: Vec<ChangedFile>,
        return_to: Option<ReturnPoint>,
    },
    /// A diff as a readonly buffer (0010 §2): the file's delta at a
    /// commit, or the `Space g p` hunk preview. The buffer's rows mirror
    /// the rendered layout — a stats row, then per hunk a `@@` header
    /// row and unprefixed content rows — so motions, `/` and yank see
    /// exactly what's on screen. `origin` names the working buffer a
    /// hunk preview belongs to, so `Space g u`/`g s` act on the file;
    /// `commit` carries the commit's other files when this delta came
    /// from the dive chain (the sidebar + `]f`/`[f`, 0011 §4).
    Diff {
        /// Stats-row label: the file path (delta view) or "hunk".
        label: String,
        hunks: Vec<Hunk>,
        added: usize,
        deleted: usize,
        origin: Option<HunkOrigin>,
        commit: Option<CommitFiles>,
        /// tuicr-style: Tab moves focus between the file sidebar and
        /// the diff content (j/k step files when the sidebar has focus).
        sidebar_focus: bool,
        return_to: Option<ReturnPoint>,
    },
}

/// The commit a Diff surface's file belongs to, with the commit's full
/// changed-file list — the sidebar's data (typed numstat rows, the same
/// ones the changed-files surface renders from; 0011 §4).
#[derive(Debug, Clone)]
pub struct CommitFiles {
    pub sha: String,
    pub files: Vec<ChangedFile>,
}

/// Where a surface was opened from: closing it hands the cursor and
/// view back to that buffer (vim's window-close behavior — without
/// this, `q` dumps you on line 1).
#[derive(Debug, Clone)]
pub struct ReturnPoint {
    pub buffer: usize,
    pub cursor: usize,
    pub view_top: usize,
}

impl Surface {
    fn set_return_point(&mut self, ret: ReturnPoint) {
        *self.return_slot() = Some(ret);
    }

    pub(crate) fn return_point(&self) -> Option<&ReturnPoint> {
        match self {
            Surface::CommitLog { return_to, .. }
            | Surface::ChangedFiles { return_to, .. }
            | Surface::Diff { return_to, .. } => return_to.as_ref(),
        }
    }

    fn return_slot(&mut self) -> &mut Option<ReturnPoint> {
        match self {
            Surface::CommitLog { return_to, .. }
            | Surface::ChangedFiles { return_to, .. }
            | Surface::Diff { return_to, .. } => return_to,
        }
    }
}

/// Where a hunk preview came from: the buffer it undoes/stages in, at
/// the edit epoch it was captured. Edits since then invalidate it —
/// applying a stale region would cut the wrong lines.
#[derive(Debug, Clone)]
pub struct HunkOrigin {
    pub buffer: usize,
    pub epoch: u64,
}

/// Per-buffer blame gutter state (0011 §3), keyed by canonical path —
/// no parallel vector to keep aligned, and index churn can never pair
/// one buffer with another's blame. Valid only while the buffer's edit
/// epoch and line count still match the capture.
#[derive(Debug, Clone)]
pub struct BlameGutter {
    pub lines: Vec<BlameLine>,
    /// Buffer edit epoch when the blame was captured; any edit since
    /// invalidates the line↔buffer-line pairing.
    pub epoch: u64,
}

/// Jobs post results here; the event loop drains (never blocks input).
/// Index-carrying jobs carry the buffer-list `generation` they were
/// spawned under — a dead surface cannot be resurrected by index reuse
/// (0011 §2).
pub enum GitJob {
    Log {
        buffer: usize,
        generation: u64,
        rows: Vec<LogRow>,
    },
    Card {
        generation: u64,
        card: Box<BlameCard>,
    },
    Gutter {
        path: PathBuf,
        generation: u64,
        lines: Vec<BlameLine>,
    },
    Error(String),
}

impl Editor {
    pub fn surface(&self) -> Option<&Surface> {
        self.surfaces.get(self.current).and_then(|s| s.as_ref())
    }
    // ---- surface lifecycle --------------------------------------------
    fn push_surface(&mut self, name: Option<&str>, text: &str, mut surface: Surface) {
        // surfaces stack: only the first one opened from a plain buffer
        // carries a return point (closing the deepest unwinds the chain)
        if self.surface().is_none() {
            surface.set_return_point(ReturnPoint {
                buffer: self.current,
                cursor: self.cursor,
                view_top: self.view_top,
            });
        }
        let mut buf = Buffer::from_text(text);
        buf.readonly = true;
        buf.name = name.map(|n| n.to_string());
        self.buffers.push(buf);
        self.surfaces.push(Some(surface));
        self.highlighters.push(None); // surfaces render via delta/plain rules
        self.generation += 1; // buffer indices moved: old jobs are stale (0011 §2)
        self.current = self.buffers.len() - 1;
        self.touch_mru(self.current);
        self.cursor = 0;
        self.view_top = 0;
    }

    /// A diff surface from structured hunks (0010 §2). `label` heads the
    /// stats row; `origin` is set only for working-tree hunk previews.
    pub(crate) fn open_diff_surface(
        &mut self,
        name: &str,
        label: &str,
        hunks: Vec<Hunk>,
        origin: Option<HunkOrigin>,
    ) {
        self.open_delta(name, label, hunks, origin, None);
    }

    /// The diff-surface builder: `commit` rides along when the delta
    /// came from the dive chain (sidebar + `]f`/`[f`, 0011 §4).
    fn open_delta(
        &mut self,
        name: &str,
        label: &str,
        hunks: Vec<Hunk>,
        origin: Option<HunkOrigin>,
        commit: Option<CommitFiles>,
    ) {
        let (added, deleted) = hunk_stats(&hunks);
        let text = diff_surface_text(label, &hunks);
        self.push_surface(
            Some(name),
            &text,
            Surface::Diff {
                label: label.to_string(),
                hunks,
                added,
                deleted,
                origin,
                commit,
                sidebar_focus: false,
                return_to: None,
            },
        );
        // syntax highlighting under the origin tint (delta's look):
        // the label is the file path for commit deltas; "hunk" and
        // friends resolve to None and keep origin colors
        if let Some(hl) = strop_syntax::Highlighter::for_path(label) {
            let last = self.highlighters.len() - 1;
            self.highlighters[last] = Some(hl);
        }
    }

    /// `Space g l`: commit browser. `Space g h`: log scoped to the file.
    pub(crate) fn open_log(&mut self, file_scoped: bool) {
        self.open_log_inner(file_scoped, None);
    }

    /// Open the commit browser *at* a commit — the blame dive lands on
    /// the row it was asked about (0011 §3), not the newest entry.
    pub(crate) fn open_log_at(&mut self, sha: &str) {
        self.open_log_inner(false, Some(sha.to_string()));
    }

    fn open_log_inner(&mut self, file_scoped: bool, focus: Option<String>) {
        let Some(repo) = &self.git else {
            self.message = "not a git repo".into();
            return;
        };
        let workdir = repo.workdir().to_path_buf();
        let file = if file_scoped {
            self.buf().path.as_deref().and_then(|p| {
                let abs = if Path::new(p).is_absolute() {
                    PathBuf::from(p)
                } else {
                    workdir.join(p)
                };
                abs.strip_prefix(&workdir).ok().map(|r| r.to_path_buf())
            })
        } else {
            None
        };
        self.push_surface(
            Some(if file_scoped {
                "git log ·file"
            } else {
                "git log"
            }),
            "loading log…",
            Surface::CommitLog {
                rows: vec![],
                focus,
                return_to: None,
            },
        );
        let idx = self.current;
        let generation = self.generation;
        let tx = self.git_tx.clone();
        std::thread::spawn(move || {
            let msg = match memory::log_graph(&workdir, 200, file.as_deref()) {
                Ok(rows) => GitJob::Log {
                    buffer: idx,
                    generation,
                    rows,
                },
                Err(e) => GitJob::Error(e),
            };
            let _ = tx.send(msg);
        });
    }

    /// `Space g b`: on a file buffer, toggle the blame gutter; anywhere
    /// else (or as feedback while the gutter loads) the single-line
    /// card (0011 §3).
    pub(crate) fn toggle_blame_gutter(&mut self) {
        if self.buf().readonly || self.buf().path.is_none() {
            return self.blame_line();
        }
        let key = self.blame_key();
        if self.blame_gutters.remove(&key).is_some() {
            return; // toggle off
        }
        self.blame_gutters.insert(
            key.clone(),
            BlameGutter {
                lines: Vec::new(),
                epoch: self.buf().epoch,
            },
        );
        self.spawn_blame_file(&key);
        self.blame_line(); // the card covers the line until data lands
    }

    /// Canonical path key for the current buffer's gutter entry — the
    /// same normalization every lookup uses, so `f.rs` and an absolute
    /// path for one file share one entry.
    fn blame_key(&self) -> PathBuf {
        self.blame_key_of(self.buf().path.as_deref().unwrap_or(""))
    }

    fn blame_key_of(&self, path: &str) -> PathBuf {
        Path::new(path)
            .canonicalize()
            .unwrap_or_else(|_| self.cwd.join(path))
    }

    fn spawn_blame_file(&mut self, key: &Path) {
        let Some(repo) = &self.git else {
            self.message = "not a git repo".into();
            return;
        };
        let workdir = repo.workdir().to_path_buf();
        let key = key.to_path_buf(); // owned: the job outlives the caller
        let Ok(rel) = key.strip_prefix(&workdir).map(|r| r.to_path_buf()) else {
            self.message = "buffer not under workdir".into();
            return;
        };
        let generation = self.generation;
        let tx = self.git_tx.clone();
        std::thread::spawn(move || {
            let msg = match memory::blame_file(&workdir, &rel) {
                Ok(lines) => GitJob::Gutter {
                    path: key.to_path_buf(),
                    generation,
                    lines,
                },
                Err(e) => GitJob::Error(e),
            };
            let _ = tx.send(msg);
        });
    }

    /// The buffer's blame gutter, if its data is still trustworthy:
    /// same edit epoch, same line count. Any edit since the capture
    pub fn blame_gutter_for(&self, buffer: usize) -> Option<&BlameGutter> {
        let buf = self.buffers.get(buffer)?;
        let path = buf.path.as_deref()?;
        let key = Path::new(path)
            .canonicalize()
            .unwrap_or_else(|_| self.cwd.join(path));
        let gutter = self.blame_gutters.get(&key)?;
        // len_lines counts the trailing newline's phantom line — the
        // content count is what blame rows pair with
        let content_lines = buf.last_content_line() + 1;
        (gutter.epoch == buf.epoch && gutter.lines.len() == content_lines).then_some(gutter)
    }

    /// Enter with the blame gutter on: dive into the cursor line's
    /// commit, positioned at its sha (0011 §3). An unloaded or edited-
    /// stale gutter falls back to the single-line card; with the gutter
    /// off, Enter stays inert in normal mode.
    pub(crate) fn dive_from_blame(&mut self) {
        if self.buf().readonly || self.buf().path.is_none() {
            return;
        }
        let key = self.blame_key();
        match self.blame_gutters.get(&key) {
            None => {}
            Some(_) if self.blame_gutter_for(self.current).is_some() => {
                let line = self.buf().line_of(self.cursor);
                match self.blame_gutters.get(&key).and_then(|g| g.lines.get(line)) {
                    Some(bl) if bl.is_uncommitted() => self.message = "uncommitted line".into(),
                    Some(bl) => {
                        let sha = bl.sha.clone();
                        self.open_log_at(&sha);
                    }
                    None => {}
                }
            }
            Some(_) => self.blame_line(), // still loading (or stale): card
        }
    }

    /// `Space g b` fallback / surface blame: the card for the cursor
    /// line.
    pub(crate) fn blame_line(&mut self) {
        let Some(repo) = &self.git else {
            self.message = "not a git repo".into();
            return;
        };
        let Some(path) = self.buf().path.clone() else {
            self.message = "blame works on file buffers".into();
            return;
        };
        let workdir = repo.workdir().to_path_buf();
        let line = self.buf().line_of(self.cursor) + 1;
        let generation = self.generation;
        let tx = self.git_tx.clone();
        std::thread::spawn(move || {
            let abs = if Path::new(&path).is_absolute() {
                PathBuf::from(&path)
            } else {
                workdir.join(&path)
            };
            let rel = match abs.strip_prefix(&workdir) {
                Ok(r) => r.to_path_buf(),
                Err(_) => {
                    let _ = tx.send(GitJob::Error("not under workdir".into()));
                    return;
                }
            };
            let msg = match memory::blame_line(&workdir, &rel, line) {
                Ok(card) => GitJob::Card {
                    generation,
                    card: Box::new(card),
                },
                Err(e) => GitJob::Error(e),
            };
            let _ = tx.send(msg);
        });
    }

    /// `Space g y`: permalink for the cursor line (or visual range) —
    /// SHA-resolved, remote-prioritized (0001 pillar 3.3).
    pub(crate) fn yank_permalink(&mut self) {
        match self.build_permalink() {
            Some(url) => {
                self.set_register(None, url.clone(), false);
                self.osc52 = Some(url);
                self.message = "permalink copied".into();
            }
            None => self.message = "no remote / not a repo".into(),
        }
    }

    /// `Space g o`: open the permalink in the browser.
    pub(crate) fn open_permalink(&mut self) {
        let Some(url) = self.build_permalink() else {
            self.message = "no remote / not a repo".into();
            return;
        };
        for opener in ["wslview", "xdg-open", "open"] {
            if std::process::Command::new(opener)
                .arg(&url)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
                .is_ok()
            {
                self.message = format!("opened {url}");
                return;
            }
        }
        self.message = format!("no opener found — {url}");
    }

    fn build_permalink(&self) -> Option<String> {
        let repo = self.git.as_ref()?;
        let path = self.buf().path.as_deref()?;
        let abs = if Path::new(path).is_absolute() {
            PathBuf::from(path)
        } else {
            repo.workdir().join(path)
        };
        let rel = abs.strip_prefix(repo.workdir()).ok()?;
        let (a, b) = if self.mode == Mode::Visual || self.mode == Mode::VisualLine {
            (
                self.buf().line_of(self.anchor) + 1,
                self.buf().line_of(self.cursor) + 1,
            )
        } else {
            let l = self.buf().line_of(self.cursor) + 1;
            (l, l)
        };
        memory::permalink(repo, rel, a.min(b), a.max(b))
    }

    // ---- surface interaction -------------------------------------------

    /// Keys for readonly surface buffers (0001 §3): q closes, Enter
    /// dives, and everything else goes through the shared grammar
    /// resolver — motions and yank resolve, mutations refuse. The
    /// resolver is the source of truth, not a hand-maintained motion
    /// whitelist (0010 §6).
    pub(crate) fn feed_readonly(&mut self, key: Key) {
        if !self.pending.is_empty() {
            return self.feed_pending_readonly(key);
        }
        match key {
            Key::Char('q') => {
                self.close_surface();
            }
            // C-w works from surfaces too: splits are core grammar
            Key::CtrlW => self.pending = "\x17".into(),
            // tuicr's tab: focus hops between the file sidebar and the
            // diff content; focused j/k steps files, Enter hops back
            Key::Tab | Key::Backtab => self.toggle_sidebar_focus(),
            Key::Char('j') if self.sidebar_focused() => self.commit_file_step(true),
            Key::Char('k') if self.sidebar_focused() => self.commit_file_step(false),
            Key::Enter if self.sidebar_focused() => self.toggle_sidebar_focus(),
            Key::Enter => self.dive(),
            // searches repeat on surfaces too (diff preview power tools)
            Key::Char('n') => self.repeat_search(false),
            Key::Char('N') => self.repeat_search(true),
            Key::Char('v') => {
                self.mode = Mode::Visual;
                self.anchor = self.cursor;
            }
            Key::Char(c) => {
                // multi-char heads wait for their second key; the rest
                // parse immediately (Invalid clears, Incomplete waits)
                self.pending.push(c);
                if !matches!(c, ' ' | ':' | 'g' | 'y' | ']' | '[') {
                    self.resolve_pending_readonly();
                }
            }
            _ => {}
        }
    }

    fn feed_pending_readonly(&mut self, key: Key) {
        match key {
            Key::Esc => self.pending.clear(),
            Key::Enter => {
                if self.pending.starts_with(':') {
                    self.run_ex(); // :q & friends work on surfaces too
                } else if self.pending.contains('/') {
                    self.pending.push('\r');
                    self.resolve_pending_readonly();
                } else {
                    self.pending.clear();
                }
            }
            Key::Char(c) => {
                // leader namespaces still work from a surface
                if self.pending == " " {
                    self.pending.clear();
                    if c == 'g' {
                        self.pending = " g".into();
                    }
                    return;
                }
                // window commands (C-w): h l j k w move, v s split,
                // q closes the pane-or-surface (0011 §1)
                if self.pending == "\x17" {
                    self.pending.clear();
                    return match c {
                        'h' | 'l' | 'j' | 'k' | 'w' => self.pane_move(c),
                        'v' => self.split(true, None),
                        's' => self.split(false, None),
                        'q' => self.close_surface(),
                        _ => self.message = "C-w: h l j k w move · v s split · q close".into(),
                    };
                }
                if self.pending == " g" {
                    return self.feed_git_pending(c);
                }
                if (self.pending == "]" || self.pending == "[") && (c == 'c' || c == 'f') {
                    let forward = self.pending == "]";
                    self.pending.clear();
                    return if c == 'c' {
                        self.jump_hunk(forward)
                    } else {
                        self.commit_file_step(forward)
                    };
                }
                self.pending.push(c);
                self.resolve_pending_readonly();
            }
            _ => {}
        }
    }

    /// Motions and yank resolve; mutations refuse with a message.
    fn resolve_pending_readonly(&mut self) {
        match strop_grammar::parse(&self.pending) {
            strop_grammar::Parse::Incomplete => {}
            strop_grammar::Parse::Invalid => {
                self.pending.clear();
                self.message = "readonly — q closes, enter dives".into();
            }
            strop_grammar::Parse::Complete(cmd) => {
                self.pending.clear();
                match cmd.op {
                    None => self.move_cursor(&cmd),
                    Some(strop_grammar::Op::Yank) => self.yank_only(&cmd),
                    Some(_) => self.message = "readonly buffer".into(),
                }
            }
        }
    }

    fn yank_only(&mut self, cmd: &strop_grammar::Command) {
        if let Some(r) = strop_grammar::resolve(self.buf(), self.cursor, cmd) {
            let text = self.buf().slice_string(r.range);
            self.set_register(cmd.register, text, r.range.linewise);
            self.flash(r.range);
        }
    }

    /// Enter on a surface line dives deeper (0001 pillar 3.2).
    fn dive(&mut self) {
        let line = self.buf().line_of(self.cursor);
        match self.surface().cloned() {
            Some(Surface::CommitLog { rows, .. }) => {
                let Some(sha) = rows.get(line).and_then(|r| r.sha.clone()) else {
                    return;
                };
                let Some(repo) = &self.git else { return };
                match memory::show_stat(repo.workdir(), &sha) {
                    Ok(files) => {
                        let mut text = format!("commit {}\n\n", &sha[..10.min(sha.len())]);
                        for f in &files {
                            text.push_str(&f.path.display().to_string());
                            text.push('\n');
                        }
                        self.push_surface(
                            Some("commit files"),
                            &text,
                            Surface::ChangedFiles {
                                sha,
                                files,
                                return_to: None,
                            },
                        );
                    }
                    Err(e) => self.message = e,
                }
            }
            Some(Surface::ChangedFiles { sha, files, .. }) => {
                // row 0/1 are the header
                let Some(file) = line.checked_sub(2).and_then(|i| files.get(i)) else {
                    return;
                };
                let Some(repo) = &self.git else { return };
                match repo.commit_file_diff(&sha, &file.path) {
                    Ok(diff) => {
                        // the delta carries its commit + siblings: the
                        // sidebar and `]f`/`[f` navigate them (0011 §4)
                        let commit = CommitFiles {
                            sha: sha.clone(),
                            files: files.clone(),
                        };
                        self.open_delta(
                            "delta",
                            &file.path.display().to_string(),
                            diff.hunks,
                            None,
                            Some(commit),
                        );
                    }
                    Err(e) => self.message = e,
                }
            }
            _ => {}
        }
    }

    /// Tab on a commit diff: hop focus between the file sidebar and
    /// the diff content (tuicr's model, 0011 §4).
    fn toggle_sidebar_focus(&mut self) {
        let Some(Some(Surface::Diff {
            commit: Some(_),
            sidebar_focus,
            ..
        })) = self.surfaces.get_mut(self.current)
        else {
            self.message = "tab: no file sidebar here".into();
            return;
        };
        *sidebar_focus = !*sidebar_focus;
    }

    fn sidebar_focused(&self) -> bool {
        matches!(
            self.surface(),
            Some(Surface::Diff {
                sidebar_focus: true,
                ..
            })
        )
    }

    /// `q`: pop one surface (0011 §1). In a split the *pane* closes —
    /// the buffer stays, vim `:q` semantics — and only the last pane's
    /// close closes the buffer, running the guaranteed return-point
    /// restore.
    fn close_surface(&mut self) {
        self.close_pane_or_buffer(true);
        if let Some(pane) = self.panes.get_mut(self.active_pane) {
            pane.buffer = self.current; // the pane follows the successor
        }
    }

    /// `]f` / `[f`: next/previous file of the same commit (0011 §4).
    /// Rewrites the diff surface in place — the surface keeps its
    /// return point; only the file it shows changes.
    pub(crate) fn commit_file_step(&mut self, forward: bool) {
        let Some(Surface::Diff {
            commit: Some(cf),
            label,
            ..
        }) = self.surface().cloned()
        else {
            self.message = "]f/[f: file navigation needs a commit diff".into();
            return;
        };
        if cf.files.len() < 2 {
            self.message = "single-file commit".into();
            return;
        }
        let Some(cur) = cf
            .files
            .iter()
            .position(|f| f.path.display().to_string() == label)
        else {
            self.message = "current file not in commit".into();
            return;
        };
        let n = cf.files.len();
        let next = if forward {
            (cur + 1) % n
        } else {
            (cur + n - 1) % n
        };
        let file = cf.files[next].clone();
        let Some(repo) = &self.git else { return };
        match repo.commit_file_diff(&cf.sha, &file.path) {
            Ok(diff) => self.load_commit_delta(&cf, &file.path, diff.hunks),
            Err(e) => self.message = e,
        }
    }

    /// Swap the current diff surface to another file of the same
    /// commit: surface data and buffer text in place, cursor to top.
    fn load_commit_delta(&mut self, cf: &CommitFiles, path: &Path, hunks: Vec<Hunk>) {
        let (added, deleted) = hunk_stats(&hunks);
        let label = path.display().to_string();
        let text = diff_surface_text(&label, &hunks);
        let idx = self.current;
        self.buffers[idx].replace_all(&text);
        if let Some(Some(Surface::Diff {
            label: slot,
            hunks: hunk_slot,
            added: add_slot,
            deleted: del_slot,
            ..
        })) = self.surfaces.get_mut(idx)
        {
            *slot = label.clone();
            *hunk_slot = hunks;
            *add_slot = added;
            *del_slot = deleted;
        }
        // the highlighter follows the file the surface now shows
        self.highlighters[idx] = strop_syntax::Highlighter::for_path(&label);
        self.cursor = 0;
        self.view_top = 0;
        let pos = cf
            .files
            .iter()
            .position(|f| f.path == path)
            .map_or(0, |i| i + 1);
        self.message = format!("{label} · {pos}/{}", cf.files.len());
    }

    // ---- job drain ------------------------------------------------------

    pub fn drain_git_jobs(&mut self) {
        while let Ok(job) = self.git_rx.try_recv() {
            match job {
                GitJob::Log {
                    buffer,
                    generation,
                    rows,
                } => {
                    // a closed surface's index may be recycled by the
                    // next buffer: only same-generation results land
                    // (0011 §2)
                    if generation != self.generation || buffer >= self.buffers.len() {
                        continue;
                    }
                    let text = rows
                        .iter()
                        .map(|r| r.text.as_str())
                        .collect::<Vec<_>>()
                        .join("\n")
                        + "\n";
                    self.buffers[buffer].replace_all(&text);
                    let mut focus_row = None;
                    if let Some(Some(Surface::CommitLog {
                        rows: slot, focus, ..
                    })) = self.surfaces.get_mut(buffer)
                    {
                        focus_row = focus.take().and_then(|sha| {
                            rows.iter().position(|r| r.sha.as_deref() == Some(&sha))
                        });
                        *slot = rows;
                    }
                    if let Some(row) = focus_row {
                        // the blame dive asked for this commit: land on
                        // it (only when the browser is still what's
                        // being driven)
                        if self.current == buffer {
                            self.cursor = self.buffers[buffer].line_start(row);
                            self.view_top = row;
                        }
                    }
                }
                GitJob::Card { generation, card } => {
                    if generation == self.generation {
                        self.blame_card = Some(*card);
                    }
                }
                GitJob::Gutter {
                    path,
                    generation,
                    lines,
                } => {
                    // toggled off meanwhile → the entry is gone → drop
                    if generation != self.generation {
                        continue;
                    }
                    if let Some(gutter) = self.blame_gutters.get_mut(&path) {
                        gutter.lines = lines;
                        // the gutter supersedes the card that covered
                        // the load for this buffer
                        if self
                            .buf()
                            .path
                            .as_deref()
                            .is_some_and(|p| self.blame_key_of(p) == path)
                        {
                            self.blame_card = None;
                        }
                    }
                }
                GitJob::Error(e) => self.message = e,
            }
        }
    }
}

/// Added/deleted counts across hunks.
fn hunk_stats(hunks: &[Hunk]) -> (usize, usize) {
    hunks.iter().fold((0, 0), |(a, d), h| {
        let adds = h
            .lines
            .iter()
            .filter(|l| l.origin == LineOrigin::Addition)
            .count();
        let dels = h
            .lines
            .iter()
            .filter(|l| l.origin == LineOrigin::Deletion)
            .count();
        (a + adds, d + dels)
    })
}

/// The buffer text a diff surface shows: stats row, then per hunk a
/// header row and unprefixed content rows — exactly the rendered
/// layout (0010 §2).
fn diff_surface_text(label: &str, hunks: &[Hunk]) -> String {
    let (added, deleted) = hunk_stats(hunks);
    let mut text = format!("{label} +{added} -{deleted}\n");
    for hunk in hunks {
        text.push_str(&hunk.header());
        text.push('\n');
        for line in &hunk.lines {
            text.push_str(&line.text);
            text.push('\n');
        }
    }
    text
}

/// The git job channel ends (created once in `Editor::new`).
pub fn git_channel() -> (Sender<GitJob>, Receiver<GitJob>) {
    channel()
}

#[cfg(test)]
mod tests {
    use std::process::Command;

    use crate::editor::{Editor, GitJob, Key, Surface};
    use strop_core::Buffer;
    use strop_git::memory::LogRow;
    use strop_git::LineOrigin;

    /// Repo with two commits; second adds a line to f.rs.
    fn fixture() -> (tempfile::TempDir, Editor) {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(root)
                .output()
                .unwrap();
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@t.t"]);
        git(&["config", "user.name", "t"]);
        std::fs::write(root.join("f.rs"), "fn a() {}\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-qm", "first"]);
        std::fs::write(root.join("f.rs"), "fn a() {}\nfn b() {}\n").unwrap();
        git(&["commit", "-qam", "add b"]);
        let mut e = Editor::new(Buffer::open(root.join("f.rs").to_str().unwrap()).unwrap());
        e.cwd = root.to_path_buf();
        e.discover_git();
        (dir, e)
    }

    fn pump(e: &mut Editor) {
        // let job threads deliver (bounded, like headless settle)
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        loop {
            e.drain_git_jobs();
            let loaded = e.surface().is_some_and(
                |s| matches!(s, crate::editor::Surface::CommitLog { rows, .. } if !rows.is_empty()),
            );
            if loaded || std::time::Instant::now() > deadline {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }

    #[test]
    fn commit_browser_dives_to_delta() {
        let (_d, mut e) = fixture();
        e.open_log(false);
        pump(&mut e);
        let text = e.buf().rope.to_string();
        assert!(text.contains("add b"), "{text}");
        assert!(text.contains("first"), "{text}");
        assert!(e.buf().readonly, "browser is a readonly real buffer");

        // motions work on the surface
        e.feed_text("j");
        // Enter on a commit row → changed files
        e.feed_text("k");
        e.feed(Key::Enter);
        let text = e.buf().rope.to_string();
        assert!(text.contains("commit"), "{text}");
        assert!(text.contains("f.rs"), "{text}");
        assert!(matches!(e.surface(), Some(Surface::ChangedFiles { .. })));

        // Enter on the file row → the diff surface
        e.feed_text("j");
        e.feed_text("j");
        e.feed(Key::Enter);
        let text = e.buf().rope.to_string();
        assert!(text.contains("fn b() {}"), "{text}");
        assert!(text.starts_with("f.rs +1 -0\n"), "{text}");
        assert!(!text.contains("diff --git"), "no raw patch noise: {text}");
        assert!(text.contains("@@ -1,1 +1,2 @@"), "hunk header row: {text}");

        // edits refuse, q climbs out
        e.feed_text("x");
        assert!(e.message.contains("readonly"));
        e.feed_text("q");
        assert!(matches!(e.surface(), Some(Surface::ChangedFiles { .. })));
    }

    #[test]
    fn diff_surface_rows_carry_line_numbers() {
        let (_d, mut e) = fixture();
        e.open_log(false);
        pump(&mut e);
        e.feed_text("k"); // newest commit is row 0? feed j then k lands on 0
        e.feed(Key::Enter);
        e.feed_text("jj");
        e.feed(Key::Enter);
        let Some(Surface::Diff { hunks, .. }) = e.surface() else {
            panic!("not a diff surface");
        };
        let h = &hunks[0];
        let ctx = h
            .lines
            .iter()
            .find(|l| l.origin == LineOrigin::Context)
            .expect("context line");
        assert_eq!((ctx.old_lineno, ctx.new_lineno), (Some(1), Some(1)));
        let add = h
            .lines
            .iter()
            .find(|l| l.origin == LineOrigin::Addition)
            .expect("addition");
        assert_eq!(add.new_lineno, Some(2));
    }

    #[test]
    fn blame_card_shows_commit() {
        let (_d, mut e) = fixture();
        e.feed_text("j"); // line 2 (fn b)
        e.blame_line();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        while e.blame_card.is_none() && std::time::Instant::now() < deadline {
            e.drain_git_jobs();
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        let card = e.blame_card.as_ref().expect("blame card");
        assert_eq!(card.summary, "add b");
        assert_eq!(card.author, "t");
    }

    #[test]
    fn permalink_needs_remote() {
        let (_d, e) = fixture();
        // no remote configured → honest refusal
        assert!(e.build_permalink().is_none());
    }

    #[test]
    fn permalink_resolves_sha_and_ssh_remote() {
        let (_d, mut e) = fixture();
        let root = e.cwd.clone();
        Command::new("git")
            .args([
                "-C",
                &root.display().to_string(),
                "remote",
                "add",
                "origin",
                "git@github.com:stropdev/strop.git",
            ])
            .output()
            .unwrap();
        e.discover_git();
        e.feed_text("j"); // line 2
        let url = e.build_permalink().expect("permalink");
        assert!(
            url.starts_with("https://github.com/stropdev/strop/blob/"),
            "{url}"
        );
        assert!(url.ends_with("/f.rs#L2"), "{url}");
        assert!(!url.contains("/main/"), "branch must resolve to SHA: {url}");
        e.yank_permalink();
        assert_eq!(e.register(None).0, url);
        assert!(e.osc52.is_some(), "OSC52 payload staged for the TUI");
    }

    fn git_out(root: &std::path::Path, args: &[&str]) -> String {
        String::from_utf8_lossy(
            &Command::new("git")
                .args(args)
                .current_dir(root)
                .output()
                .unwrap()
                .stdout,
        )
        .trim()
        .to_string()
    }

    fn pump_ready(e: &mut Editor, ready: impl Fn(&Editor) -> bool) {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        while !ready(e) && std::time::Instant::now() < deadline {
            e.drain_git_jobs();
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }

    /// `Space g b` toggles a per-buffer gutter; Enter dives into the
    /// cursor line's commit, positioned at its sha (0011 §3).
    #[test]
    fn blame_gutter_toggles_and_dives() {
        let (dir, mut e) = fixture();
        let root = dir.path().to_path_buf();
        e.feed_text(" gb");
        assert_eq!(e.blame_gutters.len(), 1, "gutter on for the buffer");
        pump_ready(&mut e, |e| e.blame_gutter_for(0).is_some());
        let gutter = e.blame_gutter_for(0).expect("gutter data loaded");
        assert_eq!(gutter.lines.len(), 2, "one blame per file line");
        assert_eq!(
            gutter.lines[0].sha,
            git_out(&root, &["rev-parse", "HEAD~1"])
        );
        assert_eq!(gutter.lines[1].sha, git_out(&root, &["rev-parse", "HEAD"]));

        // cursor on line 1 → Enter dives into "first", landing on its row
        e.feed(Key::Enter);
        pump_ready(&mut e, |e| {
            e.surface().is_some_and(
                |s| matches!(s, crate::editor::Surface::CommitLog { rows, .. } if !rows.is_empty()),
            )
        });
        assert!(
            matches!(e.surface(), Some(Surface::CommitLog { .. })),
            "dive opened the browser"
        );
        assert_eq!(
            e.buf().line_of(e.cursor),
            1,
            "cursor on the first-commit row"
        );
        assert_eq!(e.view_top, 1, "view positioned at the focused sha");
        let text = e.buf().rope.to_string();
        assert!(text.contains("first"), "{text}");

        // q returns; the gutter survives; toggle off removes it
        e.feed_text("q");
        assert_eq!(e.blame_gutters.len(), 1, "gutter is per-buffer view state");
        e.feed_text(" gb");
        assert!(e.blame_gutters.is_empty(), "second toggle turns it off");
        e.feed(Key::Enter);
        assert!(
            !matches!(e.surface(), Some(Surface::CommitLog { .. })),
            "Enter without a gutter stays inert"
        );
    }

    /// The gutter refuses to dive after edits (stale pairing) and falls
    /// back to the single-line card (0011 §3).
    #[test]
    fn stale_gutter_falls_back_to_card() {
        let (_d, mut e) = fixture();
        e.feed_text(" gb");
        // settle both spawned jobs (gutter + interim card): a sentinel
        // through the same FIFO channel proves everything before it
        // was delivered
        e.git_tx.send(GitJob::Error("\u{0}settled".into())).unwrap();
        pump_ready(&mut e, |e| e.message.contains('\u{0}'));
        e.message.clear();
        e.blame_card = None;
        // edit the buffer: line count changes, epoch bumps. Save so
        // the disk-blame card can speak about the new line at all
        e.feed_text("o");
        e.feed_text("fn c() {}");
        e.feed(Key::Esc);
        e.feed_text(":w<cr>");
        assert!(
            e.blame_gutter_for(0).is_none(),
            "edits void the line↔blame pairing"
        );
        e.blame_card = None;
        e.feed(Key::Enter);
        assert!(
            !matches!(e.surface(), Some(Surface::CommitLog { .. })),
            "no dive from stale data"
        );
        // the card is the fallback: it blames the cursor's own line
        // (wait for the *new* card — the toggle's line-1 card may
        // still be in flight)
        pump_ready(&mut e, |e| {
            e.blame_card.as_ref().is_some_and(|c| c.line == 3)
        });
    }

    /// The return point restores even when the origin buffer is not
    /// the one the close would land on next (0011 §1).
    #[test]
    fn return_point_restores_when_origin_not_current() {
        let (dir, mut e) = fixture();
        let root = dir.path();
        e.feed_text("j$"); // line 2, end
        let want = e.cursor;
        e.open_log(false);
        pump(&mut e);
        std::fs::write(root.join("g.rs"), "other\n").unwrap();
        e.open_buffer(root.join("g.rs").to_str().unwrap()).unwrap();
        assert_eq!(e.current, 2, "switched away from the log's origin");
        e.current = 1; // back onto the log surface
        e.cursor = 0;
        e.feed_text("q");
        assert_eq!(e.current, 0, "closing switches back to the origin");
        assert_eq!(e.cursor, want, "cursor restored, not line 1");
        assert_eq!(e.buf().line_of(e.cursor), 1);
    }

    /// A log result for a dead surface cannot land in the buffer that
    /// recycled its index (0011 §2).
    #[test]
    fn stale_log_results_are_dropped() {
        let (_d, mut e) = fixture();
        e.open_log(false);
        pump(&mut e);
        let stale = e.generation;
        e.feed_text("q"); // closes the surface; generation moves on
        assert_ne!(stale, e.generation);
        e.git_tx
            .send(GitJob::Log {
                buffer: 1,
                generation: stale,
                rows: vec![LogRow {
                    text: "POISON ROW".into(),
                    sha: None,
                }],
            })
            .unwrap();
        e.drain_git_jobs();
        for (i, b) in e.buffers.iter().enumerate() {
            let text = b.rope.to_string();
            assert!(!text.contains("POISON"), "buffer {i} clobbered: {text}");
        }
        // the live path still delivers
        e.open_log(false);
        pump(&mut e);
        assert!(e.buf().rope.to_string().contains("add b"));
    }

    /// A late gutter result for a toggled-off buffer is dropped: the
    /// entry is the toggle, not the job (0011 §2).
    #[test]
    fn gutter_result_dropped_after_toggle_off() {
        let (dir, mut e) = fixture();
        let key = dir.path().join("f.rs").canonicalize().unwrap();
        e.feed_text(" gb"); // on (job in flight)
        e.feed_text(" gb"); // off
        assert!(e.blame_gutters.is_empty());
        e.git_tx
            .send(GitJob::Gutter {
                path: key,
                generation: e.generation, // even a current generation
                lines: vec![strop_git::memory::BlameLine {
                    sha: "deadbeef".into(),
                    author: "nobody".into(),
                    age: "1m".into(),
                    ts: 0,
                }],
            })
            .unwrap();
        e.drain_git_jobs();
        assert!(
            e.blame_gutters.is_empty(),
            "a late job must not re-open a closed gutter"
        );
    }

    /// Two files in one fixture repo; the second commit touches both.
    fn multi_file_fixture() -> (tempfile::TempDir, Editor) {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(root)
                .output()
                .unwrap();
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@t.t"]);
        git(&["config", "user.name", "t"]);
        std::fs::write(root.join("a.rs"), "one\n").unwrap();
        std::fs::write(root.join("b.rs"), "uno\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-qm", "base"]);
        std::fs::write(root.join("a.rs"), "one\ntwo\n").unwrap();
        std::fs::write(root.join("b.rs"), "uno\ndos\n").unwrap();
        git(&["commit", "-qam", "touch both"]);
        let mut e = Editor::new(Buffer::open(root.join("a.rs").to_str().unwrap()).unwrap());
        e.cwd = root.to_path_buf();
        e.discover_git();
        (dir, e)
    }

    /// Dive to a file delta: the surface carries the commit's files,
    /// and `]f`/`[f` walk them, wrapping (0011 §4).
    #[test]
    fn commit_file_nav_walks_files() {
        let (_d, mut e) = multi_file_fixture();
        e.open_log(false);
        pump(&mut e);
        e.feed(Key::Enter); // newest commit → changed files
        e.feed_text("jj");
        e.feed(Key::Enter); // a.rs → delta
        let (label, files) = match e.surface() {
            Some(Surface::Diff {
                label,
                commit: Some(cf),
                ..
            }) => (label.clone(), cf.files.len()),
            other => panic!("not a commit diff: {other:?}"),
        };
        assert_eq!(label, "a.rs");
        assert_eq!(files, 2, "the sidebar's data rides the surface");

        e.feed_text("]f");
        match e.surface() {
            Some(Surface::Diff { label, .. }) => assert_eq!(label, "b.rs"),
            other => panic!("surface lost: {other:?}"),
        }
        let text = e.buf().rope.to_string();
        assert!(text.starts_with("b.rs +1 -0\n"), "{text}");
        assert!(text.contains("dos"), "{text}");
        assert!(e.message.contains("b.rs · 2/2"), "{}", e.message);

        e.feed_text("[f");
        assert!(
            matches!(e.surface(), Some(Surface::Diff { label, .. }) if label == "a.rs"),
            "back to the first file"
        );
        e.feed_text("[f"); // wraparound
        assert!(
            matches!(e.surface(), Some(Surface::Diff { label, .. }) if label == "b.rs"),
            "wraparound to the last file"
        );
        assert_eq!(
            e.buffers.len(),
            4,
            "]f rewrites the surface in place (no new buffers)"
        );
    }

    /// Tab hops focus between sidebar and diff; focused j/k steps
    /// files (tuicr's model); Enter hops back (0011 §4).
    #[test]
    fn tab_cycles_focus_between_sidebar_and_diff() {
        let (_d, mut e) = multi_file_fixture();
        e.open_log(false);
        pump(&mut e);
        e.feed(Key::Enter); // changed files
        e.feed_text("jj");
        e.feed(Key::Enter); // a.rs delta
        assert!(!e.sidebar_focused());

        e.feed(crate::editor::Key::Tab);
        assert!(e.sidebar_focused(), "tab focuses the sidebar");
        e.feed_text("j"); // focused j steps to the next file
        assert!(
            matches!(e.surface(), Some(Surface::Diff { label, .. }) if label == "b.rs"),
            "j stepped to b.rs"
        );
        assert!(e.sidebar_focused(), "focus survives the file step");
        e.feed(crate::editor::Key::Enter);
        assert!(!e.sidebar_focused(), "enter hops back to the diff");
        e.feed(crate::editor::Key::Backtab);
        assert!(e.sidebar_focused(), "shift-tab focuses too");
    }

    /// `q` in a split closes the pane (buffer stays); the last pane's
    /// `q` closes the buffer and restores the origin (0011 §1).
    #[test]
    fn q_in_split_closes_pane_then_buffer() {
        let (_d, mut e) = fixture();
        e.open_log(false);
        pump(&mut e);
        e.feed(Key::CtrlW);
        e.feed_text("v"); // split: both panes show the log
        assert_eq!(e.panes.len(), 2);
        e.feed_text("q");
        assert_eq!(e.panes.len(), 1, "q closes the pane in a split");
        assert_eq!(e.buffers.len(), 2, "the surface buffer survives");
        assert!(
            matches!(e.surface(), Some(Surface::CommitLog { .. })),
            "still on the log"
        );
        e.feed_text("q");
        assert_eq!(e.buffers.len(), 1, "the last pane's q closes the buffer");
        assert_eq!(e.current, 0, "back on the origin buffer");
        assert!(e.surface().is_none());
    }

    /// Golden shape: the blame column renders per line; the commit
    /// sidebar renders beside the delta with the current file marked.
    #[test]
    fn gutters_and_sidebar_render() {
        let (dir, mut e) = fixture();
        let root = dir.path().to_path_buf();
        e.feed_text(" gb");
        pump_ready(&mut e, |e| e.blame_gutter_for(0).is_some());
        let frame = crate::headless::frame_string(&mut e, 100, 10);
        let first_sha = git_out(&root, &["rev-parse", "HEAD~1"]);
        assert!(
            frame.contains(&format!("{} t ", &first_sha[..7])),
            "blame cell: {frame}"
        );
        assert!(
            frame.contains("fn a() {}"),
            "content still renders right of the gutter: {frame}"
        );

        let (_d, mut e) = multi_file_fixture();
        e.open_log(false);
        pump(&mut e);
        e.feed(Key::Enter);
        e.feed_text("jj");
        e.feed(Key::Enter); // a.rs delta
        let frame = crate::headless::frame_string(&mut e, 100, 12);
        assert!(frame.contains("▌a.rs"), "current file marked: {frame}");
        assert!(frame.contains(" b.rs"), "sibling files listed: {frame}");
        e.feed_text("]f");
        let frame = crate::headless::frame_string(&mut e, 100, 12);
        assert!(frame.contains("▌b.rs"), "marker follows ]f: {frame}");
    }
}