hjkl 0.11.0

Vim-modal terminal editor: standalone TUI built on the hjkl engine.
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
use std::path::PathBuf;
use std::time::{Duration, Instant};

use crate::picker_action::AppAction;

use git2::{BranchType, ErrorCode, ObjectType};
use hjkl_buffer::Buffer;
use hjkl_engine::{BufferEdit, Editor, Host, Options};

use super::{App, BufferSlot, DiskState, STATUS_LINE_HEIGHT};
use crate::host::TuiHost;
use crate::syntax::BufferId;

/// Window radius (in lines) around the cursor when snapshotting a buffer
/// for the picker preview. Bounds the per-frame tree-sitter parse cost
/// so huge buffers don't stall the picker.
const BUFFER_PREVIEW_WINDOW_RADIUS: usize = 250;

/// Snapshot a window of `buf` around the cursor as a `String`, returning
/// the content, the cursor row *within that window* (0-based), and the
/// original-buffer row of the first line in the window (`window_start`).
fn snapshot_buffer_window(buf: &hjkl_buffer::Buffer) -> (String, usize, usize) {
    let cursor_row = buf.cursor().row;
    let total = buf.row_count();
    let start = cursor_row.saturating_sub(BUFFER_PREVIEW_WINDOW_RADIUS);
    let end = (cursor_row + BUFFER_PREVIEW_WINDOW_RADIUS).min(total);
    let mut content = String::with_capacity((end - start).saturating_mul(80));
    for r in start..end {
        if let Some(line) = buf.line(r) {
            content.push_str(line);
            content.push('\n');
        }
    }
    (content, cursor_row - start, start)
}

impl App {
    /// Open the fuzzy file picker.
    pub(crate) fn open_picker(&mut self) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let theme =
            self.theme.syntax.clone() as std::sync::Arc<dyn hjkl_bonsai::Theme + Send + Sync>;
        let source = Box::new(crate::picker::HighlightedFileSource::new(
            cwd,
            theme,
            self.directory.clone(),
        ));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
    }

    /// Open the buffer picker over the currently open slots.
    pub(crate) fn open_buffer_picker(&mut self) {
        let inner = crate::picker::BufferSource::new(
            &self.slots,
            |s| {
                s.filename
                    .as_ref()
                    .and_then(|p| p.to_str())
                    .unwrap_or("[No Name]")
                    .to_owned()
            },
            |s| s.dirty,
            |s| snapshot_buffer_window(s.editor.buffer()).0,
            |s| s.filename.clone(),
            |s| snapshot_buffer_window(s.editor.buffer()).1,
            |s| snapshot_buffer_window(s.editor.buffer()).2,
        );
        let theme =
            self.theme.syntax.clone() as std::sync::Arc<dyn hjkl_bonsai::Theme + Send + Sync>;
        let source = Box::new(crate::picker::HighlightedBufferSource::new(
            inner,
            theme,
            self.directory.clone(),
        ));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
    }

    /// Open the ripgrep content-search picker, optionally prepopulating
    /// the query with `pattern`.
    pub(crate) fn open_grep_picker(&mut self, pattern: Option<&str>) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let theme =
            self.theme.syntax.clone() as std::sync::Arc<dyn hjkl_bonsai::Theme + Send + Sync>;
        let source = Box::new(crate::picker::HighlightedRgSource::new(
            cwd,
            theme,
            self.directory.clone(),
        ));
        self.picker = Some(match pattern {
            Some(p) if !p.is_empty() => crate::picker::Picker::new_with_query(source, p),
            _ => crate::picker::Picker::new(source),
        });
        self.pending_leader = false;
    }

    /// Open the git-log commit picker.
    pub(crate) fn open_git_log_picker(&mut self) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let theme =
            self.theme.syntax.clone() as std::sync::Arc<dyn hjkl_bonsai::Theme + Send + Sync>;
        let source = Box::new(crate::picker_git::GitLogPicker::new(
            cwd,
            theme,
            self.directory.clone(),
        ));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
        self.pending_git = false;
    }

    /// Open the git-branch picker.
    pub(crate) fn open_git_branch_picker(&mut self) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let source = Box::new(crate::picker_git::GitBranchPicker::new(cwd));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
        self.pending_git = false;
    }

    /// Open the git file-history picker for the current buffer's path.
    pub(crate) fn open_git_file_history_picker(&mut self) {
        let filename = match self.active().filename.clone() {
            Some(p) => p,
            None => {
                self.status_message = Some("git: current buffer has no path".into());
                self.pending_leader = false;
                self.pending_git = false;
                return;
            }
        };

        // Resolve relative path inside the repo workdir.
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let abs = if filename.is_absolute() {
            filename.clone()
        } else {
            cwd.join(&filename)
        };

        // Discover repo to obtain workdir.
        let repo = match git2::Repository::discover(&abs) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some("git: not in a git repo".into());
                self.pending_leader = false;
                self.pending_git = false;
                return;
            }
        };

        let workdir = match repo.workdir() {
            Some(w) => w.to_path_buf(),
            None => {
                self.status_message = Some("git: bare repo — no workdir".into());
                self.pending_leader = false;
                self.pending_git = false;
                return;
            }
        };

        let rel_path = match abs.strip_prefix(&workdir) {
            Ok(r) => r.to_path_buf(),
            Err(_) => {
                self.status_message =
                    Some("git: current buffer is outside the repo workdir".into());
                self.pending_leader = false;
                self.pending_git = false;
                return;
            }
        };

        let theme =
            self.theme.syntax.clone() as std::sync::Arc<dyn hjkl_bonsai::Theme + Send + Sync>;
        let source = Box::new(crate::picker_git::GitFileHistoryPicker::new(
            workdir,
            rel_path,
            theme,
            self.directory.clone(),
        ));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
        self.pending_git = false;
    }

    /// Open the git-tags picker.
    pub(crate) fn open_git_tags_picker(&mut self) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let source = Box::new(crate::picker_git::GitTagsPicker::new(cwd));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
        self.pending_git = false;
    }

    /// Open the git-remotes picker.
    pub(crate) fn open_git_remotes_picker(&mut self) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let source = Box::new(crate::picker_git::GitRemotesPicker::new(cwd));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
        self.pending_git = false;
    }

    /// Open the git-stash picker.
    pub(crate) fn open_git_stash_picker(&mut self) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let source = Box::new(crate::picker_git::GitStashPicker::new(cwd));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
        self.pending_git = false;
    }

    /// Open the git-status fuzzy picker.
    pub(crate) fn open_git_status_picker(&mut self) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let theme =
            self.theme.syntax.clone() as std::sync::Arc<dyn hjkl_bonsai::Theme + Send + Sync>;
        let source = Box::new(crate::picker_git::GitStatusPicker::new(
            cwd,
            theme,
            self.directory.clone(),
        ));
        self.picker = Some(crate::picker::Picker::new(source));
        self.pending_leader = false;
        self.pending_git = false;
    }

    pub(crate) fn handle_picker_key(&mut self, key: crossterm::event::KeyEvent) {
        let event = match self.picker.as_mut() {
            Some(p) => p.handle_key(key),
            None => return,
        };
        match event {
            crate::picker::PickerEvent::None => {}
            crate::picker::PickerEvent::Cancel => {
                self.picker = None;
            }
            crate::picker::PickerEvent::Select(action) => {
                self.picker = None;
                self.dispatch_picker_action(action);
            }
        }
    }

    pub(crate) fn dispatch_picker_action(&mut self, action: crate::picker::PickerAction) {
        let boxed = match action {
            crate::picker::PickerAction::Custom(b) => b,
            crate::picker::PickerAction::None => return,
        };
        let app_action = match boxed.downcast::<AppAction>() {
            Ok(a) => *a,
            Err(_) => {
                self.status_message = Some("picker: unknown action type".into());
                return;
            }
        };
        match app_action {
            AppAction::OpenPath(path) => {
                let s = path.to_string_lossy().to_string();
                self.do_edit(&s, false);
            }
            AppAction::SwitchSlot(idx) => {
                if idx < self.slots.len() {
                    self.switch_to(idx);
                }
            }
            AppAction::OpenPathAtLine(path, line) => {
                let s = path.to_string_lossy().to_string();
                self.do_edit(&s, false);
                // goto_line is 1-based and clamps to buffer length.
                if line > 0 {
                    self.active_mut().editor.goto_line(line as usize);
                    // Reset viewport top so the line is visible.
                    let vp = self.active_mut().editor.host_mut().viewport_mut();
                    let top = (line as usize).saturating_sub(5);
                    vp.top_row = top;
                }
            }
            AppAction::ShowCommit(sha) => self.do_show_commit(&sha),
            AppAction::CheckoutBranch(name) => self.do_checkout_branch(&name),
            AppAction::CheckoutTag(name) => self.do_checkout_tag(&name),
            AppAction::FetchRemote(name) => self.do_fetch_remote(&name),
            AppAction::StashApply(idx) => self.do_stash_apply(idx),
            AppAction::StashPop(idx) => self.do_stash_pop(idx),
            AppAction::StashDrop(idx) => self.do_stash_drop(idx),
        }
    }

    pub(crate) fn do_checkout_branch(&mut self, name: &str) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let repo = match git2::Repository::discover(&cwd) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some("git: not in a repo".into());
                return;
            }
        };

        // Try local first, then remote.
        let local_result = repo.find_branch(name, BranchType::Local);
        let (branch, is_remote) = match local_result {
            Ok(b) => (b, false),
            Err(ref e) if e.code() == ErrorCode::NotFound => {
                match repo.find_branch(name, BranchType::Remote) {
                    Ok(b) => (b, true),
                    Err(_) => {
                        self.status_message = Some(format!("git: branch '{name}' not found"));
                        return;
                    }
                }
            }
            Err(e) => {
                self.status_message = Some(format!("git: {e}"));
                return;
            }
        };

        let target_obj = match branch.get().peel(git2::ObjectType::Commit) {
            Ok(o) => o,
            Err(e) => {
                self.status_message = Some(format!("git: {e}"));
                return;
            }
        };
        let target_oid = target_obj.id();

        let tree = match branch.get().peel_to_tree() {
            Ok(t) => t,
            Err(e) => {
                self.status_message = Some(format!("git: {e}"));
                return;
            }
        };

        // Pre-flight: paths that switching would touch (diff HEAD tree vs target tree)
        // intersected with dirty paths in workdir/index. Refuse with friendly list
        // instead of letting libgit2's safe() return opaque Conflict (-13).
        let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok());
        let touched: std::collections::HashSet<String> = match head_tree.as_ref() {
            Some(ht) => match repo.diff_tree_to_tree(Some(ht), Some(&tree), None) {
                Ok(diff) => {
                    let mut set = std::collections::HashSet::new();
                    diff.foreach(
                        &mut |delta, _| {
                            if let Some(p) = delta.new_file().path().and_then(|p| p.to_str()) {
                                set.insert(p.to_string());
                            }
                            if let Some(p) = delta.old_file().path().and_then(|p| p.to_str()) {
                                set.insert(p.to_string());
                            }
                            true
                        },
                        None,
                        None,
                        None,
                    )
                    .ok();
                    set
                }
                Err(_) => std::collections::HashSet::new(),
            },
            None => std::collections::HashSet::new(),
        };

        let mut so = git2::StatusOptions::new();
        so.include_untracked(false).include_ignored(false);
        let dirty: Vec<String> = match repo.statuses(Some(&mut so)) {
            Ok(statuses) => statuses
                .iter()
                .filter(|s| !s.status().is_empty())
                .filter_map(|s| s.path().map(|p| p.to_string()))
                .filter(|p| touched.contains(p))
                .collect(),
            Err(_) => Vec::new(),
        };

        if !dirty.is_empty() {
            let preview: Vec<&str> = dirty.iter().take(3).map(String::as_str).collect();
            let suffix = if dirty.len() > 3 {
                format!(", +{} more", dirty.len() - 3)
            } else {
                String::new()
            };
            self.status_message = Some(format!(
                "git: uncommitted changes in {}{} — stash or commit first",
                preview.join(", "),
                suffix,
            ));
            return;
        }

        let mut cb = git2::build::CheckoutBuilder::new();
        cb.safe();
        if let Err(e) = repo.checkout_tree(tree.as_object(), Some(&mut cb)) {
            self.status_message = Some(format!("git: checkout failed: {e}"));
            return;
        }

        if is_remote {
            // Detached HEAD for remote branch checkouts.
            if let Err(e) = repo.set_head_detached(target_oid) {
                self.status_message = Some(format!("git: {e}"));
                return;
            }
        } else {
            let refname = format!("refs/heads/{name}");
            if let Err(e) = repo.set_head(&refname) {
                self.status_message = Some(format!("git: {e}"));
                return;
            }
        }

        self.status_message = Some(format!("checked out {name}"));
        // Reload non-dirty buffers whose disk file changed during checkout.
        self.checktime_all();
    }

    pub(crate) fn do_checkout_tag(&mut self, name: &str) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let repo = match git2::Repository::discover(&cwd) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some("git: not in a repo".into());
                return;
            }
        };

        let refname = format!("refs/tags/{name}");
        let tag_ref = match repo.find_reference(&refname) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some(format!("git: tag '{name}' not found"));
                return;
            }
        };

        let target_obj = match tag_ref.peel(ObjectType::Commit) {
            Ok(o) => o,
            Err(e) => {
                self.status_message = Some(format!("git: {e}"));
                return;
            }
        };
        let target_oid = target_obj.id();

        let tree = match target_obj.peel_to_tree() {
            Ok(t) => t,
            Err(e) => {
                self.status_message = Some(format!("git: {e}"));
                return;
            }
        };

        // Pre-flight conflict check: same pattern as do_checkout_branch.
        let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok());
        let touched: std::collections::HashSet<String> = match head_tree.as_ref() {
            Some(ht) => match repo.diff_tree_to_tree(Some(ht), Some(&tree), None) {
                Ok(diff) => {
                    let mut set = std::collections::HashSet::new();
                    diff.foreach(
                        &mut |delta, _| {
                            if let Some(p) = delta.new_file().path().and_then(|p| p.to_str()) {
                                set.insert(p.to_string());
                            }
                            if let Some(p) = delta.old_file().path().and_then(|p| p.to_str()) {
                                set.insert(p.to_string());
                            }
                            true
                        },
                        None,
                        None,
                        None,
                    )
                    .ok();
                    set
                }
                Err(_) => std::collections::HashSet::new(),
            },
            None => std::collections::HashSet::new(),
        };

        let mut so = git2::StatusOptions::new();
        so.include_untracked(false).include_ignored(false);
        let dirty: Vec<String> = match repo.statuses(Some(&mut so)) {
            Ok(statuses) => statuses
                .iter()
                .filter(|s| !s.status().is_empty())
                .filter_map(|s| s.path().map(|p| p.to_string()))
                .filter(|p| touched.contains(p))
                .collect(),
            Err(_) => Vec::new(),
        };

        if !dirty.is_empty() {
            let preview: Vec<&str> = dirty.iter().take(3).map(String::as_str).collect();
            let suffix = if dirty.len() > 3 {
                format!(", +{} more", dirty.len() - 3)
            } else {
                String::new()
            };
            self.status_message = Some(format!(
                "git: uncommitted changes in {}{} — stash or commit first",
                preview.join(", "),
                suffix,
            ));
            return;
        }

        let mut cb = git2::build::CheckoutBuilder::new();
        cb.safe();
        if let Err(e) = repo.checkout_tree(tree.as_object(), Some(&mut cb)) {
            self.status_message = Some(format!("git: checkout failed: {e}"));
            return;
        }

        if let Err(e) = repo.set_head_detached(target_oid) {
            self.status_message = Some(format!("git: {e}"));
            return;
        }

        self.status_message = Some(format!("checked out tag {name} (detached HEAD)"));
        self.checktime_all();
    }

    pub(crate) fn do_fetch_remote(&mut self, name: &str) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let repo = match git2::Repository::discover(&cwd) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some("git: not in a repo".into());
                return;
            }
        };

        let mut remote = match repo.find_remote(name) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some(format!("git: remote '{name}' not found"));
                return;
            }
        };

        match remote.fetch(&[] as &[&str], None, None) {
            Ok(()) => {
                self.status_message = Some(format!("fetched {name}"));
            }
            Err(e) => {
                self.status_message = Some(format!("git: fetch {name} failed — {e}"));
            }
        }
    }

    pub(crate) fn do_stash_apply(&mut self, idx: usize) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut repo = match git2::Repository::discover(&cwd) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some("git: not in a repo".into());
                return;
            }
        };
        let mut opts = git2::StashApplyOptions::new();
        match repo.stash_apply(idx, Some(&mut opts)) {
            Ok(()) => {
                self.status_message = Some(format!("applied stash@{{{idx}}}"));
                self.checktime_all();
            }
            Err(e) => {
                self.status_message = Some(format!("stash apply conflict — {e}"));
            }
        }
    }

    pub(crate) fn do_stash_pop(&mut self, idx: usize) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut repo = match git2::Repository::discover(&cwd) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some("git: not in a repo".into());
                return;
            }
        };
        let mut opts = git2::StashApplyOptions::new();
        match repo.stash_pop(idx, Some(&mut opts)) {
            Ok(()) => {
                self.status_message = Some(format!("popped stash@{{{idx}}}"));
                self.checktime_all();
            }
            Err(e) => {
                self.status_message = Some(format!("stash pop conflict — {e}"));
            }
        }
    }

    pub(crate) fn do_stash_drop(&mut self, idx: usize) {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let mut repo = match git2::Repository::discover(&cwd) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some("git: not in a repo".into());
                return;
            }
        };
        match repo.stash_drop(idx) {
            Ok(()) => {
                self.status_message = Some(format!("dropped stash@{{{idx}}}"));
            }
            Err(e) => {
                self.status_message = Some(format!("git: stash drop failed — {e}"));
            }
        }
    }

    pub(crate) fn do_show_commit(&mut self, sha: &str) {
        let repo = match git2::Repository::discover(
            std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
        ) {
            Ok(r) => r,
            Err(_) => {
                self.status_message = Some("git: not in a repo".into());
                return;
            }
        };
        let oid = match git2::Oid::from_str(sha) {
            Ok(o) => o,
            Err(e) => {
                self.status_message = Some(format!("git: bad sha: {e}"));
                return;
            }
        };
        let commit = match repo.find_commit(oid) {
            Ok(c) => c,
            Err(e) => {
                self.status_message = Some(format!("git: {e}"));
                return;
            }
        };
        let content = crate::picker_git::render_commit(&repo, &commit);
        let short_sha = &sha[..7.min(sha.len())];
        match build_scratch_slot(
            &mut self.syntax,
            self.next_buffer_id,
            &content,
            &self.config,
        ) {
            Ok(slot) => {
                self.next_buffer_id += 1;
                self.slots.push(slot);
                let new_idx = self.slots.len() - 1;
                self.switch_to(new_idx);
                self.status_message = Some(format!("showing commit {short_sha}"));
            }
            Err(e) => {
                self.status_message = Some(e);
            }
        }
    }
}

/// Build a scratch [`BufferSlot`] pre-loaded with `content`. Mirrors
/// `build_slot`'s file-read path but injects content directly instead of
/// reading from disk, avoiding a file round-trip for ephemeral commit views.
fn build_scratch_slot(
    syntax: &mut crate::syntax::SyntaxLayer,
    buffer_id: BufferId,
    content: &str,
    config: &crate::config::Config,
) -> Result<BufferSlot, String> {
    let mut buffer = Buffer::new();
    let content = content.strip_suffix('\n').unwrap_or(content);
    BufferEdit::replace_all(&mut buffer, content);

    let host = TuiHost::new();
    let opts = Options {
        expandtab: config.editor.expandtab,
        tabstop: config.editor.tab_width as u32,
        shiftwidth: config.editor.tab_width as u32,
        softtabstop: config.editor.tab_width as u32,
        readonly: true,
        ..Options::default()
    };
    let mut editor = Editor::new(buffer, host, opts);
    if let Ok(size) = crossterm::terminal::size() {
        let vp = editor.host_mut().viewport_mut();
        vp.width = size.0;
        vp.height = size.1.saturating_sub(STATUS_LINE_HEIGHT);
    }
    let _ = editor.take_content_edits();
    let _ = editor.take_content_reset();

    let (vp_top, vp_height) = {
        let vp = editor.host().viewport();
        (vp.top_row, vp.height as usize)
    };
    if let Some(out) = syntax.preview_render(buffer_id, editor.buffer(), vp_top, vp_height) {
        editor.install_ratatui_syntax_spans(out.spans);
    }
    let initial_dg = editor.buffer().dirty_gen();
    let (key, signs) = if let Some(out) = syntax.wait_for_initial_result(Duration::from_millis(150))
    {
        let k = out.key;
        editor.install_ratatui_syntax_spans(out.spans);
        (Some(k), out.signs)
    } else {
        (Some((initial_dg, vp_top, vp_height)), Vec::new())
    };

    let mut slot = BufferSlot {
        buffer_id,
        editor,
        filename: None,
        dirty: false,
        is_new_file: false,
        is_untracked: false,
        diag_signs: signs,
        git_signs: Vec::new(),
        last_git_dirty_gen: None,
        last_git_refresh_at: Instant::now(),
        last_recompute_at: Instant::now() - Duration::from_secs(1),
        last_recompute_key: key,
        saved_hash: 0,
        saved_len: 0,
        disk_mtime: None,
        disk_len: None,
        disk_state: DiskState::Synced,
    };
    slot.snapshot_saved();
    Ok(slot)
}