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
//! Keyboard event dispatch: the core `handle_key` state machine.
//!
//! Split out of `app.rs`; this is the single entry point that all
//! keyboard input flows through, delegating to pane/clipboard/theme
//! helpers defined in sibling modules and in the active [`FileExplorer`]
//! pane itself.
use super::*;
impl App {
// ── Event handling ────────────────────────────────────────────────────────
/// Process a single [`crossterm::event::KeyEvent`] and update application state.
///
/// This is the core key-dispatch method. Library consumers that read
/// their own events (e.g. via a shared event loop) should call this
/// directly instead of [`App::handle_event`].
///
/// Returns `true` when the event loop should exit (user confirmed a
/// selection or dismissed the explorer).
///
/// # Example
///
/// ```
/// use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
/// use tui_file_explorer::{App, AppOptions};
///
/// let mut app = App::new(AppOptions::default());
///
/// // Normally `event` comes from `crossterm::event::read()`.
/// let event = Event::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
/// if let Event::Key(key) = event {
/// let should_exit = app.handle_key(key).unwrap();
/// assert!(!should_exit);
/// }
/// ```
pub fn handle_key(&mut self, key: crossterm::event::KeyEvent) -> io::Result<bool> {
// Only react to key-press events. On Windows (and terminals that
// negotiate the kitty keyboard protocol) crossterm delivers both
// Press *and* Release events for every physical key-press. Without
// this guard the handler runs twice per key — once on press and once
// on release — which silently clobbers multi-item clipboard state
// (the release re-runs yank after marks have been cleared, falling
// back to the single cursor entry).
press_only!(key, Ok(false));
// ── Inline editor intercepts all input ───────────────────────────────
if let Some(ref mut editor) = self.inline_editor {
match editor.handle_key(key) {
EditorAction::Continue => return Ok(false),
EditorAction::Saved => {
let fname = editor
.path()
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
self.notify(format!("Saved '{fname}'"));
// Reload panes to reflect any on-disk changes.
for p in &mut self.panes {
p.reload();
p.clear_dir_size_cache();
}
self.preview_state.invalidate();
return Ok(false);
}
EditorAction::Exit => {
let edited = editor.path().to_path_buf();
self.inline_editor = None;
// A bulk rename edited with the built-in editor applies
// when that editor closes.
self.editor_finished(&edited);
// Reload panes in case the file was changed externally.
for p in &mut self.panes {
p.reload();
}
self.preview_state.invalidate();
return Ok(false);
}
}
}
// Always handle Ctrl-C.
if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
return Ok(true);
}
// ── Modal intercepts all input ────────────────────────────────────────
if let Some(modal) = self.modal.take() {
match &modal {
Modal::Delete { path } => match key.code {
KeyCode::Char('y' | 'Y') => {
let p = path.clone();
self.confirm_delete(&p);
}
_ => self.status_msg = "Delete cancelled.".into(),
},
Modal::MultiDelete { paths } => match key.code {
KeyCode::Char('y' | 'Y') => {
let ps = paths.clone();
self.confirm_delete_many(&ps);
}
_ => self.status_msg = "Multi-delete cancelled.".into(),
},
Modal::Overwrite { src, dst, is_cut } => match key.code {
KeyCode::Char('y' | 'Y') => {
let (s, d, cut) = (src.clone(), dst.clone(), *is_cut);
self.do_paste(&s, &d, cut);
}
_ => self.status_msg = "Paste cancelled.".into(),
},
}
return Ok(false);
}
// The picker overlay (bookmarks / fuzzy finder) owns the keyboard.
if self.picker.is_some() {
self.handle_picker_key(key);
return Ok(false);
}
// Active text modes consume printable keys before global shortcuts.
// This prevents names/search queries containing `p`, `d`, `t`, etc.
// from triggering application-level commands.
let pane_captures_text =
self.active_pane().is_searching() || self.active_pane().has_prompt();
if pane_captures_text {
let outcome = self.active_pane_mut().handle_key(key);
return self.apply_explorer_outcome(outcome);
}
// ── Debug-log scroll (Ctrl+Up / Ctrl+Down) ───────────────────────────
if self.verbose {
match key.code {
KeyCode::Up if key.modifiers.contains(KeyModifiers::CONTROL) => {
let max = self.debug_log.len().saturating_sub(1);
self.debug_scroll = (self.debug_scroll + 1).min(max);
return Ok(false);
}
KeyCode::Down if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.debug_scroll = self.debug_scroll.saturating_sub(1);
return Ok(false);
}
_ => {}
}
}
// ── Preview scroll (Ctrl+J / Ctrl+K) ─────────────────────────────────
if self.show_preview {
match key.code {
KeyCode::Char('j') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.preview_state.scroll_down(3);
return Ok(false);
}
KeyCode::Char('k') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.preview_state.scroll_up(3);
return Ok(false);
}
_ => {}
}
}
// ── Global keys (always active) ─────────────────────────────────
// ── Editor panel navigation (arrows / j / k steal focus when open) ───
if self.show_editor_panel {
match key.code {
KeyCode::Down | KeyCode::Char('j') if key.modifiers.is_empty() => {
let editors = App::all_editors();
self.editor_panel_idx = (self.editor_panel_idx + 1) % editors.len();
return Ok(false);
}
KeyCode::Up | KeyCode::Char('k') if key.modifiers.is_empty() => {
let editors = App::all_editors();
self.editor_panel_idx = self
.editor_panel_idx
.checked_sub(1)
.unwrap_or(editors.len() - 1);
return Ok(false);
}
KeyCode::Enter => {
let editors = App::all_editors();
self.editor = editors[self.editor_panel_idx].clone();
self.show_editor_panel = false;
return Ok(false);
}
KeyCode::Esc => {
self.show_editor_panel = false;
return Ok(false);
}
_ => {}
}
}
// ── Theme panel navigation (arrows / j / k steal focus when open) ────
if self.show_theme_panel {
match key.code {
KeyCode::Down | KeyCode::Char('j') if key.modifiers.is_empty() => {
self.next_theme();
return Ok(false);
}
KeyCode::Up | KeyCode::Char('k') if key.modifiers.is_empty() => {
self.prev_theme();
return Ok(false);
}
_ => {}
}
}
match key.code {
// Cycle theme forward
KeyCode::Char('t') if key.modifiers.is_empty() => {
self.next_theme();
return Ok(false);
}
// Cycle theme backward
KeyCode::Char('[') => {
self.prev_theme();
return Ok(false);
}
// Toggle theme panel — closes options/editor panels if open
KeyCode::Char('T') => {
self.show_theme_panel = !self.show_theme_panel;
if self.show_theme_panel {
self.show_options_panel = false;
self.show_editor_panel = false;
}
return Ok(false);
}
// Toggle options panel — closes theme/editor panels if open
KeyCode::Char('O') => {
self.show_options_panel = !self.show_options_panel;
if self.show_options_panel {
self.show_theme_panel = false;
self.show_editor_panel = false;
}
return Ok(false);
}
// Toggle editor panel — closes theme/options panels if open
KeyCode::Char('E') => {
self.show_editor_panel = !self.show_editor_panel;
if self.show_editor_panel {
self.show_options_panel = false;
self.show_theme_panel = false;
self.sync_editor_panel_idx();
}
return Ok(false);
}
// Toggle cd-on-exit (also available in the options panel)
KeyCode::Char('C') => {
self.cd_on_exit = !self.cd_on_exit;
let state = if self.cd_on_exit { "on" } else { "off" };
self.status_msg = format!("cd-on-exit: {state}");
return Ok(false);
}
// Toggle preview panel
KeyCode::Char('P') => {
self.show_preview = !self.show_preview;
if self.show_preview {
// Force immediate preview update.
self.preview_state.invalidate();
}
return Ok(false);
}
// Open inline editor for the current file
KeyCode::Char('i') if key.modifiers.is_empty() => {
if let Some(entry) = self.active_pane().current_entry()
&& !entry.is_dir
{
match InlineEditor::open(&entry.path) {
Ok(ed) => {
self.inline_editor = Some(ed);
}
Err(e) => {
self.notify_error(format!("Cannot edit: {e}"));
}
}
}
return Ok(false);
}
// Switch pane (cycle forward / backward through all panes)
KeyCode::Tab => {
self.focus_next_pane();
return Ok(false);
}
KeyCode::BackTab => {
self.focus_prev_pane();
return Ok(false);
}
// Toggle single/multi-pane
KeyCode::Char('w') if key.modifiers.is_empty() => {
self.single_pane = !self.single_pane;
return Ok(false);
}
// Open a new pane at the active pane's current directory.
KeyCode::Char('t') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.add_pane_from_active();
return Ok(false);
}
// Close the active pane (at least one pane always remains).
KeyCode::Char('w') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.close_active_pane();
return Ok(false);
}
// Undo the last reversible action / redo it again
KeyCode::Char('u') if key.modifiers.is_empty() => {
self.undo();
return Ok(false);
}
KeyCode::Char('r') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.redo();
return Ok(false);
}
// Bulk rename in an editor
KeyCode::Char('R') => {
self.start_bulk_rename();
return Ok(false);
}
// Bookmark the current folder / open the bookmark list
KeyCode::Char('b') if key.modifiers.is_empty() => {
self.toggle_bookmark();
return Ok(false);
}
KeyCode::Char('B') => {
self.open_bookmarks();
return Ok(false);
}
// Recursive fuzzy finder
KeyCode::Char('f') if key.modifiers.is_empty() => {
self.open_fuzzy_find();
return Ok(false);
}
// Toggle git change markers
KeyCode::Char('v') if key.modifiers.is_empty() => {
self.toggle_git();
return Ok(false);
}
// Extract the highlighted archive
#[cfg(feature = "archive")]
KeyCode::Char('X') => {
self.extract_current_archive();
return Ok(false);
}
// Cut
KeyCode::Char('x') if key.modifiers.is_empty() => {
self.yank(ClipOp::Cut);
return Ok(false);
}
// Paste
KeyCode::Char('p') if key.modifiers.is_empty() => {
self.paste();
return Ok(false);
}
// Delete
KeyCode::Char('d') if key.modifiers.is_empty() => {
self.prompt_delete();
return Ok(false);
}
// Open the highlighted file in the configured editor.
KeyCode::Char('e') if key.modifiers.is_empty() => {
if self.editor != Editor::None {
if let Some(entry) = self.active_pane().current_entry()
&& !entry.is_dir
{
self.open_with_editor = Some(entry.path.clone());
}
// Silently ignore dirs — no status message per spec.
} else {
// No editor configured — tell the user how to set one.
self.notify_error("No editor set — open Editor picker (Shift + E) to pick one");
}
return Ok(false);
}
_ => {}
}
// ── Delegate to active pane explorer ─────────────────────────────────
// Clear any previous non-error status when navigating.
let outcome = self.active_pane_mut().handle_key(key);
self.apply_explorer_outcome(outcome)
}
fn apply_explorer_outcome(&mut self, outcome: ExplorerOutcome) -> io::Result<bool> {
match outcome {
ExplorerOutcome::Selected(path) => {
if self.active_pane().filesystem.is_dir(&path) {
self.selected = Some(path);
Ok(true)
} else if self.editor != Editor::None {
self.open_with_editor = Some(path);
Ok(false)
} else {
self.notify_error("No editor set — open Editor picker (Shift + E) to pick one");
Ok(false)
}
}
ExplorerOutcome::Dismissed => Ok(true),
ExplorerOutcome::MkdirCreated(path) => {
self.record_undo(UndoEntry::Create {
path: path.clone(),
is_dir: true,
});
self.reload_and_notify(&path, "Created folder");
self.preview_state.invalidate();
Ok(false)
}
ExplorerOutcome::TouchCreated(path) => {
self.record_undo(UndoEntry::Create {
path: path.clone(),
is_dir: false,
});
self.reload_and_notify(&path, "Created file");
self.preview_state.invalidate();
Ok(false)
}
ExplorerOutcome::RenameCompleted { from, to: path } => {
self.record_undo(UndoEntry::Rename {
from,
to: path.clone(),
});
self.reload_and_notify(&path, "Renamed to");
self.preview_state.invalidate();
Ok(false)
}
ExplorerOutcome::Pending => {
if !self.status_msg.starts_with("Error") && !self.status_msg.starts_with("Delete") {
self.status_msg.clear();
}
Ok(false)
}
ExplorerOutcome::Unhandled => Ok(false),
}
}
/// Dispatch a pre-read terminal [`Event`].
///
/// This is the testable core of event handling. Only [`Event::Key`]
/// events are forwarded to [`App::handle_key`]; all other event types
/// (mouse, resize, focus, paste) are consumed and silently ignored
/// because the application is entirely keyboard-driven.
///
/// # Why mouse capture is **not** enabled
///
/// Earlier versions of `tfe` enabled `EnableMouseCapture` even though no
/// widget or handler ever inspected mouse input. On macOS this caused
/// SGR mouse-tracking escape sequences (`^[[<35;…M`) to leak visually
/// at the bottom of the terminal. Removing mouse capture is safe on
/// **all** platforms (Linux, macOS, Windows) because the TUI is purely
/// keyboard-driven.
pub fn handle_raw_event(&mut self, event: Event) -> io::Result<bool> {
match event {
Event::Key(key) => {
// Custom `[app]` bindings (keymap.toml / KeyBindings) apply
// everywhere except while text input owns the keyboard.
let text_input = self.inline_editor.is_some()
|| self.modal.is_some()
|| self.active_pane().is_searching()
|| self.active_pane().has_prompt()
|| self.picker.is_some();
let key = if text_input || self.key_bindings.is_empty() {
Some(key)
} else {
self.key_bindings.translate(key)
};
match key {
Some(key) => self.handle_key(key),
None => Ok(false),
}
}
// Mouse, Resize, FocusGained, FocusLost, Paste — consume and
// discard. Resize is handled automatically by ratatui's
// `Terminal::draw` which queries the terminal size each frame.
_ => Ok(false),
}
}
/// Read one terminal event and update application state.
///
/// Calls [`event::read`] internally. If your application already owns the
/// event loop and reads events itself, call [`App::handle_key`] or
/// [`App::handle_raw_event`] instead.
///
/// Returns `true` when the event loop should exit (user confirmed a
/// selection or dismissed the explorer).
pub fn handle_event(&mut self) -> io::Result<bool> {
// While background work is running, wake up regularly so finished
// results get drawn even without user input.
if self.has_background_work() && !event::poll(Duration::from_millis(60))? {
self.poll_background();
return Ok(false);
}
self.handle_raw_event(event::read()?)
}
}