From cd8a8ebfd08b8c3a9c89c9febc99dee0dab7ea8d Mon Sep 17 00:00:00 2001 From: CharOfString Date: Fri, 16 Oct 2026 10:58:51 -0500 Subject: [PATCH 1/5] feat: Add file tree sidebar and file tabs - C-c c t shows a Treemacs style file tree on the left. It starts at the project of the open file and selects that file. - Each open file has its own tab in a row inside the editor box. C-x Right and C-x Left switch tabs, C-x k closes one and asks first when it has unsaved changes. - C-x o moves focus through the tree, the editor and the terminal. - Move the App tests into src/app/tests.rs to keep app.rs short. Co-Authored-By: Claude Opus 5.5 --- doc/shortcuts/shortcuts.md | 29 ++- doc/shortcuts/shortcuts.zh.md | 29 ++- src/app.rs | 305 +----------------------------- src/app/tests.rs | 312 +++++++++++++++++++++++++++++++ src/buffers/completion/keys.rs | 2 + src/buffers/dialog.rs | 60 ++++-- src/buffers/menu/mod.rs | 25 ++- src/buffers/mod.rs | 2 + src/buffers/paste.rs | 7 +- src/buffers/render.rs | 35 +++- src/buffers/sidebar.rs | 327 +++++++++++++++++++++++++++++++++ src/buffers/sidebar/tests.rs | 233 +++++++++++++++++++++++ src/buffers/tabs.rs | 182 ++++++++++++++++++ src/buffers/tabs/tests.rs | 125 +++++++++++++ src/buffers/terminal.rs | 10 +- src/lsp/mod.rs | 1 + 16 files changed, 1337 insertions(+), 347 deletions(-) create mode 100644 src/app/tests.rs create mode 100644 src/buffers/sidebar.rs create mode 100644 src/buffers/sidebar/tests.rs create mode 100644 src/buffers/tabs.rs create mode 100644 src/buffers/tabs/tests.rs diff --git a/doc/shortcuts/shortcuts.md b/doc/shortcuts/shortcuts.md index 877ce0e..4103860 100644 --- a/doc/shortcuts/shortcuts.md +++ b/doc/shortcuts/shortcuts.md @@ -17,7 +17,7 @@ ## Terminal * `Ctrl + C` `T` `T`: open or hide the terminal. Hiding it keeps the shell running. -* `Ctrl + X` `O`: switch focus between the editor and the visible terminal. +* `Ctrl + X` `O`: switch focus between the visible panes: the file tree, the editor and the terminal. * `Ctrl + C` `T` `C`: run Clang-tidy. * `Alt + V` / `Ctrl + V`: scroll terminal history up / down one page. `Shift + PageUp` / `Shift + PageDown` also work. Up to 1000 history rows are kept. @@ -30,3 +30,30 @@ The terminal opens below the editor when the workspace has at least 28 rows; otherwise it opens on the right. It starts in the current file's directory, or the editor's working directory for an unnamed file. After the shell exits, hide and reopen the terminal to start a new session. + +## File tree + +* `Ctrl + C` `C` `T`: show or hide the file tree on the left, like Emacs Treemacs. + It is also in the WINDOW menu. Showing the tree gives it focus. +* `N` / `P`: next / previous row. `Down` / `Up` and `Ctrl + N` / `Ctrl + P` also work. +* `Tab`: open or close the selected folder. +* `Enter`: open the selected file in a new tab (or go to its tab when it is open already), + or open or close the selected folder. +* `U`: go to the parent folder. +* `G`: read the folders again. +* `Q`: hide the tree. + +The tree starts at the project of the current file: the nearest folder above it that holds +`.git`, `Cargo.toml`, `CMakeLists.txt`, `compile_commands.json` or `compile_flags.txt` +(otherwise the file's own folder). For an unnamed file, it starts at the editor's working directory. +It opens the folders above the current file and selects it. The `.git` folder is not shown. + +## Tabs + +* `Ctrl + X` `Right` / `Ctrl + X` `Left`: go to the next / previous tab. At the last tab, the next one is the first. +* `Ctrl + X` `K`: close the tab. If it has unsaved changes, a dialog asks first: + `Y` / `Enter` closes it without saving, `N` / `Esc` keeps it open. + +The tab row is the first line of the editor. The active tab is highlighted, and `●` marks a tab +with unsaved changes. A file from the file tree opens in a new tab after the active one; an empty +unnamed tab is reused for it. Closing the last tab leaves an empty unnamed tab. diff --git a/doc/shortcuts/shortcuts.zh.md b/doc/shortcuts/shortcuts.zh.md index e397bd0..c830305 100644 --- a/doc/shortcuts/shortcuts.zh.md +++ b/doc/shortcuts/shortcuts.zh.md @@ -16,7 +16,7 @@ ## 终端 * `Ctrl + C` `T` `T`:打开或隐藏终端。隐藏后 Shell 继续运行。 -* `Ctrl + X` `O`:在编辑器和已显示的终端之间切换焦点。 +* `Ctrl + X` `O`:在已显示的面板之间切换焦点:文件树、编辑器和终端。 * `Ctrl + C` `T` `C`:运行 Clang-tidy。 * `Alt + V` / `Ctrl + V`:向上 / 向下翻阅终端历史输出。 也支持 `Shift + PageUp` / `Shift + PageDown`,最多保留 1000 行历史。 @@ -28,3 +28,30 @@ 工作区高度不少于 28 行时,终端显示在编辑器下方;否则显示在右侧。 Shell 在当前文件的目录启动;未命名文件则使用编辑器的工作目录。 Shell 退出后,隐藏并重新打开终端即可启动新会话。 + +## 文件树 + +* `Ctrl + C` `C` `T`:在左侧显示或隐藏文件树,类似 Emacs 的 Treemacs。 + 也可以从 WINDOW 菜单打开。显示文件树时焦点会移到文件树上。 +* `N` / `P`:下一行 / 上一行。也支持 `Down` / `Up` 和 `Ctrl + N` / `Ctrl + P`。 +* `Tab`:展开或折叠选中的目录。 +* `Enter`:在新标签页中打开选中的文件(已打开的文件会切换到它的标签页), + 或展开 / 折叠选中的目录。 +* `U`:跳到上级目录。 +* `G`:重新读取目录。 +* `Q`:隐藏文件树。 + +文件树从当前文件所在的项目开始:即向上找到的第一个含有 `.git`、`Cargo.toml`、`CMakeLists.txt`、 +`compile_commands.json` 或 `compile_flags.txt` 的目录(找不到时使用文件所在的目录)。 +未命名文件则从编辑器的工作目录开始。 +打开时会展开当前文件上层的目录并选中它。`.git` 目录不会显示。 + +## 标签页 + +* `Ctrl + X` `Right` / `Ctrl + X` `Left`:切换到下一个 / 上一个标签页。在最后一个标签页时,下一个是第一个。 +* `Ctrl + X` `K`:关闭标签页。有未保存的修改时会先弹出对话框询问: + `Y` / `Enter` 不保存直接关闭,`N` / `Esc` 保留标签页。 + +标签栏是编辑器的第一行。当前标签页会高亮显示,`●` 表示该标签页有未保存的修改。 +从文件树打开的文件会在当前标签页之后新开一个标签页;如果当前是空的未命名标签页,则直接用它打开。 +关闭最后一个标签页后,会留下一个空的未命名标签页。 diff --git a/src/app.rs b/src/app.rs index 3e14c04..a42db55 100644 --- a/src/app.rs +++ b/src/app.rs @@ -45,6 +45,8 @@ pub(crate) struct App { pub(crate) search: crate::buffers::search::Search, pub(crate) goto_line: crate::buffers::goto_line::GotoLine, pub(crate) paste_scroll: Option, + pub(crate) sidebar: crate::buffers::sidebar::Sidebar, + pub(crate) tabs: crate::buffers::tabs::Tabs, // Draw icons from a Nerd Font (WINDOW menu). pub(crate) nerd_font: bool, } @@ -97,7 +99,7 @@ impl App { } pub(crate) fn handle_key(&mut self, key: KeyEvent) { - if self.handle_terminal_key(key) { + if self.handle_sidebar_key(key) || self.handle_terminal_key(key) { return; } // Print key in buffer command section in bottom tool bar. @@ -110,7 +112,7 @@ impl App { self.buffer_command = crate::utils::keys::shortcut_label(key, !prefix.is_empty()) .map_or_else(String::new, |chord| format!("{prefix}{chord}")); - if self.handle_cpp_check_key(key) { + if self.handle_cpp_check_key(key) || self.handle_tab_key(key) { return; } @@ -298,301 +300,4 @@ impl App { } #[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - struct TestFile(PathBuf); - impl TestFile { - fn new() -> Self { - static NEXT: AtomicUsize = AtomicUsize::new(0); - let path = std::env::temp_dir().join(format!( - "ptre-confirm-test-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); - std::fs::write(&path, "original").unwrap(); - Self(path) - } - } - impl Drop for TestFile { - fn drop(&mut self) { - let _ = std::fs::remove_file(&self.0); - } - } - - fn save_keys(app: &mut App) { - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); - } - - fn type_text(app: &mut App, text: &str) { - app.editor_area = Rect::new(1, 1, 78, 22); - for c in text.chars() { - let code = if c == '\n' { - KeyCode::Enter - } else { - KeyCode::Char(c) - }; - app.handle_key(KeyEvent::new(code, KeyModifiers::NONE)); - } - } - - #[test] - fn cursor_editing_and_undo_use_editor_buffer() { - let mut app = App::default(); - type_text(&mut app, "ac"); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); - type_text(&mut app, "b"); - assert_eq!(app.buffer.editor.get_content(), "abc"); - app.handle_key(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::CONTROL)); - assert_eq!(app.buffer.editor.get_content(), "ac"); - } - - #[test] - fn emacs_undo_and_redo_shortcuts() { - let mut app = App::default(); - type_text(&mut app, "a"); - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE)); - assert_eq!(app.buffer.editor.get_content(), ""); - app.handle_key(KeyEvent::new( - KeyCode::Char('_'), - KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT, - )); - assert_eq!(app.buffer.editor.get_content(), "a"); - } - - #[test] - fn emacs_region_shortcuts_replace_default_clipboard_bindings() { - let mut app = App::default(); - type_text(&mut app, "abc"); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); - - app.handle_key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::ALT)); - assert_eq!(app.kill_ring.as_deref(), Some("bc")); - assert_eq!(app.buffer.editor.get_content(), "abc"); - - app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::CONTROL)); - assert_eq!(app.buffer.editor.get_content(), "abc"); - - app.buffer.editor.clear_selection(); - app.buffer.editor.set_cursor(3); - app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)); - assert_eq!(app.buffer.editor.get_content(), "abcbc"); - - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); - app.handle_key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL)); - assert_eq!(app.buffer.editor.get_content(), "abc"); - app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)); - assert_eq!(app.buffer.editor.get_content(), "abcbc"); - } - - #[test] - fn save_prompt_does_not_edit_content() { - let mut app = App::default(); - type_text(&mut app, "hello"); - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); - type_text(&mut app, "cancelled.rs"); - app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(app.save_path_input.is_none()); - assert_eq!(app.buffer.editor.get_content(), "hello"); - } - - #[test] - fn obsolete_file_requires_confirmation_and_cancel_keeps_disk_intact() { - let file = TestFile::new(); - let mut app = App::default(); - app.buffer.open(file.0.clone()).unwrap(); - app.buffer.editor.set_content("my edits"); - std::fs::write(&file.0, "external edits").unwrap(); - - // No timer tick is needed: saving checks the disk immediately. - save_keys(&mut app); - assert!(app.overwrite_confirm); - assert_eq!(std::fs::read_to_string(&file.0).unwrap(), "external edits"); - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)); - assert_eq!(app.buffer.editor.get_content(), "my edits"); - assert!(app.overwrite_confirm); - - app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(!app.overwrite_confirm); - assert!(app.buffer.is_dirty()); - assert!(app.buffer.obsolete); - assert_eq!(std::fs::read_to_string(&file.0).unwrap(), "external edits"); - } - - #[test] - fn confirming_overwrites_obsolete_file_and_resets_indicators() { - let file = TestFile::new(); - let mut app = App::default(); - app.buffer.open(file.0.clone()).unwrap(); - app.buffer.editor.set_content("my edits"); - std::fs::write(&file.0, "external edits").unwrap(); - save_keys(&mut app); - assert!(app.overwrite_confirm); - app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); - assert!(!app.overwrite_confirm); - assert!(!app.buffer.is_dirty()); - assert!(!app.buffer.obsolete); - assert_eq!(std::fs::read_to_string(&file.0).unwrap(), "my edits"); - } - - #[test] - fn enter_confirms_overwrite() { - let file = TestFile::new(); - let mut app = App::default(); - app.buffer.open(file.0.clone()).unwrap(); - app.buffer.editor.set_content("my edits"); - std::fs::write(&file.0, "external edits").unwrap(); - save_keys(&mut app); - - app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - assert!(!app.overwrite_confirm); - assert_eq!(std::fs::read_to_string(&file.0).unwrap(), "my edits"); - } - - #[test] - fn confirmation_dialog_is_rendered_over_editor() { - use ratatui::{Terminal, backend::TestBackend}; - let mut app = App { - overwrite_confirm: true, - ..App::default() - }; - let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); - terminal.draw(|frame| app.draw(frame)).unwrap(); - let screen = terminal.backend().buffer(); - let text: String = (0..24) - .flat_map(|y| (0..80).map(move |x| screen[(x, y)].symbol().to_owned())) - .collect(); - assert!(text.contains("Confirm overwrite")); - assert!(text.contains("File has been changed on disk. Overwrite it?")); - assert!(text.contains("Y/ENTER")); - } - - #[test] - fn renders_editor_and_updated_shortcuts() { - use ratatui::{Terminal, backend::TestBackend}; - let mut app = App::default(); - type_text(&mut app, "fn main() {}"); - app.buffer.obsolete = true; - let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); - terminal.draw(|frame| app.draw(frame)).unwrap(); - assert_eq!(app.editor_area, Rect::new(1, 3, 98, 16)); - let screen = terminal.backend().buffer(); - let title: String = (0..100).map(|x| screen[(x, 2)].symbol()).collect(); - assert!(title.starts_with("╭─ [No Name] · DIRTY BUFFER")); - assert!(title.contains("· DIRTY BUFFER")); - assert!(title.contains("· OBSOLETE FILE")); - assert_eq!(screen[(0, 2)].symbol(), "╭"); - assert_eq!(screen[(99, 2)].symbol(), "╮"); - assert_eq!(screen[(0, 21)].symbol(), "╰"); - assert_eq!(screen[(99, 21)].symbol(), "╯"); - assert_eq!(screen[(0, 2)].fg, ratatui::style::Color::White); - assert_eq!(screen[(0, 10)].fg, ratatui::style::Color::White); - assert_eq!(screen[(99, 10)].fg, ratatui::style::Color::White); - let status: String = (0..100).map(|x| screen[(x, 23)].symbol()).collect(); - assert!(status.contains("F10: menu")); - assert!(!status.contains("Buffer command")); - for x in 0..100 { - assert_eq!(screen[(x, 22)].symbol(), "─"); - assert_eq!(screen[(x, 21)].fg, ratatui::style::Color::White); - assert_eq!(screen[(x, 22)].fg, ratatui::style::Color::Green); - assert_eq!(screen[(x, 22)].bg, ratatui::style::Color::Reset); - assert_eq!(screen[(x, 23)].bg, ratatui::style::Color::Reset); - assert_eq!(screen[(x, 23)].fg, ratatui::style::Color::Green); - } - assert!( - app.buffer - .editor - .get_visible_cursor(&app.editor_area) - .is_some() - ); - } - - #[test] - fn echoes_emacs_shortcuts_after_menu_hint() { - use ratatui::{Terminal, backend::TestBackend}; - let mut app = App::default(); - let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); - let status = |app: &mut App, terminal: &mut Terminal| { - terminal.draw(|frame| app.draw(frame)).unwrap(); - (0..100) - .map(|x| terminal.backend().buffer()[(x, 23)].symbol().to_owned()) - .collect::() - }; - assert!(status(&mut app, &mut terminal).contains("F10: menu")); - assert!(!status(&mut app, &mut terminal).contains("Buffer command:")); - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); - assert!(status(&mut app, &mut terminal).contains("Buffer command: C-x")); - app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE)); - assert!(status(&mut app, &mut terminal).contains("Buffer command: C-x u")); - app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); - assert!(!status(&mut app, &mut terminal).contains("Buffer command: C-x")); - app.handle_key(KeyEvent::new( - KeyCode::Char('_'), - KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT, - )); - assert!(status(&mut app, &mut terminal).contains("C-M-_")); - app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); - assert!(status(&mut app, &mut terminal).contains("F10")); - } - - #[test] - fn editor_title_shows_only_file_name_and_indicators() { - use ratatui::{Terminal, backend::TestBackend}; - let mut app = App::default(); - app.buffer.open(PathBuf::from("Cargo.toml")).unwrap(); - let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); - terminal.draw(|frame| app.draw(frame)).unwrap(); - let screen = terminal.backend().buffer(); - let title: String = (0..80).map(|x| screen[(x, 2)].symbol()).collect(); - assert!(title.starts_with("╭─ Cargo.toml ─")); - assert!(!title.contains("TOML")); - assert!(!title.contains("PTRE UNSTABLE")); - } - - #[test] - fn exit_requires_ctrl_x_then_ctrl_c() { - let mut app = App::default(); - app.handle_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); - assert!(!app.exit_flag); - - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::NONE)); - assert!(!app.exit_flag); - - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); - assert!(app.exit_flag); - } - - #[test] - fn unnamed_buffer_prompts_then_remembers_path() { - let mut app = App::default(); - type_text(&mut app, "hello\n"); - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); - assert!(app.save_path_input.is_some()); - - let path = std::env::temp_dir().join(format!("ptre-save-test-{}", std::process::id())); - app.save_path_input = Some(path.to_string_lossy().into_owned()); - app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - assert_eq!(app.buffer.path.as_ref(), Some(&path)); - assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello\n"); - - type_text(&mut app, "world"); - app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); - app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); - assert!(app.save_path_input.is_none()); - assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello\nworld"); - std::fs::remove_file(path).unwrap(); - } -} +mod tests; diff --git a/src/app/tests.rs b/src/app/tests.rs new file mode 100644 index 0000000..7c427e8 --- /dev/null +++ b/src/app/tests.rs @@ -0,0 +1,312 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; + +struct TestFile(PathBuf); +impl TestFile { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let path = std::env::temp_dir().join(format!( + "ptre-confirm-test-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::write(&path, "original").unwrap(); + Self(path) + } +} +impl Drop for TestFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +fn save_keys(app: &mut App) { + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); +} + +fn type_text(app: &mut App, text: &str) { + app.editor_area = Rect::new(1, 1, 78, 22); + for c in text.chars() { + let code = if c == '\n' { + KeyCode::Enter + } else { + KeyCode::Char(c) + }; + app.handle_key(KeyEvent::new(code, KeyModifiers::NONE)); + } +} + +#[test] +fn cursor_editing_and_undo_use_editor_buffer() { + let mut app = App::default(); + type_text(&mut app, "ac"); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + type_text(&mut app, "b"); + assert_eq!(app.buffer.editor.get_content(), "abc"); + app.handle_key(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::CONTROL)); + assert_eq!(app.buffer.editor.get_content(), "ac"); +} + +#[test] +fn emacs_undo_and_redo_shortcuts() { + let mut app = App::default(); + type_text(&mut app, "a"); + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE)); + assert_eq!(app.buffer.editor.get_content(), ""); + app.handle_key(KeyEvent::new( + KeyCode::Char('_'), + KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT, + )); + assert_eq!(app.buffer.editor.get_content(), "a"); +} + +#[test] +fn emacs_region_shortcuts_replace_default_clipboard_bindings() { + let mut app = App::default(); + type_text(&mut app, "abc"); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); + + app.handle_key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::ALT)); + assert_eq!(app.kill_ring.as_deref(), Some("bc")); + assert_eq!(app.buffer.editor.get_content(), "abc"); + + app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::CONTROL)); + assert_eq!(app.buffer.editor.get_content(), "abc"); + + app.buffer.editor.clear_selection(); + app.buffer.editor.set_cursor(3); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)); + assert_eq!(app.buffer.editor.get_content(), "abcbc"); + + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::SHIFT)); + app.handle_key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL)); + assert_eq!(app.buffer.editor.get_content(), "abc"); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL)); + assert_eq!(app.buffer.editor.get_content(), "abcbc"); +} + +#[test] +fn save_prompt_does_not_edit_content() { + let mut app = App::default(); + type_text(&mut app, "hello"); + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); + type_text(&mut app, "cancelled.rs"); + app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert!(app.save_path_input.is_none()); + assert_eq!(app.buffer.editor.get_content(), "hello"); +} + +#[test] +fn obsolete_file_requires_confirmation_and_cancel_keeps_disk_intact() { + let file = TestFile::new(); + let mut app = App::default(); + app.buffer.open(file.0.clone()).unwrap(); + app.buffer.editor.set_content("my edits"); + std::fs::write(&file.0, "external edits").unwrap(); + + // No timer tick is needed: saving checks the disk immediately. + save_keys(&mut app); + assert!(app.overwrite_confirm); + assert_eq!(std::fs::read_to_string(&file.0).unwrap(), "external edits"); + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)); + assert_eq!(app.buffer.editor.get_content(), "my edits"); + assert!(app.overwrite_confirm); + + app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert!(!app.overwrite_confirm); + assert!(app.buffer.is_dirty()); + assert!(app.buffer.obsolete); + assert_eq!(std::fs::read_to_string(&file.0).unwrap(), "external edits"); +} + +#[test] +fn confirming_overwrites_obsolete_file_and_resets_indicators() { + let file = TestFile::new(); + let mut app = App::default(); + app.buffer.open(file.0.clone()).unwrap(); + app.buffer.editor.set_content("my edits"); + std::fs::write(&file.0, "external edits").unwrap(); + save_keys(&mut app); + assert!(app.overwrite_confirm); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + assert!(!app.overwrite_confirm); + assert!(!app.buffer.is_dirty()); + assert!(!app.buffer.obsolete); + assert_eq!(std::fs::read_to_string(&file.0).unwrap(), "my edits"); +} + +#[test] +fn enter_confirms_overwrite() { + let file = TestFile::new(); + let mut app = App::default(); + app.buffer.open(file.0.clone()).unwrap(); + app.buffer.editor.set_content("my edits"); + std::fs::write(&file.0, "external edits").unwrap(); + save_keys(&mut app); + + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert!(!app.overwrite_confirm); + assert_eq!(std::fs::read_to_string(&file.0).unwrap(), "my edits"); +} + +#[test] +fn confirmation_dialog_is_rendered_over_editor() { + use ratatui::{Terminal, backend::TestBackend}; + let mut app = App { + overwrite_confirm: true, + ..App::default() + }; + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + let text: String = (0..24) + .flat_map(|y| (0..80).map(move |x| screen[(x, y)].symbol().to_owned())) + .collect(); + assert!(text.contains("Confirm overwrite")); + assert!(text.contains("File has been changed on disk. Overwrite it?")); + assert!(text.contains("Y/ENTER")); +} + +#[test] +fn renders_editor_and_updated_shortcuts() { + use ratatui::{Terminal, backend::TestBackend}; + let mut app = App::default(); + type_text(&mut app, "fn main() {}"); + app.buffer.obsolete = true; + let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + assert_eq!(app.editor_area, Rect::new(1, 4, 98, 15)); + let screen = terminal.backend().buffer(); + let tabs: String = (0..100).map(|x| screen[(x, 3)].symbol()).collect(); + assert!(tabs.starts_with("│❃ [No Name] ●")); + let title: String = (0..100).map(|x| screen[(x, 2)].symbol()).collect(); + assert!(title.starts_with("╭─ [No Name] · DIRTY BUFFER")); + assert!(title.contains("· DIRTY BUFFER")); + assert!(title.contains("· OBSOLETE FILE")); + assert_eq!(screen[(0, 2)].symbol(), "╭"); + assert_eq!(screen[(99, 2)].symbol(), "╮"); + assert_eq!(screen[(0, 21)].symbol(), "╰"); + assert_eq!(screen[(99, 21)].symbol(), "╯"); + assert_eq!(screen[(0, 2)].fg, ratatui::style::Color::White); + assert_eq!(screen[(0, 10)].fg, ratatui::style::Color::White); + assert_eq!(screen[(99, 10)].fg, ratatui::style::Color::White); + let status: String = (0..100).map(|x| screen[(x, 23)].symbol()).collect(); + assert!(status.contains("F10: menu")); + assert!(!status.contains("Buffer command")); + for x in 0..100 { + assert_eq!(screen[(x, 22)].symbol(), "─"); + assert_eq!(screen[(x, 21)].fg, ratatui::style::Color::White); + assert_eq!(screen[(x, 22)].fg, ratatui::style::Color::Green); + assert_eq!(screen[(x, 22)].bg, ratatui::style::Color::Reset); + assert_eq!(screen[(x, 23)].bg, ratatui::style::Color::Reset); + assert_eq!(screen[(x, 23)].fg, ratatui::style::Color::Green); + } + assert!( + app.buffer + .editor + .get_visible_cursor(&app.editor_area) + .is_some() + ); +} + +#[test] +fn echoes_emacs_shortcuts_after_menu_hint() { + use ratatui::{Terminal, backend::TestBackend}; + let mut app = App::default(); + let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); + let status = |app: &mut App, terminal: &mut Terminal| { + terminal.draw(|frame| app.draw(frame)).unwrap(); + (0..100) + .map(|x| terminal.backend().buffer()[(x, 23)].symbol().to_owned()) + .collect::() + }; + assert!(status(&mut app, &mut terminal).contains("F10: menu")); + assert!(!status(&mut app, &mut terminal).contains("Buffer command:")); + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + assert!(status(&mut app, &mut terminal).contains("Buffer command: C-x")); + app.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE)); + assert!(status(&mut app, &mut terminal).contains("Buffer command: C-x u")); + app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); + assert!(!status(&mut app, &mut terminal).contains("Buffer command: C-x")); + app.handle_key(KeyEvent::new( + KeyCode::Char('_'), + KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT, + )); + assert!(status(&mut app, &mut terminal).contains("C-M-_")); + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + assert!(status(&mut app, &mut terminal).contains("F10")); +} + +#[test] +fn editor_title_shows_only_file_name_and_indicators() { + use ratatui::{Terminal, backend::TestBackend}; + let mut app = App::default(); + app.buffer.open(PathBuf::from("Cargo.toml")).unwrap(); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + let title: String = (0..80).map(|x| screen[(x, 2)].symbol()).collect(); + assert!(title.starts_with("╭─ Cargo.toml ─")); + assert!(!title.contains("TOML")); + assert!(!title.contains("PTRE UNSTABLE")); +} + +#[test] +fn exit_requires_ctrl_x_then_ctrl_c() { + let mut app = App::default(); + app.handle_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); + assert!(!app.exit_flag); + + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::NONE)); + assert!(!app.exit_flag); + + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); + assert!(app.exit_flag); +} + +#[test] +fn unnamed_buffer_prompts_then_remembers_path() { + let mut app = App::default(); + type_text(&mut app, "hello\n"); + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); + assert!(app.save_path_input.is_some()); + + let path = std::env::temp_dir().join(format!("ptre-save-test-{}", std::process::id())); + app.save_path_input = Some(path.to_string_lossy().into_owned()); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_eq!(app.buffer.path.as_ref(), Some(&path)); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello\n"); + + type_text(&mut app, "world"); + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); + assert!(app.save_path_input.is_none()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello\nworld"); + std::fs::remove_file(path).unwrap(); +} diff --git a/src/buffers/completion/keys.rs b/src/buffers/completion/keys.rs index bd0b83c..6fec753 100644 --- a/src/buffers/completion/keys.rs +++ b/src/buffers/completion/keys.rs @@ -43,6 +43,8 @@ impl App { KeyCode::Char('l') => self.run_cpp_check(Tool::Cpplint), // C-c t is a prefix; handle_terminal_key reads the next key. KeyCode::Char('t') => self.ctrl_c_t_wait_flag = true, + // C-c c is a prefix; handle_sidebar_key reads the next key. + KeyCode::Char('c') => self.sidebar.prefix = true, KeyCode::Char('a') => self.request_fix(), _ => {} } diff --git a/src/buffers/dialog.rs b/src/buffers/dialog.rs index d594adc..2cb55d2 100644 --- a/src/buffers/dialog.rs +++ b/src/buffers/dialog.rs @@ -21,7 +21,35 @@ use ratatui::{ }; use std::path::Path; -pub(super) fn draw_overwrite(frame: &mut Frame, path: Option<&Path>) { +// The words of a yes or no dialog. +pub(super) struct Confirm { + title: &'static str, + question: &'static str, + warning: &'static str, + action: &'static str, + cancel: &'static str, + short: &'static str, +} + +pub(super) const OVERWRITE: Confirm = Confirm { + title: "Confirm overwrite", + question: "File has been changed on disk. Overwrite it?", + warning: "Saving will replace the external changes.", + action: " Overwriting", + cancel: "Cancel keeps both your file and buffer unchanged.", + short: "File changed on disk.", +}; + +pub(super) const CLOSE: Confirm = Confirm { + title: "Confirm close", + question: "Buffer has unsaved changes. Close it?", + warning: "Closing will lose the unsaved changes.", + action: " Close without saving", + cancel: "Cancel keeps the tab open.", + short: "Unsaved changes.", +}; + +pub(super) fn draw_confirm(frame: &mut Frame, path: Option<&Path>, words: &Confirm) { let area = frame.area(); let bg = Color::Rgb(28, 28, 32); let fg = Color::Rgb(225, 222, 216); @@ -64,33 +92,27 @@ pub(super) fn draw_overwrite(frame: &mut Frame, path: Option<&Path>) { ), Span::styled(" Keep editing ", Style::default().fg(fg)), Span::styled(" Y/ENTER ", Style::default().fg(bg).bg(red).bold()), - Span::styled(" Overwriting", Style::default().fg(red).bg(bg).bold()), + Span::styled(words.action, Style::default().fg(red).bg(bg).bold()), ]); let lines = if inner.height >= 9 && inner.width >= 48 { vec![ Line::from(""), - Line::styled("! Confirm overwrite", Style::default().fg(amber).bold()), - Line::from(""), - Line::styled(filename, Style::default().fg(fg).bold()), - Line::styled( - "File has been changed on disk. Overwrite it?", - Style::default().fg(fg), - ), Line::styled( - "Saving will replace the external changes.", - Style::default().fg(muted), + format!("! {}", words.title), + Style::default().fg(amber).bold(), ), Line::from(""), + Line::styled(filename, Style::default().fg(fg).bold()), + Line::styled(words.question, Style::default().fg(fg)), + Line::styled(words.warning, Style::default().fg(muted)), + Line::from(""), buttons, - Line::styled( - "Cancel keeps both your file and buffer unchanged.", - Style::default().fg(muted), - ), + Line::styled(words.cancel, Style::default().fg(muted)), ] } else { vec![ - Line::styled("Confirm overwrite", Style::default().fg(amber).bold()), - Line::from("File changed on disk."), + Line::styled(words.title, Style::default().fg(amber).bold()), + Line::from(words.short), Line::styled("Y/ENTER: confirm", Style::default().fg(red)), Line::from("N / Esc: cancel"), ] @@ -106,7 +128,9 @@ mod tests { #[test] fn overwrite_border_has_rounded_corners() { let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); - terminal.draw(|frame| draw_overwrite(frame, None)).unwrap(); + terminal + .draw(|frame| draw_confirm(frame, None, &OVERWRITE)) + .unwrap(); let buffer = terminal.backend().buffer(); let x = 8; let y = 5; diff --git a/src/buffers/menu/mod.rs b/src/buffers/menu/mod.rs index 9f868d8..1b674af 100644 --- a/src/buffers/menu/mod.rs +++ b/src/buffers/menu/mod.rs @@ -110,14 +110,17 @@ fn items( ("Complete", "M-/"), ("Quick Fix", "C-c a"), ], - (WINDOW_MENU, _) => vec![( - if nerd_font { - "NF Mode: On" - } else { - "NF Mode: Off" - }, - "", - )], + (WINDOW_MENU, _) => vec![ + ( + if nerd_font { + "NF Mode: On" + } else { + "NF Mode: Off" + }, + "", + ), + ("File Tree", "C-c c t"), + ], (CPP_MENU, Some(settings)) => cpp_entries(settings) .into_iter() .map(|(label, shortcut, _)| (label, shortcut)) @@ -330,7 +333,11 @@ impl App { self.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); } } else if active == WINDOW_MENU { - self.toggle_nerd_font(); + if selected == 0 { + self.toggle_nerd_font(); + } else { + self.toggle_sidebar(); + } } else if active == CPP_MENU { // selected indexes the same entries the popup showed. match cpp_entries(&self.cpp_checks.settings)[selected].2 { diff --git a/src/buffers/mod.rs b/src/buffers/mod.rs index e8610d4..721f317 100644 --- a/src/buffers/mod.rs +++ b/src/buffers/mod.rs @@ -24,4 +24,6 @@ pub(crate) mod menu; pub(crate) mod paste; mod render; pub(crate) mod search; +pub(crate) mod sidebar; +pub(crate) mod tabs; pub(crate) mod terminal; diff --git a/src/buffers/paste.rs b/src/buffers/paste.rs index c48091f..9b90696 100644 --- a/src/buffers/paste.rs +++ b/src/buffers/paste.rs @@ -54,6 +54,10 @@ impl App { } return; } + // For the file tree, it doesn't accept pasting. + if self.sidebar.focused { + return; + } // Insert the text as it is, in one edit. Typing it key by key would // indent each new line again and redraw the screen after each key. @@ -87,7 +91,7 @@ impl App { } // True when typed keys do not go straight into the text. - fn keys_go_elsewhere(&self) -> bool { + pub(crate) fn keys_go_elsewhere(&self) -> bool { self.prompt_open() || self.search.is_active() || self.goto_line.is_busy() @@ -95,6 +99,7 @@ impl App { || self.ctrl_x_wait_flag || self.ctrl_c_wait_flag || self.ctrl_c_t_wait_flag + || self.sidebar.prefix } } diff --git a/src/buffers/render.rs b/src/buffers/render.rs index cfe0d63..9c38b81 100644 --- a/src/buffers/render.rs +++ b/src/buffers/render.rs @@ -30,6 +30,14 @@ impl App { .areas(frame.area()); self.menu.draw_bar(frame, menu_area, self.is_c_or_cpp()); + // Drawing the file tree layout on top left... + let editor_area = if self.sidebar.visible { + let [sidebar, rest] = super::sidebar::split(editor_area); + self.sidebar.draw(frame, sidebar, self.nerd_font); + rest + } else { + editor_area + }; let editor_area = if self.terminal.visible { let [editor, terminal] = super::terminal::split(editor_area); if let Err(err) = self.terminal.draw(frame, terminal) { @@ -61,9 +69,15 @@ impl App { .border_type(BorderType::Rounded) .border_style(Style::default().fg(Color::White)) .title(title); - let [content_area, buffer_status_area] = - Layout::vertical([Constraint::Min(0), Constraint::Length(2)]) - .areas(border.inner(editor_area)); + + // Tab bar + let [tab_area, content_area, buffer_status_area] = Layout::vertical([ + Constraint::Length(1), + Constraint::Min(0), + Constraint::Length(2), + ]) + .areas(border.inner(editor_area)); + self.draw_tabs(frame, tab_area); self.editor_area = content_area; // While the paste scroll runs, draw the editor parts from its current line. let offset_y = self.buffer.editor.get_offset_y(); @@ -86,12 +100,8 @@ impl App { self.draw_fix_chooser(frame); self.draw_diagnostic_popup(frame); if !self.terminal.focused - && !self.cpp_check_modal() - && self.save_path_input.is_none() - && !self.search.reads_input() - && !self.goto_line.is_open() - && !self.overwrite_confirm - && self.menu.active.is_none() + && !self.sidebar.focused + && !self.prompt_open() && let Some((x, y)) = self.buffer.editor.get_visible_cursor(&self.editor_area) { frame.set_cursor_position((x, y)); @@ -120,6 +130,8 @@ impl App { // A focused terminal takes all keys, so show its keys instead. let hints = if self.terminal.focused { "C-x o: focus ※ M-v/C-v: scroll" + } else if self.sidebar.focused { + "C-x o: focus ※ RET: open ※ TAB: fold ※ q: hide" } else { "F10: menu ※ C-c t t: terminal" }; @@ -165,8 +177,11 @@ impl App { self.draw_goto_line(frame); self.draw_cpp_check(frame); + let path = self.buffer.path.as_deref(); if self.overwrite_confirm { - super::dialog::draw_overwrite(frame, self.buffer.path.as_deref()); + super::dialog::draw_confirm(frame, path, &super::dialog::OVERWRITE); + } else if self.tabs.close_confirm { + super::dialog::draw_confirm(frame, path, &super::dialog::CLOSE); } } } diff --git a/src/buffers/sidebar.rs b/src/buffers/sidebar.rs new file mode 100644 index 0000000..767c82a --- /dev/null +++ b/src/buffers/sidebar.rs @@ -0,0 +1,327 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + +//! File tree on the left side, in the style of Emacs Treemacs (C-c c t). + +use super::menu::LIGHT_BLUE; +use crate::app::App; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use ratatui::{ + Frame, + layout::{Constraint, Layout, Rect}, + style::{Color, Modifier, Style}, + text::Line, + widgets::{Block, BorderType, List, ListItem, ListState}, +}; +use std::{ + collections::HashSet, + fs, + path::{Path, PathBuf}, +}; + +#[derive(Default)] +pub(crate) struct Sidebar { + pub(crate) visible: bool, + pub(crate) focused: bool, + // Set after C-c c, which waits for its next key. + pub(crate) prefix: bool, + root: PathBuf, + // Folders that show their content. + expanded: HashSet, + rows: Vec, + // The selected row and the scroll position. + list: ListState, + // Set when the open file was selected; the next frame scrolls it to the middle. + reveal: bool, +} + +// The bar under the selected row, as the buttons in the confirm dialog. +const SELECTED: Color = Color::Rgb(60, 60, 68); + +struct Row { + path: PathBuf, + depth: usize, + is_dir: bool, +} + +// The tree takes the left part of the area, at most 30 columns. +pub(crate) fn split(area: Rect) -> [Rect; 2] { + let width = (area.width / 3).min(30); + Layout::horizontal([Constraint::Length(width), Constraint::Min(0)]).areas(area) +} + +fn name(path: &Path) -> String { + path.file_name().map_or_else( + || path.display().to_string(), + |name| name.to_string_lossy().into(), + ) +} + +// Add the content of `dir` to `rows`, and the content of each open folder below it. +fn add_rows(dir: &Path, depth: usize, expanded: &HashSet, rows: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + let mut children: Vec<(bool, PathBuf)> = entries + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.file_name() != Some(".git".as_ref())) + .map(|path| (path.is_dir(), path)) + .collect(); + // Folders first, then by name without case, as in Treemacs. + children.sort_by_cached_key(|(is_dir, path)| (!is_dir, name(path).to_lowercase())); + for (is_dir, path) in children { + let open = is_dir && expanded.contains(&path); + rows.push(Row { + path: path.clone(), + depth, + is_dir, + }); + if open { + add_rows(&path, depth + 1, expanded, rows); + } + } +} + +impl Sidebar { + // Show the tree of `root`, with the folders above `file` open and `file` selected. + fn show(&mut self, root: PathBuf, file: Option<&Path>) { + if root != self.root { + self.root = root; + self.expanded.clear(); + } + let file = file.filter(|file| file.starts_with(&self.root)); + if let Some(file) = file { + let folders = file.ancestors().skip(1).take_while(|dir| *dir != self.root); + self.expanded.extend(folders.map(Path::to_path_buf)); + } + self.refresh(); + if let Some(index) = file.and_then(|file| self.rows.iter().position(|row| row.path == file)) + { + self.list.select(Some(index)); + self.reveal = true; + } + } + + // Read the folders again and keep the same path selected when it still exists, + // else the same row number. + fn refresh(&mut self) { + let selected = self.selected().map(|row| row.path.clone()); + self.rows.clear(); + add_rows(&self.root, 0, &self.expanded, &mut self.rows); + let index = selected.and_then(|path| self.rows.iter().position(|row| row.path == path)); + let index = index.or(self.list.selected()).unwrap_or(0); + let last = self.rows.len().checked_sub(1); + self.list.select(last.map(|last| index.min(last))); + } + + fn selected(&self) -> Option<&Row> { + self.rows.get(self.list.selected()?) + } + + // Move the selection by `step` rows, stopping at the first and the last row. + fn step(&mut self, step: isize) { + if let (Some(index), Some(last)) = (self.list.selected(), self.rows.len().checked_sub(1)) { + self.list + .select(Some(index.saturating_add_signed(step).min(last))); + } + } + + // Open or close the selected folder. + fn fold(&mut self) { + if let Some(row) = self.selected().filter(|row| row.is_dir) { + let path = row.path.clone(); + if !self.expanded.remove(&path) { + self.expanded.insert(path); + } + self.refresh(); + } + } + + // Select the folder that holds the selected row. + fn select_parent(&mut self) { + let parent = self.selected().and_then(|row| row.path.parent()); + if let Some(index) = parent.and_then(|dir| self.rows.iter().position(|row| row.path == dir)) + { + self.list.select(Some(index)); + } + } + + pub(crate) fn draw(&mut self, frame: &mut Frame, area: Rect, nerd_font: bool) { + let border = Block::bordered() + .border_type(BorderType::Rounded) + .title(format!("─ {} ", name(&self.root))) + .border_style(Style::default().fg(if self.focused { + Color::Green + } else { + Color::White + })); + let items: Vec = self + .rows + .iter() + .map(|row| { + let open = self.expanded.contains(&row.path); + let icon = match (row.is_dir, open, nerd_font) { + (true, false, false) => "▸ ", + (true, true, false) => "▾ ", + (true, false, true) => "\u{f07b} ", + (true, true, true) => "\u{f07c} ", + (false, _, false) => " ", + (false, _, true) => "\u{f15b} ", + }; + let style = if row.is_dir { + Style::default().fg(LIGHT_BLUE) + } else { + Style::default() + }; + let indent = " ".repeat(row.depth); + ListItem::new(Line::styled( + format!("{indent}{icon}{}", name(&row.path)), + style, + )) + }) + .collect(); + // The selected row gets a soft bar while the tree has focus, else bold text only. + let mut highlight = Style::default().add_modifier(Modifier::BOLD); + if self.focused { + highlight = highlight.bg(SELECTED); + } + // Put a file that was just revealed in the middle of the tree. + if std::mem::take(&mut self.reveal) + && let Some(index) = self.list.selected() + { + let height = usize::from(area.height.saturating_sub(2)); + let offset = index.saturating_sub(height / 2); + *self.list.offset_mut() = offset.min(self.rows.len().saturating_sub(height)); + } + let list = List::new(items).block(border).highlight_style(highlight); + frame.render_stateful_widget(list, area, &mut self.list); + } +} + +impl App { + // Show the tree and give it focus, or hide it. + pub(crate) fn toggle_sidebar(&mut self) { + self.sidebar.visible = !self.sidebar.visible; + self.sidebar.focused = self.sidebar.visible; + if !self.sidebar.visible { + return; + } + self.terminal.focused = false; + // The tree starts at the project of the open file, or at the working directory. + let file = self + .buffer + .path + .as_deref() + .and_then(|path| std::path::absolute(path).ok()); + let root = file + .as_deref() + .and_then(|file| crate::lsp::find_root(file).ok()) + .or_else(|| std::env::current_dir().ok()) + .unwrap_or_else(|| PathBuf::from(".")); + self.sidebar.show(root, file.as_deref()); + } + + // C-x o: focus the next visible pane, in the order tree, editor, terminal. + fn focus_next_pane(&mut self) { + let current = if self.sidebar.focused { + 0 + } else if self.terminal.focused { + 2 + } else { + 1 + }; + let visible = [self.sidebar.visible, true, self.terminal.visible]; + let next = (1..=3) + .map(|step| (current + step) % 3) + .find(|&pane| visible[pane]) + .unwrap_or(1); + self.sidebar.focused = next == 0; + self.terminal.focused = next == 2; + } + + // Show the selected file in a tab, or open or close the selected folder. + fn open_selected(&mut self) { + let Some((path, is_dir)) = self + .sidebar + .selected() + .map(|row| (row.path.clone(), row.is_dir)) + else { + return; + }; + if is_dir { + self.sidebar.fold(); + return; + } + // A path below the working directory stays short in the status bar. + let path = std::env::current_dir() + .ok() + .and_then(|dir| path.strip_prefix(dir).ok().map(Path::to_path_buf)) + .unwrap_or(path); + if let Err(err) = self.open_tab(path) { + self.status_bar_text = format!("Open failed: {err}"); + return; + } + self.sidebar.focused = false; + } + + // Keys of C-c c, C-x o and the focused tree. Returns true when the key was used. + pub(crate) fn handle_sidebar_key(&mut self, key: KeyEvent) -> bool { + let plain = |c| key.code == KeyCode::Char(c) && key.modifiers.is_empty(); + if std::mem::take(&mut self.sidebar.prefix) { + if plain('t') { + self.toggle_sidebar(); + } + return true; + } + if self.prompt_open() { + return false; + } + if self.ctrl_x_wait_flag && plain('o') && (self.sidebar.visible || self.terminal.visible) { + self.ctrl_x_wait_flag = false; + self.focus_next_pane(); + return true; + } + if !self.sidebar.focused || self.keys_go_elsewhere() { + return false; + } + + let control = key.modifiers == KeyModifiers::CONTROL; + match key.code { + KeyCode::Down => self.sidebar.step(1), + KeyCode::Up => self.sidebar.step(-1), + KeyCode::Char('n') if plain('n') || control => self.sidebar.step(1), + KeyCode::Char('p') if plain('p') || control => self.sidebar.step(-1), + KeyCode::Tab => self.sidebar.fold(), + KeyCode::Enter => self.open_selected(), + KeyCode::Char('u') if plain('u') => self.sidebar.select_parent(), + KeyCode::Char('g') if plain('g') => self.sidebar.refresh(), + KeyCode::Char('q') if plain('q') => self.toggle_sidebar(), + // Chords such as C-x C-s and the menu keys still work. + _ if key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) + || matches!(key.code, KeyCode::F(_)) => + { + return false; + } + // Other keys do nothing, so they cannot change the buffer. + _ => {} + } + true + } +} + +#[cfg(test)] +mod tests; diff --git a/src/buffers/sidebar/tests.rs b/src/buffers/sidebar/tests.rs new file mode 100644 index 0000000..6d75e57 --- /dev/null +++ b/src/buffers/sidebar/tests.rs @@ -0,0 +1,233 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + +use super::*; +use ratatui::{Terminal, backend::TestBackend}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const NONE: KeyModifiers = KeyModifiers::NONE; +const CONTROL: KeyModifiers = KeyModifiers::CONTROL; + +// A small project in the temporary folder, removed after the test. +struct Project(PathBuf); +impl Project { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let root = std::env::temp_dir().join(format!( + "ptre-sidebar-test-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + for dir in [".git", "src/inner"] { + fs::create_dir_all(root.join(dir)).unwrap(); + } + for file in [".git/config", ".hidden", "a.txt", "B.txt", "src/main.rs"] { + fs::write(root.join(file), file).unwrap(); + } + Self(root) + } + + // An app with src/main.rs open and the tree shown by C-c c t. + fn app(&self) -> App { + let mut app = App::default(); + app.buffer.open(self.0.join("src/main.rs")).unwrap(); + toggle(&mut app); + app + } +} +impl Drop for Project { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn key(app: &mut App, code: KeyCode, modifiers: KeyModifiers) { + app.handle_key(KeyEvent::new(code, modifiers)); +} + +fn toggle(app: &mut App) { + key(app, KeyCode::Char('c'), CONTROL); + key(app, KeyCode::Char('c'), NONE); + key(app, KeyCode::Char('t'), NONE); +} + +// The rows as they are indented on screen. +fn rows(app: &App) -> Vec { + let rows = app.sidebar.rows.iter(); + rows.map(|row| format!("{}{}", " ".repeat(row.depth), name(&row.path))) + .collect() +} + +fn selected(app: &App) -> String { + name(&app.sidebar.selected().unwrap().path) +} + +#[test] +fn tree_opens_at_the_project_and_the_open_file() { + let project = Project::new(); + let mut app = project.app(); + assert!(app.sidebar.visible && app.sidebar.focused); + assert_eq!(app.sidebar.root, project.0); + // Folders come first; .git is left out. + assert_eq!( + rows(&app), + ["src", " inner", " main.rs", ".hidden", "a.txt", "B.txt"] + ); + assert_eq!(selected(&app), "main.rs"); + + // Typing in the tree does not change the buffer. + key(&mut app, KeyCode::Char('x'), NONE); + assert_eq!(app.buffer.editor.get_content(), "src/main.rs"); + app.handle_paste("pasted".into()); + assert_eq!(app.buffer.editor.get_content(), "src/main.rs"); + + toggle(&mut app); + assert!(!app.sidebar.visible && !app.sidebar.focused); +} + +#[test] +fn keys_move_fold_and_find_the_parent() { + let project = Project::new(); + let mut app = project.app(); + key(&mut app, KeyCode::Char('p'), NONE); + assert_eq!(selected(&app), "inner"); + key(&mut app, KeyCode::Char('u'), NONE); + assert_eq!(selected(&app), "src"); + + // TAB closes the folder, and opens it again. + key(&mut app, KeyCode::Tab, NONE); + assert_eq!(rows(&app), ["src", ".hidden", "a.txt", "B.txt"]); + key(&mut app, KeyCode::Enter, NONE); + assert_eq!(rows(&app).len(), 6); + assert_eq!(selected(&app), "src"); + + // The selection stops at both ends. + key(&mut app, KeyCode::Up, NONE); + assert_eq!(selected(&app), "src"); + for _ in 0..10 { + key(&mut app, KeyCode::Char('n'), CONTROL); + } + assert_eq!(selected(&app), "B.txt"); + + // A new file shows after g. + fs::write(project.0.join("c.txt"), "").unwrap(); + key(&mut app, KeyCode::Char('g'), NONE); + assert_eq!(rows(&app).last().unwrap(), "c.txt"); + assert_eq!(selected(&app), "B.txt"); +} + +#[test] +fn enter_opens_files_in_tabs() { + let project = Project::new(); + let mut app = project.app(); + key(&mut app, KeyCode::Down, NONE); + key(&mut app, KeyCode::Down, NONE); + key(&mut app, KeyCode::Enter, NONE); + assert_eq!(app.buffer.path, Some(project.0.join("a.txt"))); + assert_eq!(app.buffer.editor.get_content(), "a.txt"); + assert!(app.sidebar.visible && !app.sidebar.focused); + + // C-x o goes back to the tree. + key(&mut app, KeyCode::Char('x'), CONTROL); + key(&mut app, KeyCode::Char('o'), NONE); + assert!(app.sidebar.focused); + + // Unsaved changes stay in their own tab when another file opens. + app.buffer.editor.set_content("changed"); + key(&mut app, KeyCode::Down, NONE); + key(&mut app, KeyCode::Enter, NONE); + assert_eq!(app.buffer.path, Some(project.0.join("B.txt"))); + key(&mut app, KeyCode::Char('x'), CONTROL); + key(&mut app, KeyCode::Left, NONE); + assert_eq!(app.buffer.path, Some(project.0.join("a.txt"))); + assert_eq!(app.buffer.editor.get_content(), "changed"); +} + +#[test] +fn revealed_file_is_drawn_in_the_middle() { + let project = Project::new(); + for n in 0..30 { + fs::write(project.0.join(format!("f{n:02}.txt")), "").unwrap(); + } + let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); + // Rows: src, .hidden, a.txt, B.txt, then f00.txt to f29.txt. The tree shows 18 rows. + for (file, offset) in [("f15.txt", 10), ("f29.txt", 16)] { + let mut app = App::default(); + app.buffer.open(project.0.join(file)).unwrap(); + toggle(&mut app); + terminal.draw(|frame| app.draw(frame)).unwrap(); + // Near the end, the last row stays at the bottom. + assert_eq!(app.sidebar.list.offset(), offset, "{file}"); + } +} + +#[test] +fn files_below_the_working_directory_open_with_a_short_path() { + let mut app = App::default(); + app.buffer.open(PathBuf::from("src/main.rs")).unwrap(); + toggle(&mut app); + let rows = &app.sidebar.rows; + let index = rows.iter().position(|row| name(&row.path) == "Cargo.toml"); + app.sidebar.list.select(index); + key(&mut app, KeyCode::Enter, NONE); + assert_eq!(app.buffer.path, Some(PathBuf::from("Cargo.toml"))); +} + +#[test] +fn focus_moves_through_tree_editor_and_terminal() { + let project = Project::new(); + let mut app = project.app(); + app.terminal.visible = true; + let mut panes = Vec::new(); + for _ in 0..3 { + key(&mut app, KeyCode::Char('x'), CONTROL); + key(&mut app, KeyCode::Char('o'), NONE); + panes.push((app.sidebar.focused, app.terminal.focused)); + } + assert_eq!(panes, [(false, false), (false, true), (true, false)]); + + // Hiding the tree gives focus back to the editor. + key(&mut app, KeyCode::Char('q'), NONE); + assert!(!app.sidebar.visible && !app.sidebar.focused && !app.terminal.focused); +} + +#[test] +fn tree_is_drawn_on_the_left_and_window_menu_toggles_it() { + let project = Project::new(); + let mut app = project.app(); + let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + let line = |y: u16| { + (0..100) + .map(|x| screen[(x, y)].symbol()) + .collect::() + }; + assert!(line(2).starts_with("╭─ ptre-sidebar-test-")); + assert!(line(3).starts_with("│▾ src")); + assert!(line(4).starts_with("│ ▸ inner")); + assert!(line(5).starts_with("│ main.rs")); + // The selected row has a soft bar, not reversed colors. + assert_eq!(screen[(5, 5)].bg, SELECTED); + assert!(!screen[(5, 5)].modifier.contains(Modifier::REVERSED)); + assert!(line(23).contains("RET: open")); + assert_eq!(app.editor_area.x, 31); + + // WINDOW is the last menu in a text buffer; its second entry is the tree. + key(&mut app, KeyCode::F(10), NONE); + key(&mut app, KeyCode::Left, NONE); + key(&mut app, KeyCode::Down, NONE); + key(&mut app, KeyCode::Enter, NONE); + assert!(!app.sidebar.visible); +} diff --git a/src/buffers/tabs.rs b/src/buffers/tabs.rs new file mode 100644 index 0000000..0604bf3 --- /dev/null +++ b/src/buffers/tabs.rs @@ -0,0 +1,182 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + +//! File tabs above the editor: C-x Right and C-x Left switch tabs, C-x k closes one. + +use super::{editor::Buffer, menu::LIGHT_BLUE}; +use crate::app::App; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use ratatui::{ + Frame, + layout::Rect, + style::{Color, Modifier, Style}, + text::{Line, Span}, + widgets::Paragraph, +}; +use std::{ + io, + path::{Path, PathBuf}, +}; + +// Colors of the other tabs and of the unsaved mark, as in the confirm dialog. +const MUTED: Color = Color::Rgb(140, 138, 145); +const AMBER: Color = Color::Rgb(232, 181, 106); + +// The active tab is App::buffer. The other tabs wait here, in screen order. +#[derive(Default)] +pub(crate) struct Tabs { + left: Vec, + right: Vec, + // True while the dialog asks whether to close a tab with unsaved changes. + pub(crate) close_confirm: bool, +} + +fn name(buffer: &Buffer) -> String { + let name = buffer.path.as_deref().and_then(Path::file_name); + name.map_or_else(|| "[No Name]".into(), |name| name.to_string_lossy().into()) +} + +// One tab, drawn like a name in the menu bar: "❃" marks the active tab. +// A dot marks unsaved changes. +fn tab(buffer: &Buffer, active: bool) -> Vec> { + let (marker, style) = if active { + ( + "❃ ", + Style::default().fg(LIGHT_BLUE).add_modifier(Modifier::BOLD), + ) + } else { + (" ", Style::default().fg(MUTED)) + }; + let mut spans = vec![Span::styled(format!("{marker}{}", name(buffer)), style)]; + if buffer.is_dirty() { + spans.push(Span::styled(" ●", Style::default().fg(AMBER))); + } + spans.push(Span::raw(" ")); + spans +} + +impl App { + // All tabs in screen order. + fn tab_buffers(&self) -> impl Iterator { + let tabs = &self.tabs; + tabs.left.iter().chain([&self.buffer]).chain(&tabs.right) + } + + // Make the tab at `index` active. An index past the last tab goes round to the first. + fn select_tab(&mut self, index: usize) { + let mut all = std::mem::take(&mut self.tabs.left); + all.push(std::mem::take(&mut self.buffer)); + all.append(&mut self.tabs.right); + let index = index % all.len(); + self.tabs.right = all.split_off(index + 1); + self.buffer = all.pop().unwrap_or_default(); + self.tabs.left = all; + self.paste_scroll = None; + self.buffer.check_disk(); + } + + // Show `path` in a tab: its own tab when it is open already, else a new one. + pub(crate) fn open_tab(&mut self, path: PathBuf) -> io::Result<()> { + let target = std::path::absolute(&path)?; + let index = self.tab_buffers().position(|buffer| { + let path = buffer.path.as_deref(); + path.and_then(|path| std::path::absolute(path).ok()) + .as_ref() + == Some(&target) + }); + if let Some(index) = index { + self.select_tab(index); + return Ok(()); + } + let mut buffer = Buffer::default(); + buffer.open(path)?; + if self.buffer.path.is_none() && self.buffer.editor.get_content().is_empty() { + // The file takes the place of an empty unnamed tab. + self.buffer = buffer; + } else { + // The new tab goes right after the active one. + let old = std::mem::replace(&mut self.buffer, buffer); + self.tabs.left.push(old); + } + self.paste_scroll = None; + Ok(()) + } + + // Close the active tab. The tab on its right takes its place, else the one on its left. + fn close_tab(&mut self) { + let next = if self.tabs.right.is_empty() { + self.tabs.left.pop() + } else { + Some(self.tabs.right.remove(0)) + }; + // Closing the last tab leaves an empty one. + self.buffer = next.unwrap_or_default(); + self.paste_scroll = None; + self.buffer.check_disk(); + } + + // Keys of the close dialog, C-x Right, C-x Left and C-x k. Returns true when used. + pub(crate) fn handle_tab_key(&mut self, key: KeyEvent) -> bool { + if self.tabs.close_confirm { + let plain = key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT; + match key.code { + KeyCode::Char('y' | 'Y') | KeyCode::Enter if plain => { + self.tabs.close_confirm = false; + self.close_tab(); + } + KeyCode::Char('n' | 'N') | KeyCode::Esc => { + self.tabs.close_confirm = false; + self.status_bar_text = "Close cancelled".into(); + } + _ => {} + } + return true; + } + if !self.ctrl_x_wait_flag || !key.modifiers.is_empty() { + return false; + } + let active = self.tabs.left.len(); + let count = active + 1 + self.tabs.right.len(); + match key.code { + KeyCode::Right => self.select_tab(active + 1), + KeyCode::Left => self.select_tab(active + count - 1), + // Unsaved changes would be lost, so ask first. + KeyCode::Char('k') if self.buffer.is_dirty() => self.tabs.close_confirm = true, + KeyCode::Char('k') => self.close_tab(), + _ => return false, + } + self.ctrl_x_wait_flag = false; + true + } + + pub(crate) fn draw_tabs(&self, frame: &mut Frame, area: Rect) { + let active = self.tabs.left.len(); + let tabs: Vec<_> = self + .tab_buffers() + .enumerate() + .map(|(index, buffer)| tab(buffer, index == active)) + .collect(); + // Leave out tabs on the left until the active tab fits. + let width = |tabs: &[Vec]| tabs.iter().flatten().map(Span::width).sum::(); + let mut first = 0; + while first < active && width(&tabs[first..=active]) > usize::from(area.width) { + first += 1; + } + let spans: Vec<_> = tabs.into_iter().skip(first).flatten().collect(); + frame.render_widget(Paragraph::new(Line::from(spans)), area); + } +} + +#[cfg(test)] +mod tests; diff --git a/src/buffers/tabs/tests.rs b/src/buffers/tabs/tests.rs new file mode 100644 index 0000000..4f1daee --- /dev/null +++ b/src/buffers/tabs/tests.rs @@ -0,0 +1,125 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + +use super::*; +use ratatui::{Terminal, backend::TestBackend}; + +const NONE: KeyModifiers = KeyModifiers::NONE; + +fn key(app: &mut App, code: KeyCode) { + app.handle_key(KeyEvent::new(code, NONE)); +} + +// C-x and then `code`. +fn chord(app: &mut App, code: KeyCode) { + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)); + key(app, code); +} + +// The tab names in order; the active one starts with "*". +fn tabs(app: &App) -> Vec { + let active = app.tabs.left.len(); + let names = app.tab_buffers().map(|buffer| match buffer.is_dirty() { + true => format!("{} ●", name(buffer)), + false => name(buffer), + }); + names + .enumerate() + .map(|(index, name)| { + if index == active { + format!("*{name}") + } else { + name + } + }) + .collect() +} + +#[test] +fn new_tabs_follow_the_active_one_and_open_files_are_reused() { + let mut app = App::default(); + // The first file takes the place of the empty unnamed tab. + app.open_tab("Cargo.toml".into()).unwrap(); + assert_eq!(tabs(&app), ["*Cargo.toml"]); + app.open_tab("README.md".into()).unwrap(); + chord(&mut app, KeyCode::Left); + app.open_tab("src/main.rs".into()).unwrap(); + assert_eq!(tabs(&app), ["Cargo.toml", "*main.rs", "README.md"]); + + // An open file gets its tab back, even with another form of its path. + app.open_tab(std::path::absolute("README.md").unwrap()) + .unwrap(); + assert_eq!(tabs(&app), ["Cargo.toml", "main.rs", "*README.md"]); + assert!(app.open_tab("missing-file".into()).is_err()); + assert_eq!(tabs(&app).len(), 3); + + // C-x Right and C-x Left go round at the ends. + chord(&mut app, KeyCode::Right); + assert_eq!(tabs(&app)[0], "*Cargo.toml"); + chord(&mut app, KeyCode::Left); + assert_eq!(tabs(&app)[2], "*README.md"); + assert!(!app.ctrl_x_wait_flag); +} + +#[test] +fn closing_a_tab_with_changes_asks_first() { + let mut app = App::default(); + app.open_tab("Cargo.toml".into()).unwrap(); + app.open_tab("README.md".into()).unwrap(); + app.buffer.editor.set_content("changed"); + chord(&mut app, KeyCode::Char('k')); + assert!(app.tabs.close_confirm); + + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + let text: String = screen.content.iter().map(|cell| cell.symbol()).collect(); + assert!(text.contains("Buffer has unsaved changes. Close it?")); + + // Other keys do not edit while the dialog is open; N keeps the tab. + key(&mut app, KeyCode::Char('x')); + key(&mut app, KeyCode::Char('n')); + assert_eq!(app.buffer.editor.get_content(), "changed"); + assert_eq!(tabs(&app), ["Cargo.toml", "*README.md ●"]); + + chord(&mut app, KeyCode::Char('k')); + key(&mut app, KeyCode::Char('y')); + assert_eq!(tabs(&app), ["*Cargo.toml"]); + // A tab without changes closes at once; closing the last one leaves an empty tab. + chord(&mut app, KeyCode::Char('k')); + assert_eq!(tabs(&app), ["*[No Name]"]); + assert!(app.buffer.path.is_none()); +} + +#[test] +fn tab_row_keeps_the_active_tab_in_view() { + let mut app = App::default(); + for path in ["Cargo.toml", "README.md", "src/main.rs", "src/app.rs"] { + app.open_tab(path.into()).unwrap(); + } + app.buffer.editor.set_content("changed"); + let mut terminal = Terminal::new(TestBackend::new(30, 1)).unwrap(); + terminal + .draw(|frame| app.draw_tabs(frame, frame.area())) + .unwrap(); + let screen = terminal.backend().buffer(); + let row: String = (0..30).map(|x| screen[(x, 0)].symbol()).collect(); + assert!(row.starts_with(" main.rs ❃ app.rs ● "), "{row}"); + // The active tab is bold light blue, the others are dimmer, and the dot is amber. + assert_eq!(screen[(13, 0)].fg, LIGHT_BLUE); + assert!(screen[(13, 0)].modifier.contains(Modifier::BOLD)); + assert_eq!(screen[(2, 0)].fg, MUTED); + assert_eq!(screen[(20, 0)].fg, AMBER); + assert!(screen.content.iter().all(|cell| cell.bg == Color::Reset)); +} diff --git a/src/buffers/terminal.rs b/src/buffers/terminal.rs index b9aa59a..1d273cb 100644 --- a/src/buffers/terminal.rs +++ b/src/buffers/terminal.rs @@ -348,6 +348,7 @@ impl crate::app::App { pub(crate) fn prompt_open(&self) -> bool { self.cpp_check_modal() || self.overwrite_confirm + || self.tabs.close_confirm || self.save_path_input.is_some() || self.search.reads_input() || self.goto_line.is_open() @@ -375,19 +376,14 @@ impl crate::app::App { if let Err(err) = self.terminal.toggle(cwd) { self.status_bar_text = format!("Terminal failed: {err}"); } + // Only one pane has focus. + self.sidebar.focused &= !self.terminal.focused; } else if plain('c') { self.run_cpp_check(crate::buffers::cpp_checks::Tool::Tidy); } return true; } - // C-x o moves focus between the editor and the terminal, like Emacs. - if self.ctrl_x_wait_flag && plain('o') && self.terminal.visible { - self.ctrl_x_wait_flag = false; - self.terminal.focused = !self.terminal.focused; - return true; - } - if self.terminal.focused { if !self.ctrl_x_wait_flag && let Some(session) = &mut self.terminal.session diff --git a/src/lsp/mod.rs b/src/lsp/mod.rs index bc82c08..28ade82 100644 --- a/src/lsp/mod.rs +++ b/src/lsp/mod.rs @@ -30,3 +30,4 @@ pub(crate) use client::Client; pub(crate) use diagnostics::{Diagnostic, Severity}; pub(crate) use normalize::{Candidate, Completions}; pub(crate) use plugin::{Plugin, language_id, load as load_plugins}; +pub(crate) use workspace::find_root; From 586500bbb06a3faa60d161e887dd23340b4ab6fa Mon Sep 17 00:00:00 2001 From: CharOfString Date: Sat, 17 Oct 2026 22:29:08 -0500 Subject: [PATCH 2/5] feat: Open project --- doc/shortcuts/shortcuts.md | 3 + doc/shortcuts/shortcuts.zh.md | 2 + src/buffers/completion/keys.rs | 7 +- src/buffers/cpp_checks/mod.rs | 1 + src/buffers/cpp_checks/ui.rs | 8 +-- src/buffers/diagnostics/popup.rs | 1 + src/buffers/menu/mod.rs | 20 ++++-- src/buffers/menu/tests.rs | 13 +++- src/buffers/paste.rs | 2 +- src/buffers/render.rs | 5 ++ src/buffers/sidebar.rs | 117 +++++++++++++++++++++++++------ src/buffers/sidebar/tests.rs | 48 +++++++++++++ src/buffers/terminal.rs | 1 + src/utils/mod.rs | 1 + src/utils/path.rs | 30 ++++++++ 15 files changed, 221 insertions(+), 38 deletions(-) create mode 100644 src/utils/path.rs diff --git a/doc/shortcuts/shortcuts.md b/doc/shortcuts/shortcuts.md index 4103860..1677ea9 100644 --- a/doc/shortcuts/shortcuts.md +++ b/doc/shortcuts/shortcuts.md @@ -35,6 +35,7 @@ hide and reopen the terminal to start a new session. * `Ctrl + C` `C` `T`: show or hide the file tree on the left, like Emacs Treemacs. It is also in the WINDOW menu. Showing the tree gives it focus. +* `Ctrl + C` `Ctrl + P` `A`: open a project. Type a folder path and press `Enter`. * `N` / `P`: next / previous row. `Down` / `Up` and `Ctrl + N` / `Ctrl + P` also work. * `Tab`: open or close the selected folder. * `Enter`: open the selected file in a new tab (or go to its tab when it is open already), @@ -47,6 +48,8 @@ The tree starts at the project of the current file: the nearest folder above it `.git`, `Cargo.toml`, `CMakeLists.txt`, `compile_commands.json` or `compile_flags.txt` (otherwise the file's own folder). For an unnamed file, it starts at the editor's working directory. It opens the folders above the current file and selects it. The `.git` folder is not shown. +When the tree is shown again, it keeps its folder (such as an opened project) while the +current file is inside it. ## Tabs diff --git a/doc/shortcuts/shortcuts.zh.md b/doc/shortcuts/shortcuts.zh.md index c830305..6feee44 100644 --- a/doc/shortcuts/shortcuts.zh.md +++ b/doc/shortcuts/shortcuts.zh.md @@ -33,6 +33,7 @@ Shell 退出后,隐藏并重新打开终端即可启动新会话。 * `Ctrl + C` `C` `T`:在左侧显示或隐藏文件树,类似 Emacs 的 Treemacs。 也可以从 WINDOW 菜单打开。显示文件树时焦点会移到文件树上。 +* `Ctrl + C` `Ctrl + P` `A`:打开项目。输入目录路径后按 `Enter`。 * `N` / `P`:下一行 / 上一行。也支持 `Down` / `Up` 和 `Ctrl + N` / `Ctrl + P`。 * `Tab`:展开或折叠选中的目录。 * `Enter`:在新标签页中打开选中的文件(已打开的文件会切换到它的标签页), @@ -45,6 +46,7 @@ Shell 退出后,隐藏并重新打开终端即可启动新会话。 `compile_commands.json` 或 `compile_flags.txt` 的目录(找不到时使用文件所在的目录)。 未命名文件则从编辑器的工作目录开始。 打开时会展开当前文件上层的目录并选中它。`.git` 目录不会显示。 +再次显示文件树时,只要当前文件仍在原来的目录(例如打开的项目)中,就会继续显示该目录。 ## 标签页 diff --git a/src/buffers/completion/keys.rs b/src/buffers/completion/keys.rs index 6fec753..83b6d66 100644 --- a/src/buffers/completion/keys.rs +++ b/src/buffers/completion/keys.rs @@ -14,6 +14,7 @@ use super::words::is_word_char; use crate::app::App; +use crate::buffers::sidebar::Prefix; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; // Word length at which typing opens the popup by itself. @@ -37,14 +38,16 @@ impl App { self.ctrl_c_wait_flag = false; if key.code == KeyCode::Char('l') && alt { self.toggle_auto_completion(); + } else if key.code == KeyCode::Char('p') && control { + self.sidebar.prefix = Some(Prefix::Project); } else if key.modifiers.is_empty() { use crate::buffers::cpp_checks::Tool; match key.code { KeyCode::Char('l') => self.run_cpp_check(Tool::Cpplint), // C-c t is a prefix; handle_terminal_key reads the next key. KeyCode::Char('t') => self.ctrl_c_t_wait_flag = true, - // C-c c is a prefix; handle_sidebar_key reads the next key. - KeyCode::Char('c') => self.sidebar.prefix = true, + // C-c c is a prefix; handle_sidebar_key reads the next key, as for C-c C-p. + KeyCode::Char('c') => self.sidebar.prefix = Some(Prefix::Tree), KeyCode::Char('a') => self.request_fix(), _ => {} } diff --git a/src/buffers/cpp_checks/mod.rs b/src/buffers/cpp_checks/mod.rs index 0a49734..83289a7 100644 --- a/src/buffers/cpp_checks/mod.rs +++ b/src/buffers/cpp_checks/mod.rs @@ -190,6 +190,7 @@ impl App { if self.save_path_input.is_some() || self.overwrite_confirm || self.cpp_checks.path_input.is_some() + || self.sidebar.project_input.is_some() || self.menu.active.is_some() { return; diff --git a/src/buffers/cpp_checks/ui.rs b/src/buffers/cpp_checks/ui.rs index b45cff1..cfad4c8 100644 --- a/src/buffers/cpp_checks/ui.rs +++ b/src/buffers/cpp_checks/ui.rs @@ -33,12 +33,8 @@ impl App { self.status_bar_text = "Cpplint setup cancelled".into(); } KeyCode::Enter => { - let path = if let Some(rest) = input.strip_prefix("~/") { - std::env::var_os("HOME").map(|home| PathBuf::from(home).join(rest)) - } else { - Some(PathBuf::from(input.as_str())) - }; - let path = path.and_then(|path| path.canonicalize().ok()); + let path = crate::utils::path::expand_home(input) + .and_then(|path| path.canonicalize().ok()); if let Some(path) = path.filter(|path| settings::executable(path)) { let mut settings = self.cpp_checks.settings.clone(); settings.cpplint_path = path.to_string_lossy().into_owned(); diff --git a/src/buffers/diagnostics/popup.rs b/src/buffers/diagnostics/popup.rs index 273e6bc..f4e35ed 100644 --- a/src/buffers/diagnostics/popup.rs +++ b/src/buffers/diagnostics/popup.rs @@ -45,6 +45,7 @@ impl App { || self.menu.active.is_some() || self.cpp_check_modal() || self.save_path_input.is_some() + || self.sidebar.project_input.is_some() || self.overwrite_confirm { return; diff --git a/src/buffers/menu/mod.rs b/src/buffers/menu/mod.rs index 1b674af..9413df6 100644 --- a/src/buffers/menu/mod.rs +++ b/src/buffers/menu/mod.rs @@ -24,7 +24,11 @@ use ratatui::{ }; pub(crate) const LIGHT_BLUE: Color = Color::Rgb(155, 205, 245); -const FILE: &[(&str, &str)] = &[("Save", "C-x C-s"), ("Quit", "C-x C-c")]; +const FILE: &[(&str, &str)] = &[ + ("Open Project", "C-c C-p a"), + ("Save", "C-x C-s"), + ("Quit", "C-x C-c"), +]; const EDIT: &[(&str, &str)] = &[ ("Undo", "C-x u"), ("Redo", "C-M-_"), @@ -309,11 +313,15 @@ impl App { let ctrl = KeyModifiers::CONTROL; let alt = KeyModifiers::ALT; if active == 0 { - self.handle_key(KeyEvent::new(KeyCode::Char('x'), ctrl)); - self.handle_key(KeyEvent::new( - KeyCode::Char(if selected == 0 { 's' } else { 'c' }), - ctrl, - )); + if selected == 0 { + self.ask_project(); + } else { + self.handle_key(KeyEvent::new(KeyCode::Char('x'), ctrl)); + self.handle_key(KeyEvent::new( + KeyCode::Char(if selected == 1 { 's' } else { 'c' }), + ctrl, + )); + } } else if active == BUFFER_MENU { if selected == 3 { self.handle_key(KeyEvent::new(KeyCode::Char('g'), alt)); diff --git a/src/buffers/menu/tests.rs b/src/buffers/menu/tests.rs index 4111246..ae69ab8 100644 --- a/src/buffers/menu/tests.rs +++ b/src/buffers/menu/tests.rs @@ -136,7 +136,7 @@ fn active_menu_and_popup_use_markers_without_underlines() { let label: String = (0..80).map(|x| screen[(x, 0)].symbol()).collect(); assert!(label.contains(&format!("❃ {}", MENUS[active]))); assert_eq!(screen[(popup_x, 1)].symbol(), "╭"); - let popup_width = [18, 17, 27][active]; + let popup_width = [28, 17, 27][active]; assert_eq!(screen[(popup_x + popup_width - 1, 1)].symbol(), "╮"); assert_eq!(screen[(popup_x + 1, 2)].symbol(), "·"); assert_eq!(screen[(popup_x + 1, 3)].symbol(), " "); @@ -160,14 +160,21 @@ fn active_menu_and_popup_use_markers_without_underlines() { } #[test] -fn menu_consumes_typing_and_save_opens_prompt() { +fn menu_consumes_typing_and_file_entries_open_prompts() { let mut app = App::default(); app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); assert_eq!(app.buffer.editor.get_content(), ""); app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert!(app.save_path_input.is_some()); + assert!(app.sidebar.project_input.is_some()); assert!(app.menu.active.is_none()); + + // The second entry saves. + app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(app.save_path_input.is_some()); } #[test] diff --git a/src/buffers/paste.rs b/src/buffers/paste.rs index 9b90696..8ba49e2 100644 --- a/src/buffers/paste.rs +++ b/src/buffers/paste.rs @@ -99,7 +99,7 @@ impl App { || self.ctrl_x_wait_flag || self.ctrl_c_wait_flag || self.ctrl_c_t_wait_flag - || self.sidebar.prefix + || self.sidebar.prefix.is_some() } } diff --git a/src/buffers/render.rs b/src/buffers/render.rs index 9c38b81..51029b1 100644 --- a/src/buffers/render.rs +++ b/src/buffers/render.rs @@ -116,6 +116,11 @@ impl App { ) } else if let Some(prompt) = self.search.prompt() { format!(" {prompt}") + } else if let Some(input) = &self.sidebar.project_input { + format!( + " Open project: {input}█ ※ Enter: open Esc: cancel ※ {}", + self.status_bar_text + ) } else if let Some(path_input) = &self.save_path_input { format!( " Save as: {path_input}█ ※ Enter: save Esc: cancel ※ {}", diff --git a/src/buffers/sidebar.rs b/src/buffers/sidebar.rs index 767c82a..399eab9 100644 --- a/src/buffers/sidebar.rs +++ b/src/buffers/sidebar.rs @@ -34,8 +34,10 @@ use std::{ pub(crate) struct Sidebar { pub(crate) visible: bool, pub(crate) focused: bool, - // Set after C-c c, which waits for its next key. - pub(crate) prefix: bool, + // Set after C-c c or C-c C-p, which wait for their next key. + pub(crate) prefix: Option, + // The folder typed after C-c C-p a, while the prompt is open. + pub(crate) project_input: Option, root: PathBuf, // Folders that show their content. expanded: HashSet, @@ -46,6 +48,14 @@ pub(crate) struct Sidebar { reveal: bool, } +#[derive(Clone, Copy)] +pub(crate) enum Prefix { + // C-c c, as in C-c c t. + Tree, + // C-c C-p, as in C-c C-p a. Treemacs keeps its project commands here. + Project, +} + // The bar under the selected row, as the buttons in the confirm dialog. const SELECTED: Color = Color::Rgb(60, 60, 68); @@ -100,6 +110,7 @@ impl Sidebar { if root != self.root { self.root = root; self.expanded.clear(); + self.list = ListState::default(); } let file = file.filter(|file| file.starts_with(&self.root)); if let Some(file) = file { @@ -211,28 +222,88 @@ impl Sidebar { } impl App { + fn absolute_path(&self) -> Option { + let path = self.buffer.path.as_deref()?; + std::path::absolute(path).ok() + } + // Show the tree and give it focus, or hide it. pub(crate) fn toggle_sidebar(&mut self) { - self.sidebar.visible = !self.sidebar.visible; - self.sidebar.focused = self.sidebar.visible; - if !self.sidebar.visible { + if self.sidebar.visible { + self.sidebar.visible = false; + self.sidebar.focused = false; return; } + // Keep the folder shown last while the open file is inside it, as after C-c C-p a. + // Else start at the project of the open file, or at the working directory. + let file = self.absolute_path(); + let root = &self.sidebar.root; + let keep = + !root.as_os_str().is_empty() && file.as_ref().is_none_or(|file| file.starts_with(root)); + let root = if keep { + root.clone() + } else { + file.as_deref() + .and_then(|file| crate::lsp::find_root(file).ok()) + .or_else(|| std::env::current_dir().ok()) + .unwrap_or_else(|| PathBuf::from(".")) + }; + self.show_sidebar(root); + } + + // Show the tree of `root` with focus, and select the open file when it is inside. + fn show_sidebar(&mut self, root: PathBuf) { + self.sidebar.visible = true; + self.sidebar.focused = true; self.terminal.focused = false; - // The tree starts at the project of the open file, or at the working directory. - let file = self - .buffer - .path - .as_deref() - .and_then(|path| std::path::absolute(path).ok()); - let root = file - .as_deref() - .and_then(|file| crate::lsp::find_root(file).ok()) - .or_else(|| std::env::current_dir().ok()) - .unwrap_or_else(|| PathBuf::from(".")); + let file = self.absolute_path(); self.sidebar.show(root, file.as_deref()); } + // C-c C-p a: ask for a folder and show its tree, as treemacs-add-project-to-workspace. + pub(crate) fn ask_project(&mut self) { + self.sidebar.project_input = Some(String::new()); + self.status_bar_text = "Enter a folder path".into(); + } + + // Keys of the open project prompt. Returns true while the prompt is open. + fn handle_project_input(&mut self, key: KeyEvent) -> bool { + let Some(input) = &mut self.sidebar.project_input else { + return false; + }; + match key.code { + KeyCode::Esc => { + self.sidebar.project_input = None; + self.status_bar_text = "Open project cancelled".into(); + } + KeyCode::Enter => { + // Relative paths start at the working directory. + let dir = crate::utils::path::expand_home(input.trim()) + .and_then(|dir| dir.canonicalize().ok()) + .filter(|dir| dir.is_dir()); + if let Some(dir) = dir { + self.sidebar.project_input = None; + self.status_bar_text.clear(); + self.show_sidebar(dir); + } else { + self.status_bar_text = "No such folder".into(); + } + } + KeyCode::Backspace => { + input.pop(); + } + KeyCode::Char(c) + if !key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => + { + input.push(c) + } + _ => {} + } + true + } + // C-x o: focus the next visible pane, in the order tree, editor, terminal. fn focus_next_pane(&mut self) { let current = if self.sidebar.focused { @@ -276,15 +347,21 @@ impl App { self.sidebar.focused = false; } - // Keys of C-c c, C-x o and the focused tree. Returns true when the key was used. + // Keys of C-c c, C-c C-p, the project prompt, C-x o and the focused tree. + // Returns true when the key was used. pub(crate) fn handle_sidebar_key(&mut self, key: KeyEvent) -> bool { let plain = |c| key.code == KeyCode::Char(c) && key.modifiers.is_empty(); - if std::mem::take(&mut self.sidebar.prefix) { - if plain('t') { - self.toggle_sidebar(); + if let Some(prefix) = self.sidebar.prefix.take() { + match prefix { + Prefix::Tree if plain('t') => self.toggle_sidebar(), + Prefix::Project if plain('a') => self.ask_project(), + _ => {} } return true; } + if self.handle_project_input(key) { + return true; + } if self.prompt_open() { return false; } diff --git a/src/buffers/sidebar/tests.rs b/src/buffers/sidebar/tests.rs index 6d75e57..b90da1d 100644 --- a/src/buffers/sidebar/tests.rs +++ b/src/buffers/sidebar/tests.rs @@ -172,6 +172,54 @@ fn revealed_file_is_drawn_in_the_middle() { } } +#[test] +fn ctrl_c_ctrl_p_a_opens_a_project_that_stays() { + let project = Project::new(); + let src = project.0.join("src").canonicalize().unwrap(); + let mut app = App::default(); + app.buffer.open(project.0.join("a.txt")).unwrap(); + let open_project = |app: &mut App| { + key(app, KeyCode::Char('c'), CONTROL); + key(app, KeyCode::Char('p'), CONTROL); + key(app, KeyCode::Char('a'), NONE); + assert!(app.sidebar.project_input.is_some()); + }; + open_project(&mut app); + key(&mut app, KeyCode::Esc, NONE); + assert_eq!(app.status_bar_text, "Open project cancelled"); + + // A missing folder keeps the prompt open; typing never reaches the buffer. + open_project(&mut app); + app.handle_paste("/missing".into()); + key(&mut app, KeyCode::Enter, NONE); + assert_eq!(app.status_bar_text, "No such folder"); + for _ in 0.."/missing".len() { + key(&mut app, KeyCode::Backspace, NONE); + } + app.handle_paste(src.display().to_string()); + key(&mut app, KeyCode::Enter, NONE); + assert_eq!(app.buffer.editor.get_content(), "a.txt"); + assert!(app.sidebar.project_input.is_none() && app.sidebar.focused); + assert_eq!(app.sidebar.root, src); + assert_eq!(rows(&app), ["inner", "main.rs"]); + + // The tree keeps the project while the open file is inside it. + key(&mut app, KeyCode::Down, NONE); + key(&mut app, KeyCode::Enter, NONE); + toggle(&mut app); + toggle(&mut app); + assert_eq!(app.sidebar.root, src); + assert_eq!(selected(&app), "main.rs"); + + // Back in a.txt, it starts at the project of a.txt again. + key(&mut app, KeyCode::Char('x'), CONTROL); + key(&mut app, KeyCode::Left, NONE); + toggle(&mut app); + toggle(&mut app); + assert_eq!(app.sidebar.root, project.0); + assert_eq!(selected(&app), "a.txt"); +} + #[test] fn files_below_the_working_directory_open_with_a_short_path() { let mut app = App::default(); diff --git a/src/buffers/terminal.rs b/src/buffers/terminal.rs index 1d273cb..9cd380c 100644 --- a/src/buffers/terminal.rs +++ b/src/buffers/terminal.rs @@ -350,6 +350,7 @@ impl crate::app::App { || self.overwrite_confirm || self.tabs.close_confirm || self.save_path_input.is_some() + || self.sidebar.project_input.is_some() || self.search.reads_input() || self.goto_line.is_open() || self.menu.active.is_some() diff --git a/src/utils/mod.rs b/src/utils/mod.rs index b9d289c..7c7cbe5 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -14,3 +14,4 @@ pub(crate) mod file_type; pub(crate) mod keys; +pub(crate) mod path; diff --git a/src/utils/path.rs b/src/utils/path.rs new file mode 100644 index 0000000..ba189aa --- /dev/null +++ b/src/utils/path.rs @@ -0,0 +1,30 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + +//! Paths typed in prompts. + +use std::path::PathBuf; + +pub(crate) fn expand_home(input: &str) -> Option { + let rest = if input == "~" { + Some("") + } else { + input.strip_prefix("~/") + }; + + match rest { + Some(rest) => std::env::var_os("HOME").map(|home| PathBuf::from(home).join(rest)), + None => Some(PathBuf::from(input)), + } +} From 38ef1d902ca49148ef49da01c9915f9b03b35a1d Mon Sep 17 00:00:00 2001 From: CharOfString Date: Sat, 17 Oct 2026 22:47:39 -0500 Subject: [PATCH 3/5] feat: Clang-tidy/cpplint config --- src/buffers/cpp_checks/cpplint.rs | 14 +++++ src/buffers/cpp_checks/mod.rs | 13 +++-- src/buffers/cpp_checks/project.rs | 63 ++++++++++++++++++++++ src/buffers/cpp_checks/tests.rs | 86 +++++++++++++++++++++++++++---- src/buffers/sidebar.rs | 11 +++- src/buffers/sidebar/tests.rs | 1 + 6 files changed, 172 insertions(+), 16 deletions(-) create mode 100644 src/buffers/cpp_checks/project.rs diff --git a/src/buffers/cpp_checks/cpplint.rs b/src/buffers/cpp_checks/cpplint.rs index e3d8152..6de3289 100644 --- a/src/buffers/cpp_checks/cpplint.rs +++ b/src/buffers/cpp_checks/cpplint.rs @@ -1,3 +1,17 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + // Turn Cpplint output into diagnostics for the editor. Each finding is one line: // /path/main.cpp:3: Missing spaces around = [whitespace/operators] [4] // Line 0 means the whole file, such as a missing copyright line. diff --git a/src/buffers/cpp_checks/mod.rs b/src/buffers/cpp_checks/mod.rs index 83289a7..fc77c47 100644 --- a/src/buffers/cpp_checks/mod.rs +++ b/src/buffers/cpp_checks/mod.rs @@ -13,14 +13,16 @@ // not, see . mod cpplint; +mod project; pub(super) mod settings; #[cfg(test)] mod tests; mod ui; use crate::{app::App, lsp::Diagnostic}; +pub(crate) use project::config_files; use settings::{Settings, settings_path}; -use std::{io, path::PathBuf, process::Command, sync::mpsc}; +use std::{io, path::PathBuf, sync::mpsc}; #[derive(Clone, Copy)] pub(crate) enum Tool { @@ -159,16 +161,17 @@ impl App { }; let program = match tool { - Tool::Tidy => "clang-tidy".to_owned(), - Tool::Cpplint => settings.cpplint_path.clone(), + Tool::Tidy => "clang-tidy", + Tool::Cpplint => &settings.cpplint_path, }; + + let mut command = project::command(tool, program, &path, self.sidebar.project.as_deref()); let (sender, receiver) = mpsc::channel(); let text = self.buffer.editor.get_content(); self.cpp_checks.checking = Some((tool, path.clone(), text)); - // Run without a shell so spaces and shell characters in paths stay literal. std::thread::spawn(move || { - let result = Command::new(program).arg(&path).output(); + let result = command.output(); let report = match result { Ok(output) => format!( "{name}: {}\n{}\n\n{}{}", diff --git a/src/buffers/cpp_checks/project.rs b/src/buffers/cpp_checks/project.rs new file mode 100644 index 0000000..8e1bb95 --- /dev/null +++ b/src/buffers/cpp_checks/project.rs @@ -0,0 +1,63 @@ +// Copyright (C) 2026 CharOfString +// +// +// This software is free software: you can redistribute it and/or modify it under the terms of the +// GNU General Public License as published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with this software. If +// not, see . + +//! Run the C/C++ checks while opening projects + +use super::Tool; +use std::{ffi::OsString, path::Path, process::Command}; + +// Configuration files. +const CONFIG_FILES: [&str; 7] = [ + "CPPLINT.cfg", + ".clang-tidy", + ".clang-format", + "_clang-format", + "compile_commands.json", + "build/compile_commands.json", + "compile_flags.txt", +]; + +// The config files in root. +pub(crate) fn config_files(root: &Path) -> Vec<&'static str> { + CONFIG_FILES + .into_iter() + .filter(|file| root.join(file).is_file()) + .collect() +} + +// The command that checks file. +pub(super) fn command(tool: Tool, program: &str, file: &Path, project: Option<&Path>) -> Command { + let mut command = Command::new(program); + if let Some(root) = project.filter(|root| file.starts_with(root)) { + command.current_dir(root); + match tool { + Tool::Cpplint => { + let mut option = OsString::from("--repository="); + option.push(root); + command.arg(option); + } + + Tool::Tidy => { + let database = [root.to_path_buf(), root.join("build")] + .into_iter() + .find(|dir| dir.join("compile_commands.json").is_file()); + if let Some(dir) = database { + command.arg("-p").arg(dir); + } + } + } + } + command.arg(file); + command +} diff --git a/src/buffers/cpp_checks/tests.rs b/src/buffers/cpp_checks/tests.rs index fce5519..829083c 100644 --- a/src/buffers/cpp_checks/tests.rs +++ b/src/buffers/cpp_checks/tests.rs @@ -40,6 +40,15 @@ fn press(app: &mut App, code: KeyCode) { app.handle_key(KeyEvent::new(code, KeyModifiers::NONE)); } +// Wait for the running check, at most 5 seconds. +fn wait(app: &mut App) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while app.cpp_checks.pending.is_some() && std::time::Instant::now() < deadline { + app.poll_cpp_check(); + std::thread::sleep(std::time::Duration::from_millis(10)); + } +} + fn cpp_app(dir: &Directory) -> App { let mut app = App::default(); let path = dir.0.join("test.cpp"); @@ -154,11 +163,7 @@ fn checker_runs_literal_paths_and_displays_stderr_and_exit_status() { app.cpp_checks.settings.cpplint_path = executable.display().to_string(); app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); press(&mut app, KeyCode::Char('l')); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while app.cpp_checks.pending.is_some() && std::time::Instant::now() < deadline { - app.poll_cpp_check(); - std::thread::sleep(std::time::Duration::from_millis(10)); - } + wait(&mut app); let report = app.cpp_checks.report.as_ref().unwrap(); assert!(report.contains("warning: test")); assert!(report.contains("checked:")); @@ -232,11 +237,7 @@ fn cpplint_findings_show_in_the_editor_until_the_text_changes() { app.cpp_checks.settings.cpplint = true; app.cpp_checks.settings.cpplint_path = executable.display().to_string(); app.run_cpp_check(Tool::Cpplint); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while app.cpp_checks.pending.is_some() && std::time::Instant::now() < deadline { - app.poll_cpp_check(); - std::thread::sleep(std::time::Duration::from_millis(10)); - } + wait(&mut app); let findings = app.cpplint_diagnostics(); assert_eq!(findings.len(), 1); assert_eq!(findings[0].range, 0..13, "the code of `int main() {{}}`"); @@ -258,3 +259,68 @@ fn cpplint_findings_show_in_the_editor_until_the_text_changes() { press(&mut app, KeyCode::Char('x')); assert!(app.cpplint_diagnostics().is_empty()); } + +#[cfg(unix)] +#[test] +fn checks_in_an_open_project_run_from_its_folder() { + use std::{ffi::OsStr, os::unix::fs::PermissionsExt}; + let dir = Directory::new(); + let root = dir.0.canonicalize().unwrap(); + std::fs::create_dir_all(root.join("build")).unwrap(); + for file in [ + "CPPLINT.cfg", + ".clang-format", + "build/compile_commands.json", + ] { + std::fs::write(root.join(file), "").unwrap(); + } + let mut app = cpp_app(&dir); + + // C-c C-p a tells which config files the project has. + app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); + app.handle_key(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL)); + press(&mut app, KeyCode::Char('a')); + app.handle_paste(root.display().to_string()); + press(&mut app, KeyCode::Enter); + assert_eq!( + app.status_bar_text, + "C/C++ config files: CPPLINT.cfg, .clang-format, build/compile_commands.json" + ); + + // Cpplint runs from the project and names header guards after it. + let executable = root.join("cpplint"); + let script = "#!/bin/sh\nprintf 'cwd: %s\\n' \"$(pwd -P)\"\nprintf 'arg: %s\\n' \"$@\"\n"; + std::fs::write(&executable, script).unwrap(); + std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap(); + app.cpp_checks.settings.cpplint = true; + app.cpp_checks.settings.cpplint_path = executable.display().to_string(); + app.run_cpp_check(Tool::Cpplint); + wait(&mut app); + let file = root.join("test.cpp"); + let report = app.cpp_checks.report.as_ref().unwrap(); + assert!( + report.contains(&format!("cwd: {}\n", root.display())), + "{report}" + ); + let args = format!( + "arg: --repository={}\narg: {}\n", + root.display(), + file.display() + ); + assert!(report.contains(&args), "{report}"); + + // clang-tidy gets the compile database in build/. + let tidy = project::command(Tool::Tidy, "clang-tidy", &file, Some(&root)); + assert_eq!(tidy.get_current_dir(), Some(root.as_path())); + let build = root.join("build"); + let args: Vec<_> = tidy.get_args().collect(); + assert_eq!( + args, + [OsStr::new("-p"), build.as_os_str(), file.as_os_str()] + ); + + // A file outside the project is checked as before. + let outside = project::command(Tool::Cpplint, "cpplint", &file, Some(&build)); + assert_eq!(outside.get_current_dir(), None); + assert_eq!(outside.get_args().collect::>(), [file.as_os_str()]); +} diff --git a/src/buffers/sidebar.rs b/src/buffers/sidebar.rs index 399eab9..585280e 100644 --- a/src/buffers/sidebar.rs +++ b/src/buffers/sidebar.rs @@ -38,6 +38,8 @@ pub(crate) struct Sidebar { pub(crate) prefix: Option, // The folder typed after C-c C-p a, while the prompt is open. pub(crate) project_input: Option, + // The folder opened with C-c C-p a. C/C++ checks of files inside it run from there. + pub(crate) project: Option, root: PathBuf, // Folders that show their content. expanded: HashSet, @@ -283,7 +285,14 @@ impl App { .filter(|dir| dir.is_dir()); if let Some(dir) = dir { self.sidebar.project_input = None; - self.status_bar_text.clear(); + // Tell which config files the project has. + let found = crate::buffers::cpp_checks::config_files(&dir); + self.status_bar_text = if found.is_empty() { + String::new() + } else { + format!("C/C++ config files: {}", found.join(", ")) + }; + self.sidebar.project = Some(dir.clone()); self.show_sidebar(dir); } else { self.status_bar_text = "No such folder".into(); diff --git a/src/buffers/sidebar/tests.rs b/src/buffers/sidebar/tests.rs index b90da1d..83b328d 100644 --- a/src/buffers/sidebar/tests.rs +++ b/src/buffers/sidebar/tests.rs @@ -201,6 +201,7 @@ fn ctrl_c_ctrl_p_a_opens_a_project_that_stays() { assert_eq!(app.buffer.editor.get_content(), "a.txt"); assert!(app.sidebar.project_input.is_none() && app.sidebar.focused); assert_eq!(app.sidebar.root, src); + assert_eq!(app.sidebar.project.as_ref(), Some(&src)); assert_eq!(rows(&app), ["inner", "main.rs"]); // The tree keeps the project while the open file is inside it. From b247a6fa47aea44633aefe713cd936d9b337aed5 Mon Sep 17 00:00:00 2001 From: CharOfString Date: Sat, 17 Oct 2026 23:23:20 -0500 Subject: [PATCH 4/5] feat: Open directory as project in arguments --- README.md | 6 ++++- README.zh.md | 6 ++++- src/buffers/sidebar.rs | 22 +++++++++------- src/main.rs | 57 ++++++++++++++++++++++++++++-------------- 4 files changed, 61 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 4beb2c6..5865107 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,11 @@ To open an existing file in the editor buffer, pass its relative or absolute pat ```shell $ cargo run -- README.md ``` -Directories and multiple arguments are rejected. +A folder opens as a project, as `Ctrl + C` `Ctrl + P` `A` does: +```shell +$ cargo run -- src +``` +Multiple arguments are rejected. ### Packaging #### Debian diff --git a/README.zh.md b/README.zh.md index 6c8e0a7..2d6468a 100644 --- a/README.zh.md +++ b/README.zh.md @@ -80,7 +80,11 @@ $ cargo run ```bash $ cargo run -- README.md ``` -同时传入多个文件、传入目录会被`ptre`拒绝 +传入目录时会将其作为项目打开,效果与 `Ctrl + C` `Ctrl + P` `A` 相同: +```bash +$ cargo run -- src +``` +同时传入多个路径会被`ptre`拒绝 ### 打包 #### Debian diff --git a/src/buffers/sidebar.rs b/src/buffers/sidebar.rs index 585280e..d6ea023 100644 --- a/src/buffers/sidebar.rs +++ b/src/buffers/sidebar.rs @@ -268,6 +268,17 @@ impl App { self.status_bar_text = "Enter a folder path".into(); } + // Open directory as project. + pub(crate) fn open_project(&mut self, dir: PathBuf) { + // Tell which config files the project has. + let found = crate::buffers::cpp_checks::config_files(&dir); + if !found.is_empty() { + self.status_bar_text = format!("C/C++ config files: {}", found.join(", ")); + } + self.sidebar.project = Some(dir.clone()); + self.show_sidebar(dir); + } + // Keys of the open project prompt. Returns true while the prompt is open. fn handle_project_input(&mut self, key: KeyEvent) -> bool { let Some(input) = &mut self.sidebar.project_input else { @@ -285,15 +296,8 @@ impl App { .filter(|dir| dir.is_dir()); if let Some(dir) = dir { self.sidebar.project_input = None; - // Tell which config files the project has. - let found = crate::buffers::cpp_checks::config_files(&dir); - self.status_bar_text = if found.is_empty() { - String::new() - } else { - format!("C/C++ config files: {}", found.join(", ")) - }; - self.sidebar.project = Some(dir.clone()); - self.show_sidebar(dir); + self.status_bar_text.clear(); + self.open_project(dir); } else { self.status_bar_text = "No such folder".into(); } diff --git a/src/main.rs b/src/main.rs index 48b59e0..15eb670 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,6 +29,15 @@ fn main() -> io::Result<()> { let mut app = App::default(); app.load_cpp_preferences(); + // Open the passed in file, or the passed in folder as a project, if any. + if let Some(path) = path_argument(std::env::args_os().skip(1))? { + if path.is_dir() { + app.open_project(path.canonicalize()?); + } else { + app.buffer.open(path)?; + } + } + // Language server plugins; a broken plugin file is reported but does not stop ptre. let (plugins, errors) = lsp::load_plugins(); app.completion.set_plugins(plugins); @@ -36,11 +45,6 @@ fn main() -> io::Result<()> { app.status_bar_text = format!("Plugin error: {error}"); } - // Attempt to open the passed in file, if any. - if let Some(path) = file_argument(std::env::args_os().skip(1))? { - app.buffer.open(path)?; - } - ratatui::run(|terminal| { // Ask the terminal emulator to send pasted text in one piece, not as single keys. execute!(io::stdout(), EnableBracketedPaste)?; @@ -50,28 +54,28 @@ fn main() -> io::Result<()> { }) } -// Validate the file arguments -fn file_argument(mut args: impl Iterator) -> io::Result> { +// Validate the path arguments +fn path_argument(mut args: impl Iterator) -> io::Result> { // Read first argument let Some(argument) = args.next() else { return Ok(None); }; - // We only allow to open one file for each instance. + // We only allow to open one file or folder for each instance. if args.next().is_some() { return Err(io::Error::new( io::ErrorKind::InvalidInput, - "Only one file is allowed.", + "Only one path is allowed.", )); } - // Check if that is an actual file. - // TODO: To allow directories ONCE AFTER we implemented workspace feature. + // Check if that is an actual file or folder. let path = PathBuf::from(argument); - if !std::fs::metadata(&path)?.is_file() { + let metadata = std::fs::metadata(&path)?; + if !metadata.is_file() && !metadata.is_dir() { return Err(io::Error::new( io::ErrorKind::InvalidInput, - "Only regular file (NOT a directory) is allowed.", + "Only a regular file or a folder is allowed.", )); } Ok(Some(path)) @@ -85,7 +89,7 @@ mod tests { fn accepts_relative_and_absolute_file_paths_and_opens_them() { let absolute = std::env::current_dir().unwrap().join("README.md"); for name in ["Cargo.toml".into(), "src/main.rs".into(), absolute] { - let path = file_argument([name.into_os_string()].into_iter()) + let path = path_argument([name.into_os_string()].into_iter()) .unwrap() .unwrap(); let mut app = App::default(); @@ -99,17 +103,32 @@ mod tests { } #[test] - fn rejects_directories_missing_files_and_extra_arguments() { - for name in ["src", ".", "missing-file"] { + fn folders_open_as_projects() { + let src = std::env::current_dir().unwrap().join("src"); + for name in ["src", "src/", "./src"] { + let path = path_argument([OsString::from(name)].into_iter()) + .unwrap() + .unwrap(); + let mut app = App::default(); + app.open_project(path.canonicalize().unwrap()); + assert_eq!(app.sidebar.project.as_ref(), Some(&src), "{name}"); + assert!(app.sidebar.visible && app.sidebar.focused, "{name}"); + assert_eq!(app.buffer.path, None, "{name}"); + } + } + + #[test] + fn rejects_missing_paths_devices_and_extra_arguments() { + for name in ["missing-file", "/dev/null"] { assert!( - file_argument([OsString::from(name)].into_iter()).is_err(), + path_argument([OsString::from(name)].into_iter()).is_err(), "{name}" ); } assert!( - file_argument([OsString::from("Cargo.toml"), OsString::from("README.md")].into_iter()) + path_argument([OsString::from("Cargo.toml"), OsString::from("README.md")].into_iter()) .is_err() ); - assert!(file_argument(std::iter::empty()).unwrap().is_none()); + assert!(path_argument(std::iter::empty()).unwrap().is_none()); } } From 7670cfbafe889cacce3766d5dfc81696e53f3ce9 Mon Sep 17 00:00:00 2001 From: CharOfString Date: Sun, 18 Oct 2026 01:14:16 -0500 Subject: [PATCH 5/5] enhance: Tab style --- src/app/tests.rs | 2 +- src/buffers/tabs.rs | 51 ++++++++++++++++++++++++++++++++------- src/buffers/tabs/tests.rs | 48 +++++++++++++++++++++++++++--------- 3 files changed, 80 insertions(+), 21 deletions(-) diff --git a/src/app/tests.rs b/src/app/tests.rs index 7c427e8..ad239ee 100644 --- a/src/app/tests.rs +++ b/src/app/tests.rs @@ -199,7 +199,7 @@ fn renders_editor_and_updated_shortcuts() { assert_eq!(app.editor_area, Rect::new(1, 4, 98, 15)); let screen = terminal.backend().buffer(); let tabs: String = (0..100).map(|x| screen[(x, 3)].symbol()).collect(); - assert!(tabs.starts_with("│❃ [No Name] ●")); + assert!(tabs.starts_with("│ ❃ [No Name] ●")); let title: String = (0..100).map(|x| screen[(x, 2)].symbol()).collect(); assert!(title.starts_with("╭─ [No Name] · DIRTY BUFFER")); assert!(title.contains("· DIRTY BUFFER")); diff --git a/src/buffers/tabs.rs b/src/buffers/tabs.rs index 0604bf3..24b200c 100644 --- a/src/buffers/tabs.rs +++ b/src/buffers/tabs.rs @@ -19,7 +19,7 @@ use crate::app::App; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use ratatui::{ Frame, - layout::Rect, + layout::{Margin, Rect}, style::{Color, Modifier, Style}, text::{Line, Span}, widgets::Paragraph, @@ -47,8 +47,7 @@ fn name(buffer: &Buffer) -> String { name.map_or_else(|| "[No Name]".into(), |name| name.to_string_lossy().into()) } -// One tab, drawn like a name in the menu bar: "❃" marks the active tab. -// A dot marks unsaved changes. +// Single tab. fn tab(buffer: &Buffer, active: bool) -> Vec> { let (marker, style) = if active { ( @@ -58,7 +57,12 @@ fn tab(buffer: &Buffer, active: bool) -> Vec> { } else { (" ", Style::default().fg(MUTED)) }; - let mut spans = vec![Span::styled(format!("{marker}{}", name(buffer)), style)]; + + let mut spans = vec![ + Span::styled(marker, style), + Span::styled(name(buffer), style), + ]; + if buffer.is_dirty() { spans.push(Span::styled(" ●", Style::default().fg(AMBER))); } @@ -161,19 +165,48 @@ impl App { } pub(crate) fn draw_tabs(&self, frame: &mut Frame, area: Rect) { + let area = area.inner(Margin::new(1, 0)); let active = self.tabs.left.len(); - let tabs: Vec<_> = self + let mut tabs: Vec<_> = self .tab_buffers() .enumerate() .map(|(index, buffer)| tab(buffer, index == active)) .collect(); - // Leave out tabs on the left until the active tab fits. - let width = |tabs: &[Vec]| tabs.iter().flatten().map(Span::width).sum::(); + + let fits = |first: usize, last: usize| { + let mut width: usize = tabs[first..=last].iter().flatten().map(Span::width).sum(); + if first > 0 && first == active { + width += 2; + } + + if last + 1 == tabs.len() { + width -= 2; + } + width <= usize::from(area.width) + }; + let mut first = 0; - while first < active && width(&tabs[first..=active]) > usize::from(area.width) { + while first < active && !fits(first, active) { first += 1; } - let spans: Vec<_> = tabs.into_iter().skip(first).flatten().collect(); + + let mut last = active; + while last + 1 < tabs.len() && fits(first, last + 1) { + last += 1; + } + + let arrow = |text| Span::styled(text, Style::default().fg(MUTED)); + if last + 1 < tabs.len() { + *tabs[last].last_mut().unwrap() = arrow(" →"); + } + + if first > 0 && first == active { + tabs[first].insert(0, arrow("← ")); + } else if first > 0 { + tabs[first][0] = arrow("← "); + } + + let spans: Vec<_> = tabs.drain(first..=last).flatten().collect(); frame.render_widget(Paragraph::new(Line::from(spans)), area); } } diff --git a/src/buffers/tabs/tests.rs b/src/buffers/tabs/tests.rs index 4f1daee..3b7c2d0 100644 --- a/src/buffers/tabs/tests.rs +++ b/src/buffers/tabs/tests.rs @@ -102,6 +102,17 @@ fn closing_a_tab_with_changes_asks_first() { assert!(app.buffer.path.is_none()); } +// Tab row +fn row(app: &App, width: u16) -> (String, ratatui::buffer::Buffer) { + let mut terminal = Terminal::new(TestBackend::new(width, 1)).unwrap(); + terminal + .draw(|frame| app.draw_tabs(frame, frame.area())) + .unwrap(); + let screen = terminal.backend().buffer().clone(); + let row = (0..width).map(|x| screen[(x, 0)].symbol()).collect(); + (row, screen) +} + #[test] fn tab_row_keeps_the_active_tab_in_view() { let mut app = App::default(); @@ -109,17 +120,32 @@ fn tab_row_keeps_the_active_tab_in_view() { app.open_tab(path.into()).unwrap(); } app.buffer.editor.set_content("changed"); - let mut terminal = Terminal::new(TestBackend::new(30, 1)).unwrap(); - terminal - .draw(|frame| app.draw_tabs(frame, frame.area())) - .unwrap(); - let screen = terminal.backend().buffer(); - let row: String = (0..30).map(|x| screen[(x, 0)].symbol()).collect(); - assert!(row.starts_with(" main.rs ❃ app.rs ● "), "{row}"); + let (row, screen) = row(&app, 30); + assert!(row.starts_with(" ← main.rs ❃ app.rs ● "), "{row}"); // The active tab is bold light blue, the others are dimmer, and the dot is amber. - assert_eq!(screen[(13, 0)].fg, LIGHT_BLUE); - assert!(screen[(13, 0)].modifier.contains(Modifier::BOLD)); - assert_eq!(screen[(2, 0)].fg, MUTED); - assert_eq!(screen[(20, 0)].fg, AMBER); + assert_eq!(screen[(14, 0)].fg, LIGHT_BLUE); + assert!(screen[(14, 0)].modifier.contains(Modifier::BOLD)); + assert_eq!(screen[(1, 0)].fg, MUTED); + assert_eq!(screen[(3, 0)].fg, MUTED); + assert_eq!(screen[(21, 0)].fg, AMBER); assert!(screen.content.iter().all(|cell| cell.bg == Color::Reset)); } + +#[test] +fn arrows_mark_hidden_tabs_and_padding_surrounds_the_row() { + let mut app = App::default(); + for path in ["Cargo.toml", "README.md", "src/main.rs", "src/app.rs"] { + app.open_tab(path.into()).unwrap(); + } + // All tabs fit: only the padding is added. + assert_eq!( + row(&app, 50).0, + " Cargo.toml README.md main.rs ❃ app.rs " + ); + chord(&mut app, KeyCode::Left); + chord(&mut app, KeyCode::Left); + assert_eq!(row(&app, 30).0, " Cargo.toml ❃ README.md → "); + // "← " needs its own room before the active tab. + chord(&mut app, KeyCode::Right); + assert_eq!(row(&app, 20).0, " ← ❃ main.rs → "); +}