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
use hjkl_buffer::Buffer;
use hjkl_engine::{Host, MarkJump, Options};
use hjkl_vim::VimEditorExt;
use std::path::PathBuf;
use super::{App, DiskState, STATUS_LINE_HEIGHT};
use crate::host::TuiHost;
impl App {
/// Switch the focused window to display slot `idx` and refresh its
/// viewport spans. Records the previous slot index in `prev_active`
/// for alt-buffer (`<C-^>` / `:b#`).
pub(crate) fn switch_to(&mut self, idx: usize) {
// The explorer scratch buffer is never a switch target — it's managed
// as its own pane, not a normal buffer.
if self.slots.get(idx).is_some_and(|s| s.is_explorer) {
return;
}
// Never load a normal buffer into the explorer pane. If the explorer is
// focused (e.g. clicking a buffer-line entry while it's focused),
// redirect to the nearest non-explorer window first.
if self.explorer_buf_focused()
&& let Some(win_id) = self.nearest_non_explorer_window()
{
self.switch_focus(win_id);
}
let current_slot = self.focused_slot_idx();
if idx != current_slot {
self.prev_active = Some(current_slot);
}
// Update the synthetic `%` register with the new slot's filename so
// `"%p`, `<C-r>%`, and `:echo @%` reflect the correct path.
let fname = self.slots[idx]
.filename
.as_deref()
.map(|p| p.to_string_lossy().into_owned());
self.slots[idx].editor.registers_mut().set_filename(fname);
// Keep the engine's current_buffer_id in sync so `mA`–`mZ` global
// marks tag new marks with the correct slot id.
let new_bid = self.slots[idx].buffer_id;
self.slots[idx].editor.set_current_buffer_id(new_bid);
// Point the focused window at the new slot.
let fw = self.focused_window();
self.windows[fw].as_mut().expect("focused_window open").slot = idx;
// Rebuild the focused window's view editor onto the new slot's Content
// (#151 Phase D) so active_editor() below sees the switched buffer.
self.reconcile_window_editors();
if let Ok(size) = crossterm::terminal::size() {
let vp = self.active_editor_mut().host_mut().viewport_mut();
vp.width = size.0;
vp.height = size.1.saturating_sub(STATUS_LINE_HEIGHT);
}
// recompute_and_install runs render_viewport sync (post fully-sync
// refactor) — no need for a preview_render warm-up paint.
self.recompute_and_install();
self.refresh_git_signs_force();
// Follow the new active buffer in the explorer (select its row).
self.explorer_reveal_active();
}
/// `:bnext` — cycle active forward, skipping `is_explorer` slots.
/// No-op when only one non-explorer slot.
pub(crate) fn buffer_next(&mut self) {
if !self.require_multi_buffer() {
return;
}
let n = self.slots.len();
let current = self.focused_slot_idx();
// Walk forward, skipping explorer slots. Guard against all-explorer edge.
let next = (1..=n).find_map(|i| {
let idx = (current + i) % n;
if !self.slots[idx].is_explorer {
Some(idx)
} else {
None
}
});
if let Some(next) = next {
self.switch_to(next);
}
}
/// `:bprev` — cycle active backward, skipping `is_explorer` slots.
/// No-op when only one non-explorer slot.
pub(crate) fn buffer_prev(&mut self) {
if !self.require_multi_buffer() {
return;
}
let n = self.slots.len();
let current = self.focused_slot_idx();
let prev = (1..=n).find_map(|i| {
let idx = (current + n - i) % n;
if !self.slots[idx].is_explorer {
Some(idx)
} else {
None
}
});
if let Some(prev) = prev {
self.switch_to(prev);
}
}
/// `<C-^>` / `:b#` — switch to the previously-active buffer slot.
pub(crate) fn buffer_alt(&mut self) {
if !self.require_multi_buffer() {
return;
}
match self.prev_active {
Some(i) if i < self.slots.len() => {
self.switch_to(i);
}
_ => {
self.bus.warn("no alternate buffer");
}
}
}
/// `:bdelete[!]` — close the active slot. With more than one slot
/// open the slot is removed; on the last slot the buffer is reset
/// to an empty unnamed scratch buffer (vim parity for `:bd` on the
/// only buffer leaving an empty editor instead of quitting).
pub(crate) fn buffer_delete(&mut self, force: bool) {
if !force && self.active().dirty {
self.bus
.error("E89: No write since last change (add ! to override)");
return;
}
let active_slot = self.focused_slot_idx();
if self.slots.len() == 1 {
self.lsp_detach_buffer(active_slot);
let old_id = self.active().buffer_id;
self.syntax.forget(old_id);
let new_id = self.next_buffer_id;
self.next_buffer_id += 1;
let host = TuiHost::new();
let mut editor = hjkl_vim::vim_editor(Buffer::new(), host, Options::default());
editor.set_current_buffer_id(new_id);
editor.set_registers_arc(self.registers.clone());
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 slot = &mut self.slots[0];
slot.buffer_id = new_id;
slot.editor = editor;
slot.filename = None;
slot.dirty = false;
slot.is_new_file = false;
slot.is_untracked = false;
slot.diag_signs.clear();
slot.git_signs.clear();
slot.last_git_dirty_gen = None;
slot.git_repo_present = None; // re-probe on next edit
slot.saved_hash = 0;
slot.saved_len = 0;
slot.disk_mtime = None;
slot.disk_len = None;
slot.disk_state = DiskState::Synced;
slot.snapshot_saved();
// Keep all windows pointing at slot 0 (the only one).
for win in self.windows.iter_mut().flatten() {
win.slot = 0;
}
// Rebuild window view editors onto the replacement Content (#151 Phase D).
self.reconcile_window_editors();
// No file open in slot 0 anymore — stop watching it (#242).
self.fs_watch_sync();
self.bus.info("buffer closed (replaced with [No Name])");
return;
}
self.lsp_detach_buffer(active_slot);
let mut removed = self.slots.remove(active_slot);
self.syntax.forget(removed.buffer_id);
// Drop the closed buffer's swap. The owning process stays alive, so the
// orphan scan never reaps it, and the slot is gone so cleanup_swaps_on_exit
// can't either — leaving it makes a later open of the same file surface a
// spurious recovery prompt.
if let Some(p) = removed.swap_path.take() {
let _ = hjkl_app::swap::remove_swap(&p);
}
// Fix up all window slot pointers that reference the removed or shifted slots.
let slot_count = self.slots.len();
for win in self.windows.iter_mut().flatten() {
if win.slot == active_slot {
// Was pointing at the removed slot — redirect to slot before it (or 0).
win.slot = if active_slot > 0 { active_slot - 1 } else { 0 };
} else if win.slot > active_slot {
// Shift down due to the Vec::remove.
win.slot -= 1;
}
// Clamp to valid range just in case.
win.slot = win.slot.min(slot_count.saturating_sub(1));
}
let target = self.focused_slot_idx();
self.switch_to(target);
// Clear alt-buffer pointer after the switch: prev_active may refer
// to a removed or re-indexed slot. Reset unconditionally.
self.prev_active = None;
// The removed slot's file (if any) may no longer be open — resync (#242).
self.fs_watch_sync();
let name = removed
.filename
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "[No Name]".into());
self.bus.info(format!("buffer closed: \"{name}\""));
}
/// Close buffer slot `idx` triggered by a mouse click on the `✕` glyph.
///
/// Switches focus to the target slot first (so `buffer_delete` operates on
/// it), then calls `buffer_delete(false)` — preserving the unsaved-changes
/// guard: a dirty buffer emits E89 rather than silently discarding changes.
pub(crate) fn close_buffer_slot(&mut self, idx: usize) {
if idx != self.focused_slot_idx() {
self.switch_to(idx);
}
self.buffer_delete(false);
}
/// `:bwipeout[!]` — completely remove the active buffer: drop marks,
/// jumplist entries, and all per-buffer cached state. With more than
/// one slot open the slot is removed (same mechanics as `buffer_delete`
/// since the slot — and its editor — vanish entirely). On the last
/// slot a fresh scratch buffer is installed and the old editor's marks
/// and jumplists are explicitly discarded before replacement, ensuring
/// no state leaks into the new session.
pub(crate) fn buffer_wipe(&mut self, force: bool) {
if !force && self.active().dirty {
self.bus
.error("E89: No write since last change (add ! to override)");
return;
}
let active_slot = self.focused_slot_idx();
if self.slots.len() == 1 {
// Explicitly wipe marks and jumplists before discarding the editor
// so no state leaks into the replacement scratch buffer.
{
let editor = &mut self.slots[0].editor;
let mark_chars: Vec<char> = editor.marks().map(|(c, _)| c).collect();
for c in mark_chars {
editor.clear_mark(c);
}
editor.jump_back_list_mut().clear();
editor.jump_fwd_list_mut().clear();
}
// Also clear LSP diagnostics for the wiped buffer.
{
let slot = &mut self.slots[0];
slot.lsp_diags.clear();
slot.diag_signs_lsp.clear();
}
self.lsp_detach_buffer(active_slot);
let old_id = self.active().buffer_id;
self.syntax.forget(old_id);
let new_id = self.next_buffer_id;
self.next_buffer_id += 1;
let host = TuiHost::new();
let mut editor = hjkl_vim::vim_editor(Buffer::new(), host, Options::default());
editor.set_current_buffer_id(new_id);
editor.set_registers_arc(self.registers.clone());
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 slot = &mut self.slots[0];
slot.buffer_id = new_id;
slot.editor = editor;
slot.filename = None;
slot.dirty = false;
slot.is_new_file = false;
slot.is_untracked = false;
slot.diag_signs.clear();
slot.git_signs.clear();
slot.last_git_dirty_gen = None;
slot.git_repo_present = None; // re-probe on next edit
slot.saved_hash = 0;
slot.saved_len = 0;
slot.disk_mtime = None;
slot.disk_len = None;
slot.disk_state = DiskState::Synced;
slot.snapshot_saved();
// Keep all windows pointing at slot 0 (the only one).
for win in self.windows.iter_mut().flatten() {
win.slot = 0;
}
// Rebuild window view editors onto the fresh scratch Content (#151 Phase D).
self.reconcile_window_editors();
// No file open in slot 0 anymore — stop watching it (#242).
self.fs_watch_sync();
self.bus.info("buffer wiped (replaced with [No Name])");
return;
}
// Multi-slot: removing the slot entirely discards the editor (and all
// its marks/jumps) — same mechanics as buffer_delete.
self.lsp_detach_buffer(active_slot);
let mut removed = self.slots.remove(active_slot);
self.syntax.forget(removed.buffer_id);
// Drop the closed buffer's swap (see buffer_delete for rationale).
if let Some(p) = removed.swap_path.take() {
let _ = hjkl_app::swap::remove_swap(&p);
}
let slot_count = self.slots.len();
for win in self.windows.iter_mut().flatten() {
if win.slot == active_slot {
win.slot = if active_slot > 0 { active_slot - 1 } else { 0 };
} else if win.slot > active_slot {
win.slot -= 1;
}
win.slot = win.slot.min(slot_count.saturating_sub(1));
}
let target = self.focused_slot_idx();
self.switch_to(target);
self.prev_active = None;
// The removed slot's file (if any) may no longer be open — resync (#242).
self.fs_watch_sync();
let name = removed
.filename
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "[No Name]".into());
self.bus.info(format!("buffer wiped: \"{name}\""));
}
/// Returns `true` when multiple non-explorer slots are open; otherwise
/// sets the "only one buffer open" status message and returns `false`.
pub(crate) fn require_multi_buffer(&mut self) -> bool {
let real_count = self.slots.iter().filter(|s| !s.is_explorer).count();
if real_count <= 1 {
self.bus.warn("only one buffer open");
return false;
}
true
}
/// `:ls` / `:buffers` — render the buffer list to a single status
/// line. Marks: `%` active, `+` modified. Explorer slots are excluded.
pub(crate) fn list_buffers(&self) -> String {
let active_slot = self.focused_slot_idx();
let mut parts = Vec::with_capacity(self.slots.len());
for (i, slot) in self.slots.iter().enumerate() {
if slot.is_explorer {
continue;
}
let active = if i == active_slot { '%' } else { ' ' };
let modf = if slot.dirty { '+' } else { ' ' };
let name = slot
.filename
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "[No Name]".into());
parts.push(format!("{}:{active}{modf} \"{name}\"", i + 1));
}
parts.join(" | ")
}
// ── nvim-api helpers ──────────────────────────────────────────────────────
/// Buffer ids of all non-explorer slots, as `u64` (nvim wire format).
pub(crate) fn nvim_buffer_ids(&self) -> Vec<u64> {
self.slots
.iter()
.filter(|s| !s.is_explorer)
.map(|s| s.buffer_id)
.collect()
}
/// Buffer id of the currently focused slot, as `u64`.
pub(crate) fn nvim_current_buffer_id(&self) -> u64 {
self.active().buffer_id
}
/// Index into `self.slots` whose `buffer_id` matches `id`, or `None`.
pub(crate) fn nvim_slot_index_for_buffer(&self, id: u64) -> Option<usize> {
self.slots.iter().position(|s| s.buffer_id == id)
}
/// Absolute-path filename for the slot with `buffer_id == id`.
/// Returns `""` when the slot has no filename (unnamed scratch buffer).
pub(crate) fn nvim_buffer_name(&self, id: u64) -> Option<String> {
let slot = self.slots.iter().find(|s| s.buffer_id == id)?;
Some(match &slot.filename {
None => String::new(),
Some(p) => {
// Try to canonicalize (resolves symlinks + relative paths);
// fall back to whatever we have if the file doesn't exist yet.
std::fs::canonicalize(p)
.unwrap_or_else(|_| {
if p.is_absolute() {
p.clone()
} else {
std::env::current_dir()
.map(|cwd| cwd.join(p))
.unwrap_or_else(|_| p.clone())
}
})
.display()
.to_string()
}
})
}
/// Set the filename for the slot with `buffer_id == id`.
pub(crate) fn nvim_set_buffer_name(&mut self, id: u64, name: &str) {
if let Some(slot) = self.slots.iter_mut().find(|s| s.buffer_id == id) {
slot.filename = if name.is_empty() {
None
} else {
Some(PathBuf::from(name))
};
}
}
/// Shared reference to the slot-level editor for the given buffer id.
pub(crate) fn nvim_slot_editor(
&self,
id: u64,
) -> Option<&hjkl_engine::Editor<hjkl_buffer::Buffer, crate::host::TuiHost>> {
self.slots
.iter()
.find(|s| s.buffer_id == id)
.map(|s| &s.editor)
}
/// Mutable reference to the slot-level editor for the given buffer id.
pub(crate) fn nvim_slot_editor_mut(
&mut self,
id: u64,
) -> Option<&mut hjkl_engine::Editor<hjkl_buffer::Buffer, crate::host::TuiHost>> {
self.slots
.iter_mut()
.find(|s| s.buffer_id == id)
.map(|s| &mut s.editor)
}
/// First buffer id whose stored filename string contains `name` as a
/// substring, or `None` if no slot matches. Used by `nvim_call_function`
/// `bufnr("name")` semantics.
pub(crate) fn nvim_buffer_id_for_name(&self, name: &str) -> Option<u64> {
self.slots.iter().find_map(|s| {
let fname = s.filename.as_ref()?.to_string_lossy();
if fname.contains(name) {
Some(s.buffer_id)
} else {
None
}
})
}
/// Allocate a fresh empty unnamed buffer slot (nvim_create_buf).
/// The slot is appended but NOT switched to; returns the new buffer id.
pub(crate) fn nvim_create_buffer(&mut self) -> u64 {
use super::{BufferFeatures, BufferSlot, DiskState};
use crate::app::STATUS_LINE_HEIGHT;
use crate::host::TuiHost;
use hjkl_buffer::Buffer;
use hjkl_engine::Options;
use std::time::Instant;
let buffer_id = self.next_buffer_id;
self.next_buffer_id += 1;
let host = TuiHost::new();
let mut editor = hjkl_vim::vim_editor(Buffer::new(), host, Options::default());
editor.set_current_buffer_id(buffer_id);
editor.set_registers_arc(self.registers.clone());
// Mirror the nvim_api build_app viewport (80×24) for headless paths;
// in the real TUI crossterm::terminal::size() wins.
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 mut slot = BufferSlot {
buffer_id,
is_explorer: false,
features: BufferFeatures::default(),
editor,
filename: None,
dirty: false,
is_new_file: false,
is_untracked: false,
diag_signs: Vec::new(),
diag_signs_lsp: Vec::new(),
lsp_diags: Vec::new(),
last_lsp_dirty_gen: None,
git_signs: Vec::new(),
last_git_dirty_gen: None,
last_git_refresh_at: Instant::now(),
blame: Vec::new(),
last_blame_dirty_gen: None,
last_blame_refresh_at: Instant::now(),
saved_hash: 0,
saved_len: 0,
signature_cache: None,
disk_mtime: None,
disk_len: None,
disk_state: DiskState::Synced,
swap_path: None,
last_swap_dirty_gen: None,
last_fold_dirty_gen: None,
git_repo_present: None,
commit_ctx: None,
};
slot.snapshot_saved();
self.slots.push(slot);
buffer_id
}
/// Allocate a fresh `BufferId` and load `path` into a new slot.
/// Returns the index of the newly pushed slot (does NOT switch).
pub(crate) fn open_new_slot(&mut self, path: PathBuf) -> Result<usize, String> {
let buffer_id = self.next_buffer_id;
self.next_buffer_id += 1;
let slot = super::build_slot(&mut self.syntax, buffer_id, Some(path), &self.config)?;
self.slots.push(slot);
let idx = self.slots.len() - 1;
self.lsp_attach_buffer(idx);
// Event-driven autoreload: watch this file's directory (#242).
self.fs_watch_sync();
Ok(idx)
}
/// Dispatch a buffer-navigation [`crate::keymap_actions::AppAction`].
///
/// Handles variants:
/// - BufferNext / BufferPrev / BufferAlt
/// - BufferCycleH / BufferCycleL (predicate-gated: fall back to viewport motion)
/// - Tabnext / Tabprev (delegated through dispatch_ex)
pub(crate) fn dispatch_buffer_action(
&mut self,
action: crate::keymap_actions::AppAction,
count: usize,
) {
use crate::keymap_actions::AppAction;
match action {
AppAction::Tabnext => {
for _ in 0..count {
self.dispatch_ex("tabnext");
}
}
AppAction::Tabprev => {
for _ in 0..count {
self.dispatch_ex("tabprev");
}
}
AppAction::BufferNext => self.buffer_next(),
AppAction::BufferPrev => self.buffer_prev(),
AppAction::BufferAlt => self.buffer_alt(),
AppAction::BufferCycleH => {
if self.slots.len() > 1 {
self.buffer_prev();
} else {
// Single slot: fall back to viewport-top motion.
let n = self.pending_count.take_or(1) as usize;
self.active_editor_mut()
.apply_motion(hjkl_vim::MotionKind::ViewportTop, n);
}
}
AppAction::BufferCycleL => {
if self.slots.len() > 1 {
self.buffer_next();
} else {
// Single slot: fall back to viewport-bottom motion.
let n = self.pending_count.take_or(1) as usize;
self.active_editor_mut()
.apply_motion(hjkl_vim::MotionKind::ViewportBottom, n);
}
}
_ => {}
}
}
/// Handle the result of `Editor::try_goto_mark_line` /
/// `Editor::try_goto_mark_char`. Switches to the correct slot for cross-
/// buffer marks, positions the cursor, and syncs. Emits an error toast
/// when the referenced buffer has been closed.
pub(crate) fn apply_mark_jump(&mut self, jump: MarkJump, linewise: bool) {
match jump {
MarkJump::SameBuffer => {
self.sync_after_engine_mutation();
}
MarkJump::CrossBuffer {
buffer_id,
row,
col,
} => {
let slot_idx = self.slots.iter().position(|s| s.buffer_id == buffer_id);
match slot_idx {
Some(idx) => {
self.switch_to(idx);
if linewise {
self.active_editor_mut().jump_cursor(row, 0);
self.active_editor_mut()
.apply_motion(hjkl_vim::MotionKind::FirstNonBlank, 1);
} else {
self.active_editor_mut().jump_cursor(row, col);
}
self.sync_after_engine_mutation();
}
None => {
self.bus.error(format!(
"E474: mark references a closed buffer (id {buffer_id})"
));
}
}
}
MarkJump::Unset => { /* silent no-op — mark not set */ }
}
}
}