tui-file-explorer 2.1.0

Embeddable keyboard-driven multi-pane file explorer for Ratatui
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use super::*;

impl FileExplorer {
    /// Dispatch a semantic command without coupling host code to key bindings.
    pub fn handle_command(&mut self, command: ExplorerCommand) -> ExplorerOutcome {
        let code = match command {
            ExplorerCommand::MoveUp => KeyCode::Up,
            ExplorerCommand::MoveDown => KeyCode::Down,
            ExplorerCommand::PageUp => KeyCode::PageUp,
            ExplorerCommand::PageDown => KeyCode::PageDown,
            ExplorerCommand::Top => KeyCode::Home,
            ExplorerCommand::Bottom => KeyCode::End,
            ExplorerCommand::Ascend => KeyCode::Left,
            ExplorerCommand::Navigate => KeyCode::Right,
            ExplorerCommand::Confirm => KeyCode::Enter,
            ExplorerCommand::ToggleHidden => KeyCode::Char('.'),
            ExplorerCommand::ToggleSizes => KeyCode::Char('z'),
            ExplorerCommand::Search => KeyCode::Char('/'),
            ExplorerCommand::CycleSort => KeyCode::Char('s'),
            ExplorerCommand::ToggleMark => KeyCode::Char(' '),
            ExplorerCommand::NewDirectory => KeyCode::Char('n'),
            ExplorerCommand::NewFile => KeyCode::Char('N'),
            ExplorerCommand::Rename => KeyCode::Char('r'),
            ExplorerCommand::Dismiss => KeyCode::Esc,
        };
        self.handle_key(KeyEvent::new(code, KeyModifiers::NONE))
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> ExplorerOutcome {
        // 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 — which double-toggles
        // marks, double-navigates, etc.
        if key.kind != crossterm::event::KeyEventKind::Press {
            return ExplorerOutcome::Pending;
        }

        // ── Rename-mode interception ──────────────────────────────────────────
        // When rename mode is active every printable character feeds the new
        // name.  Enter confirms the rename; Esc cancels.
        handle_input_mode!(self, key, rename_active, rename_input, {
            let new_name = self.rename_input.trim().to_string();
            self.rename_active = false;
            self.rename_input.clear();
            if new_name.is_empty() {
                return ExplorerOutcome::Pending;
            }
            // Grab the source path before we reload.
            let src = match self.entries.get(self.cursor) {
                Some(e) => e.path.clone(),
                None => return ExplorerOutcome::Pending,
            };
            let dst = self.current_dir.join(&new_name);
            match self.filesystem.rename(&src, &dst) {
                Ok(()) => {
                    self.reload();
                    // Move cursor to the renamed entry.
                    if let Some(idx) = self.entries.iter().position(|e| e.path == dst) {
                        self.cursor = idx;
                    }
                    return ExplorerOutcome::RenameCompleted(dst);
                }
                Err(e) => {
                    self.status = format!("rename failed: {e}");
                    return ExplorerOutcome::Pending;
                }
            }
        });

        // ── Touch-mode interception ───────────────────────────────────────────
        // When touch mode is active every printable character feeds the new
        // file name.  Enter confirms creation; Esc cancels.
        handle_input_mode!(self, key, touch_active, touch_input, {
            let name = self.touch_input.trim().to_string();
            self.touch_active = false;
            self.touch_input.clear();
            if name.is_empty() {
                return ExplorerOutcome::Pending;
            }
            let new_file = self.current_dir.join(&name);
            // Create parent dirs if the name contains path separators,
            // then create (or truncate-to-zero) the file itself.
            let create_result = self.filesystem.create_file(&new_file);
            match create_result {
                Ok(()) => {
                    self.reload();
                    // Move cursor to the newly created file.
                    if let Some(idx) = self.entries.iter().position(|e| e.path == new_file) {
                        self.cursor = idx;
                    }
                    return ExplorerOutcome::TouchCreated(new_file);
                }
                Err(e) => {
                    self.status = format!("touch failed: {e}");
                    return ExplorerOutcome::Pending;
                }
            }
        });

        // ── Mkdir-mode interception ───────────────────────────────────────────
        // When mkdir mode is active every printable character feeds the new
        // folder name.  Enter confirms creation; Esc cancels.
        handle_input_mode!(self, key, mkdir_active, mkdir_input, {
            let name = self.mkdir_input.trim().to_string();
            self.mkdir_active = false;
            self.mkdir_input.clear();
            if name.is_empty() {
                return ExplorerOutcome::Pending;
            }
            let new_dir = self.current_dir.join(&name);
            match self.filesystem.create_dir_all(&new_dir) {
                Ok(()) => {
                    self.reload();
                    // Move cursor to the newly created directory.
                    if let Some(idx) = self.entries.iter().position(|e| e.path == new_dir) {
                        self.cursor = idx;
                    }
                    return ExplorerOutcome::MkdirCreated(new_dir);
                }
                Err(e) => {
                    self.status = format!("mkdir failed: {e}");
                    return ExplorerOutcome::Pending;
                }
            }
        });

        // ── Search-mode interception ──────────────────────────────────────────
        // When search is active, printable characters feed the query rather than
        // triggering navigation shortcuts.  Navigation keys (arrows, Enter, etc.)
        // fall through to the normal handler below so the list remains usable
        // while filtering.
        if self.search_active {
            match key.code {
                KeyCode::Char(c) if key.modifiers.is_empty() => {
                    self.search_query.push(c);
                    self.cursor = 0;
                    self.scroll_offset = 0;
                    self.reload();
                    return ExplorerOutcome::Pending;
                }
                KeyCode::Backspace => {
                    if self.search_query.is_empty() {
                        // Nothing left to erase — deactivate search.
                        self.search_active = false;
                    } else {
                        self.search_query.pop();
                        self.cursor = 0;
                        self.scroll_offset = 0;
                        self.reload();
                    }
                    return ExplorerOutcome::Pending;
                }
                KeyCode::Esc => {
                    // First Esc cancels search; second Esc (when already
                    // inactive) dismisses the explorer entirely.
                    self.search_active = false;
                    self.search_query.clear();
                    self.cursor = 0;
                    self.scroll_offset = 0;
                    self.reload();
                    return ExplorerOutcome::Pending;
                }
                _ => {} // navigation keys fall through
            }
        }

        match key.code {
            // ── Dismiss ──────────────────────────────────────────────────────
            KeyCode::Esc => ExplorerOutcome::Dismissed,

            // ── Vim-style quit ───────────────────────────────────────────────
            KeyCode::Char('q') if key.modifiers.is_empty() => ExplorerOutcome::Dismissed,

            // ── Move up ──────────────────────────────────────────────────────
            KeyCode::Up | KeyCode::Char('k') => {
                self.move_up();
                ExplorerOutcome::Pending
            }

            // ── Move down ────────────────────────────────────────────────────
            KeyCode::Down | KeyCode::Char('j') => {
                self.move_down();
                ExplorerOutcome::Pending
            }

            // ── Page up ──────────────────────────────────────────────────────
            KeyCode::PageUp => {
                for _ in 0..self.page_size {
                    self.move_up();
                }
                ExplorerOutcome::Pending
            }

            // ── Page down ────────────────────────────────────────────────────
            KeyCode::PageDown => {
                for _ in 0..self.page_size {
                    self.move_down();
                }
                ExplorerOutcome::Pending
            }

            // ── Jump to top ──────────────────────────────────────────────────
            KeyCode::Home | KeyCode::Char('g') => {
                self.cursor = 0;
                self.scroll_offset = 0;
                ExplorerOutcome::Pending
            }

            // ── Jump to bottom ───────────────────────────────────────────────
            KeyCode::End | KeyCode::Char('G') => {
                if !self.entries.is_empty() {
                    self.cursor = self.entries.len() - 1;
                }
                ExplorerOutcome::Pending
            }

            // ── Ascend (go to parent) ─────────────────────────────────────────
            // Left arrow / Backspace / h all ascend to the parent directory.
            KeyCode::Left | KeyCode::Backspace | KeyCode::Char('h') => {
                self.ascend();
                ExplorerOutcome::Pending
            }

            // ── Navigate right (pure navigation, never exits) ─────────────────
            // Right arrow descends into a directory; on a file it just moves
            // the cursor down so the user can keep browsing.
            KeyCode::Right => self.navigate(),

            // ── Confirm / descend ─────────────────────────────────────────────
            // Enter / l descend into a directory or confirm (select) a file,
            // which signals the caller to exit the TUI.
            KeyCode::Enter | KeyCode::Char('l') => self.confirm(),

            // ── Toggle hidden files ─────────────────────────────────
            KeyCode::Char('.') => {
                self.show_hidden = !self.show_hidden;
                let was = self.cursor;
                self.reload();
                self.cursor = was.min(self.entries.len().saturating_sub(1));
                ExplorerOutcome::Pending
            }

            // ── Toggle file/folder size display ───────────────────────
            KeyCode::Char('z') if key.modifiers.is_empty() => {
                self.show_sizes = !self.show_sizes;
                ExplorerOutcome::Pending
            }

            // ── Activate incremental search ───────────────────────────────────
            KeyCode::Char('/') if key.modifiers.is_empty() => {
                self.search_active = true;
                ExplorerOutcome::Pending
            }

            // ── Cycle sort mode ───────────────────────────────────────────────
            KeyCode::Char('s') if key.modifiers.is_empty() => {
                self.sort_mode = self.sort_mode.next();
                let was = self.cursor;
                self.reload();
                self.cursor = was.min(self.entries.len().saturating_sub(1));
                ExplorerOutcome::Pending
            }

            // ── Toggle space-mark on current entry ────────────────────────────
            KeyCode::Char(' ') => {
                self.toggle_mark();
                ExplorerOutcome::Pending
            }

            // ── Activate mkdir mode ───────────────────────────────────────────
            KeyCode::Char('n') if key.modifiers.is_empty() => {
                self.mkdir_active = true;
                self.mkdir_input.clear();
                ExplorerOutcome::Pending
            }

            // ── Activate touch (new file) mode ────────────────────────────────
            // Shift+N — complement to `n` (mkdir).
            KeyCode::Char('N') if key.modifiers.is_empty() => {
                self.touch_active = true;
                self.touch_input.clear();
                ExplorerOutcome::Pending
            }

            // ── Activate rename mode ──────────────────────────────────────────
            // `r` — pre-fills the input with the current entry's name so the
            // user can edit it rather than type from scratch.
            KeyCode::Char('r') if key.modifiers.is_empty() => {
                if let Some(entry) = self.entries.get(self.cursor) {
                    self.rename_input = entry.name.clone();
                    self.rename_active = true;
                }
                ExplorerOutcome::Pending
            }

            _ => ExplorerOutcome::Unhandled,
        }
    }

    // ── Internal navigation helpers ───────────────────────────────────────────

    pub(crate) fn move_up(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
        }
        // If entries shrank (e.g. external deletion) clamp to valid range.
        self.clamp_cursor();
    }

    pub(crate) fn move_down(&mut self) {
        let last = self.entries.len().saturating_sub(1);
        if !self.entries.is_empty() && self.cursor < last {
            self.cursor += 1;
        }
        self.clamp_cursor();
    }

    /// Clamp `cursor` and `scroll_offset` so they never exceed the current
    /// entries length.  Safe to call at any time — a no-op when everything is
    /// already in range.
    pub(crate) fn clamp_cursor(&mut self) {
        let max = self.entries.len().saturating_sub(1);
        if self.cursor > max {
            self.cursor = max;
        }
        if self.scroll_offset > self.cursor {
            self.scroll_offset = self.cursor;
        }
    }

    pub(crate) fn ascend(&mut self) {
        if let Some(parent) = self.current_dir.parent().map(|p| p.to_path_buf()) {
            let prev = self.current_dir.clone();
            self.current_dir = parent;
            self.cursor = 0;
            self.scroll_offset = 0;
            // Clear search and marks when navigating to a different directory.
            self.search_active = false;
            self.search_query.clear();
            self.marked.clear();
            self.reload();
            // Try to land the cursor on the directory we just came from.
            if let Some(idx) = self.entries.iter().position(|e| e.path == prev) {
                self.cursor = idx;
            }
            // Always clamp in case the parent is empty or shorter than expected.
            self.clamp_cursor();
        } else {
            // Already at root — stay put, do nothing.
            self.status = "Already at the filesystem root.".to_string();
        }
    }

    /// Navigate into the highlighted entry without ever exiting the TUI.
    ///
    /// - **Directory** → descend (same as `confirm` on a dir).
    /// - **File** → move the cursor down one step so the user can keep
    ///   browsing without accidentally triggering a selection/exit.
    fn navigate(&mut self) -> ExplorerOutcome {
        let Some(entry) = self.entries.get(self.cursor) else {
            return ExplorerOutcome::Pending;
        };

        if entry.is_dir {
            let path = entry.path.clone();
            self.search_active = false;
            self.search_query.clear();
            self.marked.clear();
            self.navigate_to(path);
        } else {
            self.move_down();
        }
        ExplorerOutcome::Pending
    }

    fn confirm(&mut self) -> ExplorerOutcome {
        let Some(entry) = self.entries.get(self.cursor) else {
            return ExplorerOutcome::Pending;
        };

        if entry.is_dir {
            if matches!(
                self.selection_mode,
                SelectionMode::Directories | SelectionMode::Any
            ) {
                return ExplorerOutcome::Selected(entry.path.clone());
            }
            let path = entry.path.clone();
            // Clear search and marks when descending into a subdirectory.
            self.search_active = false;
            self.search_query.clear();
            self.marked.clear();
            self.navigate_to(path);
            ExplorerOutcome::Pending
        } else if self.selection_mode == SelectionMode::Directories {
            self.status = "Only directories can be selected.".into();
            ExplorerOutcome::Pending
        } else {
            // All visible files already passed the extension filter in load_entries,
            // so every non-directory entry is unconditionally selectable here.
            ExplorerOutcome::Selected(entry.path.clone())
        }
    }
}