diff --git a/AGENTS.md b/AGENTS.md index 0283882..dc1a674 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,3 +7,4 @@ - Comments must be written in English; please use simple English so that non-native English speakers can understand them. If you need to update the documentation, do so in the respective language of each document. - The goal of the code is to be human-readable and maintainable; use this as the foundation to complete your task. - Please refer to `CODE_OF_CONDUCT.md` and `CONTRIBUTING.md`; all requirements applicable to human contributors and AI policies apply to you as well. +- Your comment should NOT contain Markdown elements. diff --git a/doc/shortcuts/shortcuts.md b/doc/shortcuts/shortcuts.md index ff940d2..b603c0b 100644 --- a/doc/shortcuts/shortcuts.md +++ b/doc/shortcuts/shortcuts.md @@ -10,3 +10,6 @@ * **Complete** (open/close the completion popup): `Alt + /`. * **Toggle auto completion**: `Ctrl + C` `Alt + L`. * **Apply autofix**: `Ctrl + C` `A`. +* **Search forward / backward**: `Ctrl + S` / `Ctrl + R`. (`Enter` to stop, `Ctrl + G` to go back.) +* **Query replace**: `Alt + %`. Then answer at each match: `Y`/`Space` replace, `N` skip, `!` replace all, `.` replace and stop, `Q` stop. +* **Go to line**: `Alt + G` `G` (or `Alt + G` `Alt + G`). diff --git a/doc/shortcuts/shortcuts.zh.md b/doc/shortcuts/shortcuts.zh.md index 3912e42..1426d19 100644 --- a/doc/shortcuts/shortcuts.zh.md +++ b/doc/shortcuts/shortcuts.zh.md @@ -9,3 +9,6 @@ * **补全列表**: `Alt + /`. * **自动补全**: `Ctrl + C` `Alt + L`. * **自动修复**: `Ctrl + C` `A`. +* **向前 / 向后查找**: `Ctrl + S` / `Ctrl + R`. (`Enter`结束,`Ctrl + G`回到起点) +* **逐个替换**: `Alt + %`. (`Y`/`空格`替换,`N`跳过,`!`全部替换,`.`替换后结束,`Q`结束) +* **跳转到行**: `Alt + G` `G` (或`Alt + G` `Alt + G`). diff --git a/src/app.rs b/src/app.rs index d594fa3..f612f07 100644 --- a/src/app.rs +++ b/src/app.rs @@ -39,6 +39,10 @@ pub(crate) struct App { pub(crate) cpp_checks: crate::buffers::cpp_checks::Checks, pub(crate) completion: crate::buffers::completion::Completion, pub(crate) quick_fix: crate::buffers::fixes::QuickFix, + pub(crate) search: crate::buffers::search::Search, + pub(crate) goto_line: crate::buffers::goto_line::GotoLine, + // Draw icons from a Nerd Font (WINDOW menu). + pub(crate) nerd_font: bool, } // Implementation of the app struct @@ -87,6 +91,7 @@ impl App { let prefix = match (self.ctrl_x_wait_flag, self.ctrl_c_wait_flag) { (true, _) => "C-x ", (_, true) => "C-c ", + _ if self.goto_line.after_prefix() => "M-g ", _ => "", }; self.buffer_command = crate::utils::keys::shortcut_label(key, !prefix.is_empty()) @@ -159,7 +164,13 @@ impl App { return; } - if !self.ctrl_x_wait_flag && self.menu.active.is_none() && self.handle_completion_key(key) { + // Search and replace see keys before completion. + if !self.ctrl_x_wait_flag + && self.menu.active.is_none() + && (self.handle_search_key(key) + || self.handle_goto_line_key(key) + || self.handle_completion_key(key)) + { return; } diff --git a/src/buffers/diagnostics/inline.rs b/src/buffers/diagnostics/inline.rs index 65d4180..81f99fc 100644 --- a/src/buffers/diagnostics/inline.rs +++ b/src/buffers/diagnostics/inline.rs @@ -12,7 +12,7 @@ // You should have received a copy of the GNU General Public License along with this software. If // not, see . -use super::color; +use super::{color, nerd_icon}; use crate::{app::App, lsp::Diagnostic}; use ratatui::{ Frame, @@ -57,7 +57,12 @@ impl App { let Some(worst) = on_line.iter().map(|d| d.severity).min() else { continue; }; - buf[(area.left(), y)].set_symbol("●").set_fg(color(worst)); + let mark = if self.nerd_font { + nerd_icon(worst) + } else { + "●" + }; + buf[(area.left(), y)].set_symbol(mark).set_fg(color(worst)); // Underline marked chars, up to the first cell after the text of the line. let mut end_x = None; @@ -148,5 +153,11 @@ mod tests { assert!(row(y + 2).contains("z unused 'z'")); assert_eq!(screen[(area.left(), y + 3)].symbol(), " "); assert!(!row(y + 3).contains("unused")); + + app.nerd_font = true; + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + assert_eq!(screen[(area.left(), y)].symbol(), "\u{f057}"); + assert_eq!(screen[(area.left(), y + 2)].symbol(), "\u{f071}"); } } diff --git a/src/buffers/diagnostics/mod.rs b/src/buffers/diagnostics/mod.rs index 5307d6f..679a5fa 100644 --- a/src/buffers/diagnostics/mod.rs +++ b/src/buffers/diagnostics/mod.rs @@ -44,6 +44,15 @@ impl App { } // Coloring config for the status bar. +pub(super) fn nerd_icon(severity: Severity) -> &'static str { + match severity { + Severity::Error => "\u{f057}", + Severity::Warning => "\u{f071}", + Severity::Information => "\u{f05a}", + Severity::Hint => "\u{f0eb}", + } +} + pub(super) fn color(severity: Severity) -> Color { match severity { Severity::Error => Color::LightRed, diff --git a/src/buffers/editor_status.rs b/src/buffers/editor_status.rs index b122cb3..bd69f3e 100644 --- a/src/buffers/editor_status.rs +++ b/src/buffers/editor_status.rs @@ -12,7 +12,10 @@ // You should have received a copy of the GNU General Public License along with this software. If // not, see . -use super::{diagnostics::color, menu::LIGHT_BLUE}; +use super::{ + diagnostics::{color, nerd_icon}, + menu::LIGHT_BLUE, +}; use crate::lsp::Severity; use ratatui::{ Frame, @@ -57,12 +60,21 @@ fn labels(editor: &Editor) -> (String, String) { } // The error/warning indicator. -fn problem_spans((errors, warnings): (usize, usize)) -> [Span<'static>; 4] { +// In Nerd Font mode the letters are replaced with the severity icons. +fn problem_spans((errors, warnings): (usize, usize), nerd_font: bool) -> [Span<'static>; 4] { + let label = |severity, letter, count| { + let span = if nerd_font { + format!("{} {count}", nerd_icon(severity)) + } else { + format!("{letter}: {count}") + }; + Span::styled(span, color(severity)) + }; let separator = Span::styled(" · ", Style::default().fg(LIGHT_BLUE)); [ - Span::styled(format!("E: {errors}"), color(Severity::Error)), + label(Severity::Error, 'E', errors), separator.clone(), - Span::styled(format!("W: {warnings}"), color(Severity::Warning)), + label(Severity::Warning, 'W', warnings), separator, ] } @@ -71,6 +83,7 @@ fn problem_spans((errors, warnings): (usize, usize)) -> [Span<'static>; 4] { pub(super) fn draw( editor: &Editor, problems: (usize, usize), + nerd_font: bool, frame: &mut Frame, area: Rect, border_area: Rect, @@ -92,7 +105,7 @@ pub(super) fn draw( let area = Rect::new(area.x, area.y + 1, area.width, 1); let (left, right) = labels(editor); - let mut right_line = Line::from(problem_spans(problems).to_vec()); + let mut right_line = Line::from(problem_spans(problems, nerd_font).to_vec()); right_line.push_span(right); let right_width = u16::try_from(right_line.width()).unwrap_or(u16::MAX); @@ -137,12 +150,19 @@ mod tests { #[test] fn problems_show_errors_in_red_and_warnings_in_yellow() { - let spans = problem_spans((2, 11)); + let spans = problem_spans((2, 11), false); let text: String = spans.iter().map(|span| span.content.as_ref()).collect(); assert_eq!(text, "E: 2 · W: 11 · "); assert_eq!(spans[0].style.fg, Some(Color::LightRed)); assert_eq!(spans[1].style.fg, Some(LIGHT_BLUE)); assert_eq!(spans[2].style.fg, Some(Color::Yellow)); + + // Nerd Font mode puts the icons in place of the letters, in the same colors. + let spans = problem_spans((2, 11), true); + let text: String = spans.iter().map(|span| span.content.as_ref()).collect(); + assert_eq!(text, "\u{f057} 2 · \u{f071} 11 · "); + assert_eq!(spans[0].style.fg, Some(Color::LightRed)); + assert_eq!(spans[2].style.fg, Some(Color::Yellow)); } #[test] diff --git a/src/buffers/goto_line.rs b/src/buffers/goto_line.rs new file mode 100644 index 0000000..2557f0a --- /dev/null +++ b/src/buffers/goto_line.rs @@ -0,0 +1,246 @@ +// 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 . + +//! Go to line (M-g g or M-g M-g, as in Emacs). + +use super::menu::LIGHT_BLUE; +use crate::app::App; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use ratatui::{ + Frame, + layout::Rect, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, BorderType, Clear, Padding, Paragraph}, +}; + +#[derive(Default)] +pub(crate) struct GotoLine { + // M-g was pressed. + prefix: bool, + + // The typed line number while the dialog is open. + input: Option, +} + +impl GotoLine { + pub(crate) fn after_prefix(&self) -> bool { + self.prefix + } + + pub(crate) fn is_open(&self) -> bool { + self.input.is_some() + } + + // True while M-g waits for its next key or the dialog is open. + pub(crate) fn is_busy(&self) -> bool { + self.prefix || self.is_open() + } +} + +impl App { + // Keys of M-g g and of the dialog. Returns true when the key was used. + pub(crate) fn handle_goto_line_key(&mut self, key: KeyEvent) -> bool { + let alt = key.modifiers == KeyModifiers::ALT; + if let Some(input) = &mut self.goto_line.input { + match key.code { + KeyCode::Char(c) if c.is_ascii_digit() && key.modifiers.is_empty() => input.push(c), + KeyCode::Backspace => { + input.pop(); + } + KeyCode::Enter => self.go_to_typed_line(), + KeyCode::Esc => self.goto_line.input = None, + KeyCode::Char('g') if key.modifiers == KeyModifiers::CONTROL => { + self.goto_line.input = None; + } + + // The dialog keeps every other key until it closes. + _ => {} + } + return true; + } + if std::mem::take(&mut self.goto_line.prefix) { + // M-g g and M-g M-g open the dialog; other keys after M-g do nothing. + if key.code == KeyCode::Char('g') && (key.modifiers.is_empty() || alt) { + self.completion.close(); + self.goto_line.input = Some(String::new()); + } + return true; + } + + // C-c chords belong to completion and the checks. + if key.code == KeyCode::Char('g') && alt && !self.ctrl_c_wait_flag { + self.goto_line.prefix = true; + return true; + } + false + } + + fn go_to_typed_line(&mut self) { + let typed = self.goto_line.input.take().unwrap_or_default(); + + // Nothing typed closes the dialog. + let Ok(number) = typed.parse::() else { + return; + }; + + // Like Emacs, 0 goes to the first line and numbers past the end to the last one. + let code = self.buffer.editor.code_ref(); + let index = number + .saturating_sub(1) + .min(code.len_lines().saturating_sub(1)); + let start = code.line_to_char(index); + self.buffer.editor.set_selection(None); + self.buffer.editor.set_cursor(start); + self.buffer.editor.focus(&self.editor_area); + } + + // The dialog, in the middle of the screen. + pub(crate) fn draw_goto_line(&self, frame: &mut Frame) { + let Some(input) = &self.goto_line.input else { + return; + }; + let lines = self.buffer.editor.code_ref().len_lines(); + let base = Style::default().fg(LIGHT_BLUE); + let text = vec![ + Line::from(vec![ + Span::styled(format!("Line (1-{lines}): "), base), + Span::styled(format!("{input}█"), base.add_modifier(Modifier::BOLD)), + ]), + Line::styled("Enter: go Esc: cancel", base.add_modifier(Modifier::DIM)), + ]; + + // Borders and one column of padding on each side take four columns. + let area = frame.area(); + let width = text.iter().map(Line::width).max().unwrap_or(0) as u16 + 4; + let width = width.max(TITLE.len() as u16 + 2).min(area.width); + let height = (text.len() as u16 + 2).min(area.height); + let popup = Rect::new( + area.x + (area.width - width) / 2, + area.y + (area.height - height) / 2, + width, + height, + ); + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(base) + .title(TITLE) + .padding(Padding::horizontal(1)); + frame.render_widget(Clear, popup); + frame.render_widget(Paragraph::new(text).block(block), popup); + } +} + +const TITLE: &str = " Go to line "; + +#[cfg(test)] +mod tests { + use super::*; + use ratatui::{Terminal, backend::TestBackend}; + + fn press(app: &mut App, code: KeyCode, modifiers: KeyModifiers) { + app.handle_key(KeyEvent::new(code, modifiers)); + } + + fn goto(app: &mut App, typed: &str) { + press(app, KeyCode::Char('g'), KeyModifiers::ALT); + press(app, KeyCode::Char('g'), KeyModifiers::NONE); + for c in typed.chars() { + press(app, KeyCode::Char(c), KeyModifiers::NONE); + } + press(app, KeyCode::Enter, KeyModifiers::NONE); + } + + fn app_with(text: &str) -> App { + let mut app = App::default(); + app.editor_area = Rect::new(1, 1, 78, 22); + app.buffer.editor.set_content(text); + app + } + + #[test] + fn goes_to_the_start_of_the_line_and_clamps_like_emacs() { + let mut app = app_with("one\ntwo\nthree\nfour"); + goto(&mut app, "3"); + assert_eq!(app.buffer.editor.get_cursor(), 8); + assert!(!app.goto_line.is_open()); + goto(&mut app, "99"); + assert_eq!(app.buffer.editor.get_cursor(), 14, "last line"); + goto(&mut app, "0"); + assert_eq!(app.buffer.editor.get_cursor(), 0, "first line"); + assert_eq!(app.buffer.editor.get_content(), "one\ntwo\nthree\nfour"); + } + + #[test] + fn dialog_takes_only_digits_and_can_be_cancelled() { + let mut app = app_with("a\nb\nc"); + app.buffer.editor.set_cursor(2); + + // M-g M-g works too; letters are ignored and Backspace edits the number. + press(&mut app, KeyCode::Char('g'), KeyModifiers::ALT); + assert_eq!(app.buffer_command, "M-g"); + press(&mut app, KeyCode::Char('g'), KeyModifiers::ALT); + assert_eq!(app.buffer_command, "M-g M-g"); + assert!(app.goto_line.is_open()); + for code in [KeyCode::Char('x'), KeyCode::Char('3'), KeyCode::Backspace] { + press(&mut app, code, KeyModifiers::NONE); + } + press(&mut app, KeyCode::Esc, KeyModifiers::NONE); + assert!(!app.goto_line.is_open()); + assert_eq!(app.buffer.editor.get_cursor(), 2); + assert_eq!(app.buffer.editor.get_content(), "a\nb\nc"); + + // Enter with nothing typed only closes; M-g with another key does nothing. + goto(&mut app, ""); + assert_eq!(app.buffer.editor.get_cursor(), 2); + press(&mut app, KeyCode::Char('g'), KeyModifiers::ALT); + press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE); + assert!(!app.goto_line.is_busy()); + assert_eq!(app.buffer.editor.get_content(), "a\nb\nc"); + } + + #[test] + fn m_g_ends_an_incremental_search_first() { + let mut app = app_with("a\nb\nc"); + press(&mut app, KeyCode::Char('s'), KeyModifiers::CONTROL); + press(&mut app, KeyCode::Char('b'), KeyModifiers::NONE); + goto(&mut app, "3"); + assert!(app.search.prompt().is_none()); + assert_eq!(app.buffer.editor.get_cursor(), 4); + + // While the dialog is open, C-s does not start a search. + press(&mut app, KeyCode::Char('g'), KeyModifiers::ALT); + press(&mut app, KeyCode::Char('g'), KeyModifiers::NONE); + press(&mut app, KeyCode::Char('s'), KeyModifiers::CONTROL); + assert!(app.search.prompt().is_none()); + assert!(app.goto_line.is_open()); + } + + #[test] + fn dialog_is_drawn_in_the_middle() { + let mut app = app_with("1\n2\n3\n4"); + press(&mut app, KeyCode::Char('g'), KeyModifiers::ALT); + press(&mut app, KeyCode::Char('g'), KeyModifiers::NONE); + press(&mut app, KeyCode::Char('2'), KeyModifiers::NONE); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + let rows: Vec = (0..24) + .map(|y| (0..80).map(|x| screen[(x, y)].symbol()).collect()) + .collect(); + assert!(rows[10].contains("╭ Go to line"), "{}", rows[10]); + assert!(rows[11].contains("│ Line (1-4): 2█"), "{}", rows[11]); + assert!(rows[12].contains("Enter: go Esc: cancel")); + } +} diff --git a/src/buffers/menu.rs b/src/buffers/menu.rs deleted file mode 100644 index fd84630..0000000 --- a/src/buffers/menu.rs +++ /dev/null @@ -1,539 +0,0 @@ -// 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::cpp_checks::{Tool, settings::Settings}; -use crate::app::App; -use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; -use ratatui::{ - Frame, - layout::Rect, - style::{Color, Modifier, Style}, - text::{Line, Span}, - widgets::{Block, BorderType, Clear, List, ListItem, ListState, Paragraph}, -}; - -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 EDIT: &[(&str, &str)] = &[ - ("Undo", "C-x u"), - ("Redo", "C-M-_"), - ("Cut", "C-w"), - ("Copy", "M-w"), - ("Paste", "C-y"), -]; - -const MENUS: [&str; 4] = ["FILE", "EDIT", "LSP", "C/C++"]; -const CPP_MENU: usize = 3; - -// C/C++ menu only shows if current active buffer is in C/C++ mode. -fn menus(cpp: bool) -> &'static [&'static str] { - if cpp { &MENUS } else { &MENUS[..CPP_MENU] } -} - -// What choosing a C/C++ menu entry does. -#[derive(Clone, Copy)] -enum CppAction { - Toggle(Tool), - Run(Tool), -} - -// C/C++ menu entries. A "Run" entry only shows when its check can run. -fn cpp_entries(settings: &Settings) -> Vec<(&'static str, &'static str, CppAction)> { - let tidy = if settings.tidy { - "Clang-tidy: On" - } else { - "Clang-tidy: Off" - }; - - let cpplint = if settings.cpplint { - "Cpplint: On" - } else { - "Cpplint: Off" - }; - - let mut entries = vec![ - (tidy, "", CppAction::Toggle(Tool::Tidy)), - (cpplint, "", CppAction::Toggle(Tool::Cpplint)), - ]; - - if settings.tidy { - entries.push(("Run Clang-tidy", "C-c t", CppAction::Run(Tool::Tidy))); - } - - if settings.cpplint_ready() { - entries.push(("Run Cpplint", "C-c l", CppAction::Run(Tool::Cpplint))); - } - entries -} - -// Entries of one menu. -fn items( - menu: usize, - auto_completion: bool, - cpp: Option<&Settings>, -) -> Vec<(&'static str, &'static str)> { - match (menu, cpp) { - (0, _) => FILE.to_vec(), - (1, _) => EDIT.to_vec(), - (2, _) => vec![ - ( - if auto_completion { - "Auto Complete: On" - } else { - "Auto Complete: Off" - }, - "C-c M-l", - ), - ("Complete", "M-/"), - ("Quick Fix", "C-c a"), - ], - (CPP_MENU, Some(settings)) => cpp_entries(settings) - .into_iter() - .map(|(label, shortcut, _)| (label, shortcut)) - .collect(), - _ => Vec::new(), - } -} - -#[derive(Default)] -pub(crate) struct Menu { - pub(crate) active: Option, - selected: usize, -} - -impl Menu { - pub(crate) fn draw_bar(&self, frame: &mut Frame, area: Rect, cpp: bool) { - let base = Style::default().fg(LIGHT_BLUE); - - // App name & version. - let mut spans = vec![ - Span::styled(" PTRE ", base.add_modifier(Modifier::BOLD)), - Span::styled(format!("REL.{} ", env!("CARGO_PKG_VERSION")), base), - ]; - - // App menu - for (index, name) in menus(cpp).iter().enumerate() { - let style = base.add_modifier(Modifier::BOLD); - let indicator = if self.active == Some(index) { - "❃ " - } else { - " " - }; - spans.push(Span::styled(indicator, base)); - spans.push(Span::styled(*name, style)); - spans.push(Span::styled(" ", base)); - } - - if area.height == 0 || area.width == 0 { - return; - } - - let border = if area.width == 1 { - "╭".to_owned() - } else { - format!("╭{}╮", "─".repeat(usize::from(area.width - 2))) - }; - - frame.render_widget( - Paragraph::new(Line::from(spans)).style(base), - Rect::new(area.x, area.y, area.width, 1), - ); - - if area.height > 1 { - frame.render_widget( - Paragraph::new(border).style(base), - Rect::new(area.x, area.y + 1, area.width, 1), - ); - } - } - - // Popup menu. - pub(crate) fn draw_popup( - &self, - frame: &mut Frame, - auto_completion: bool, - cpp: Option<&Settings>, - ) { - let Some(active) = self.active else { return }; - let screen = frame.area(); - let items = items(active, auto_completion, cpp); - - // The C/C++ menu has no entries once the buffer is not C/C++. - if screen.height <= 1 || screen.width == 0 || items.is_empty() { - return; - } - - let label_width = items - .iter() - .map(|(label, _)| label.len()) - .max() - .unwrap_or(0); - - let shortcut_width = items - .iter() - .map(|(_, shortcut)| shortcut.len()) - .max() - .unwrap_or(0); - - // Borders, selection indicator, side padding, and a two-column gap. - let width = (label_width + shortcut_width + 7) as u16; - let width = width.min(screen.width); - // Each menu name takes its length plus four columns of indicator and padding. - let before: usize = MENUS[..active].iter().map(|name| name.len() + 4).sum(); - let offset = (10 + env!("CARGO_PKG_VERSION").len() + before) as u16; - let area = Rect::new( - screen.x + offset.min(screen.width.saturating_sub(width)), - screen.y + 1, - width, - (items.len() as u16 + 2).min(screen.height - 1), - ); - - let rows: Vec<_> = items - .iter() - .map(|(label, shortcut)| { - ListItem::new(format!( - " {label:shortcut_width$} " - )) - }) - .collect(); - - let list = List::new(rows) - .style(Style::default().fg(LIGHT_BLUE)) - .block( - Block::bordered() - .border_type(BorderType::Rounded) - .border_style(Style::default().fg(LIGHT_BLUE)), - ) - .highlight_style(Style::default().fg(LIGHT_BLUE).add_modifier(Modifier::BOLD)) - .highlight_symbol("·"); - frame.render_widget(Clear, area); - frame.render_stateful_widget( - list, - area, - &mut ListState::default().with_selected(Some(self.selected)), - ); - } -} - -impl App { - // Invoke and activated menu. - pub(crate) fn handle_menu_key(&mut self, key: KeyEvent) -> bool { - let requested = match (key.code, key.modifiers) { - (KeyCode::F(10), _) => Some(0), - (KeyCode::Char('f' | 'F'), KeyModifiers::ALT) => Some(0), - (KeyCode::Char('e' | 'E'), KeyModifiers::ALT) => Some(1), - _ => None, - }; - - if let Some(index) = requested { - self.menu.active = if self.menu.active == Some(index) { - None - } else { - Some(index) - }; - self.menu.selected = 0; - return true; - } - - let Some(active) = self.menu.active else { - return false; - }; - - let cpp = self.is_c_or_cpp(); - let count = items(active, true, cpp.then_some(&self.cpp_checks.settings)).len(); - - // Close the C/C++ menu popup after the buffer changed language. - if count == 0 { - self.menu.active = None; - return false; - } - - let menu_count = menus(cpp).len(); - match key.code { - KeyCode::Esc => self.menu.active = None, - KeyCode::Left | KeyCode::Right | KeyCode::Tab => { - let step = if key.code == KeyCode::Left { - menu_count - 1 - } else { - 1 - }; - self.menu.active = Some((active + step) % menu_count); - self.menu.selected = 0; - } - KeyCode::Down => self.menu.selected = (self.menu.selected + 1) % count, - KeyCode::Up => self.menu.selected = (self.menu.selected + count - 1) % count, - KeyCode::Enter => { - let selected = self.menu.selected; - self.menu.active = None; - 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, - )); - } else if active == 2 { - if selected == 0 { - self.handle_key(KeyEvent::new(KeyCode::Char('c'), ctrl)); - self.handle_key(KeyEvent::new(KeyCode::Char('l'), alt)); - } else if selected == 1 { - self.handle_key(KeyEvent::new(KeyCode::Char('/'), alt)); - } else { - self.handle_key(KeyEvent::new(KeyCode::Char('c'), ctrl)); - self.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); - } - } else if active == CPP_MENU { - // selected indexes the same entries the popup showed. - match cpp_entries(&self.cpp_checks.settings)[selected].2 { - CppAction::Toggle(tool) => self.toggle_cpp_check(tool), - CppAction::Run(tool) => self.run_cpp_check(tool), - } - } else { - if selected == 0 { - self.handle_key(KeyEvent::new(KeyCode::Char('x'), ctrl)); - self.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE)); - return true; - } - let (code, modifiers) = - [('_', ctrl | alt), ('w', ctrl), ('w', alt), ('y', ctrl)][selected - 1]; - self.handle_key(KeyEvent::new(KeyCode::Char(code), modifiers)); - } - } - _ => {} - } - true - } -} - -#[cfg(test)] -mod tests { - use super::*; - use ratatui::{Terminal, backend::TestBackend}; - - #[test] - fn cpp_menu_hides_checks_that_cannot_run() { - let mut settings = Settings::default(); - assert_eq!(menus(false), ["FILE", "EDIT", "LSP"]); - assert_eq!(menus(true), ["FILE", "EDIT", "LSP", "C/C++"]); - assert_eq!(items(2, true, Some(&settings)).len(), 3); - let labels = |settings: &Settings| { - let entries = items(CPP_MENU, true, Some(settings)); - entries - .into_iter() - .map(|(label, _)| label) - .collect::>() - }; - assert_eq!(labels(&settings), ["Clang-tidy: Off", "Cpplint: Off"]); - settings.tidy = true; - assert_eq!( - labels(&settings), - ["Clang-tidy: On", "Cpplint: Off", "Run Clang-tidy"] - ); - - // Cpplint also needs an executable file as its path. - settings.cpplint = true; - for path in ["", "/ptre-missing/cpplint", "/", "Cargo.toml"] { - settings.cpplint_path = path.into(); - assert_eq!(labels(&settings).len(), 3, "{path:?}"); - } - settings.cpplint_path = std::env::current_exe().unwrap().display().to_string(); - assert_eq!( - items(CPP_MENU, true, Some(&settings))[3], - ("Run Cpplint", "C-c l") - ); - assert!(items(CPP_MENU, true, None).is_empty()); - assert_eq!(items(0, true, Some(&settings)), FILE); - } - - #[test] - fn cpp_menu_shows_only_for_c_and_cpp_buffers() { - let dir = std::env::temp_dir().join(format!("ptre-menu-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let bar = |app: &mut App| { - let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); - terminal.draw(|frame| app.draw(frame)).unwrap(); - let screen = terminal.backend().buffer(); - (0..80).map(|x| screen[(x, 0)].symbol()).collect::() - }; - for (file, cpp) in [("main.c", true), ("main.cpp", true), ("notes.txt", false)] { - let path = dir.join(file); - std::fs::write(&path, "text").unwrap(); - let mut app = App::default(); - app.buffer.open(path).unwrap(); - assert_eq!(bar(&mut app).contains("C/C++"), cpp, "{file}"); - - // Left from FILE wraps to the last menu shown. - app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); - assert_eq!(app.menu.active, Some(if cpp { CPP_MENU } else { 2 })); - } - - // With "Run Clang-tidy" hidden, the third entry runs Cpplint. - let mut app = App::default(); - app.buffer.open(dir.join("main.c")).unwrap(); - let settings = &mut app.cpp_checks.settings; - settings.cpplint = true; - settings.cpplint_path = std::env::current_exe().unwrap().display().to_string(); - app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(app.status_bar_text, "Running Cpplint…"); - std::fs::remove_dir_all(&dir).unwrap(); - } - - #[test] - fn renders_light_blue_menu_and_separator() { - let mut app = 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 title: String = (0..80).map(|x| screen[(x, 0)].symbol()).collect(); - assert!(title.contains(&format!("PTRE REL.{}", env!("CARGO_PKG_VERSION")))); - assert!(title.contains("FILE")); - assert!(title.contains("EDIT")); - assert_eq!(screen[(0, 0)].bg, Color::Reset); - assert_eq!(screen[(2, 0)].fg, LIGHT_BLUE); - assert_eq!(screen[(0, 1)].symbol(), "╭"); - assert_eq!(screen[(79, 1)].symbol(), "╮"); - for x in 1..79 { - assert_eq!(screen[(x, 1)].symbol(), "─"); - } - for x in 0..80 { - assert!(!screen[(x, 0)].modifier.contains(Modifier::UNDERLINED)); - assert_eq!(screen[(x, 1)].fg, LIGHT_BLUE); - assert_eq!(screen[(x, 1)].bg, Color::Reset); - } - app.menu.active = Some(0); - terminal.draw(|frame| app.draw(frame)).unwrap(); - let screen = terminal.backend().buffer(); - let popup_x = 10 + env!("CARGO_PKG_VERSION").len() as u16; - assert_eq!(screen[(popup_x, 1)].bg, Color::Reset); - assert_eq!(screen[(popup_x, 1)].fg, LIGHT_BLUE); - } - - #[test] - fn active_menu_and_popup_use_markers_without_underlines() { - for active in 0..3 { - let mut app = App::default(); - app.menu.active = Some(active); - let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); - terminal.draw(|frame| app.draw(frame)).unwrap(); - let screen = terminal.backend().buffer(); - let popup_x = 10 + env!("CARGO_PKG_VERSION").len() as u16 + active as u16 * 8; - 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, 31][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(), " "); - for y in 0..4 { - for x in 0..80 { - let cell = &screen[(x, y)]; - assert!( - !cell - .modifier - .intersects(Modifier::REVERSED | Modifier::UNDERLINED) - ); - assert_eq!(cell.bg, Color::Reset); - } - } - app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - terminal.draw(|frame| app.draw(frame)).unwrap(); - let screen = terminal.backend().buffer(); - assert_eq!(screen[(popup_x + 1, 2)].symbol(), " "); - assert_eq!(screen[(popup_x + 1, 3)].symbol(), "·"); - } - } - - #[test] - fn menu_consumes_typing_and_save_opens_prompt() { - 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.menu.active.is_none()); - } - - #[test] - fn edit_menu_undo_and_escape() { - let mut app = App::default(); - app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::ALT)); - app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(app.buffer.editor.get_content(), ""); - app.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::ALT)); - app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(app.buffer.editor.get_content(), "a"); - app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); - assert_eq!(app.menu.active, Some(1)); - app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(app.menu.active.is_none()); - } - - #[test] - fn lsp_menu_toggles_auto_completion_and_opens_popup() { - let mut app = App::default(); - app.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::ALT)); - app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); - assert_eq!(app.menu.active, Some(2)); - app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); - assert_eq!(app.menu.active, Some(0)); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); - assert_eq!(app.menu.active, Some(2)); - let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); - let row = |app: &mut App, terminal: &mut Terminal| { - terminal.draw(|frame| app.draw(frame)).unwrap(); - (0..80) - .map(|x| terminal.backend().buffer()[(x, 2)].symbol().to_owned()) - .collect::() - }; - assert!(row(&mut app, &mut terminal).contains("Auto Complete: On C-c M-l")); - - app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert!(!app.completion.auto_enabled()); - assert!(app.menu.active.is_none()); - app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); - assert!(row(&mut app, &mut terminal).contains("Auto Complete: Off C-c M-l")); - - app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - for c in "hello he".chars() { - app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); - } - app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(app.buffer.editor.get_content(), "hello hello"); - } - - #[test] - fn tiny_terminals_do_not_panic() { - for (width, height) in [(1, 1), (5, 2), (20, 4)] { - let mut app = App::default(); - app.menu.active = Some(2); - let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); - terminal.draw(|frame| app.draw(frame)).unwrap(); - } - } -} diff --git a/src/buffers/menu/mod.rs b/src/buffers/menu/mod.rs new file mode 100644 index 0000000..31f99ea --- /dev/null +++ b/src/buffers/menu/mod.rs @@ -0,0 +1,358 @@ +// 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::cpp_checks::{Tool, settings::Settings}; +use crate::app::App; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use ratatui::{ + Frame, + layout::Rect, + style::{Color, Modifier, Style}, + text::{Line, Span}, + widgets::{Block, BorderType, Clear, List, ListItem, ListState, Paragraph}, +}; + +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 EDIT: &[(&str, &str)] = &[ + ("Undo", "C-x u"), + ("Redo", "C-M-_"), + ("Cut", "C-w"), + ("Copy", "M-w"), + ("Paste", "C-y"), +]; + +const BUFFER: &[(&str, &str)] = &[ + ("Search Forward", "C-s"), + ("Search Backward", "C-r"), + ("Query Replace", "M-%"), + ("Go to Line", "M-g g"), +]; + +const MENUS: [&str; 6] = ["FILE", "EDIT", "BUFFER", "LSP", "WINDOW", "C/C++"]; +const BUFFER_MENU: usize = 2; +const LSP_MENU: usize = 3; +const WINDOW_MENU: usize = 4; +const CPP_MENU: usize = 5; + +// C/C++ menu only shows if current active buffer is in C/C++ mode. +fn menus(cpp: bool) -> &'static [&'static str] { + if cpp { &MENUS } else { &MENUS[..CPP_MENU] } +} + +// What choosing a C/C++ menu entry does. +#[derive(Clone, Copy)] +enum CppAction { + Toggle(Tool), + Run(Tool), +} + +// C/C++ menu entries. A "Run" entry only shows when its check can run. +fn cpp_entries(settings: &Settings) -> Vec<(&'static str, &'static str, CppAction)> { + let tidy = if settings.tidy { + "Clang-tidy: On" + } else { + "Clang-tidy: Off" + }; + + let cpplint = if settings.cpplint { + "Cpplint: On" + } else { + "Cpplint: Off" + }; + + let mut entries = vec![ + (tidy, "", CppAction::Toggle(Tool::Tidy)), + (cpplint, "", CppAction::Toggle(Tool::Cpplint)), + ]; + + if settings.tidy { + entries.push(("Run Clang-tidy", "C-c t", CppAction::Run(Tool::Tidy))); + } + + if settings.cpplint_ready() { + entries.push(("Run Cpplint", "C-c l", CppAction::Run(Tool::Cpplint))); + } + entries +} + +// Entries of one menu. +fn items( + menu: usize, + auto_completion: bool, + nerd_font: bool, + cpp: Option<&Settings>, +) -> Vec<(&'static str, &'static str)> { + match (menu, cpp) { + (0, _) => FILE.to_vec(), + (1, _) => EDIT.to_vec(), + (BUFFER_MENU, _) => BUFFER.to_vec(), + (LSP_MENU, _) => vec![ + ( + if auto_completion { + "Auto Complete: On" + } else { + "Auto Complete: Off" + }, + "C-c M-l", + ), + ("Complete", "M-/"), + ("Quick Fix", "C-c a"), + ], + (WINDOW_MENU, _) => vec![( + if nerd_font { + "NF Mode: On" + } else { + "NF Mode: Off" + }, + "", + )], + (CPP_MENU, Some(settings)) => cpp_entries(settings) + .into_iter() + .map(|(label, shortcut, _)| (label, shortcut)) + .collect(), + _ => Vec::new(), + } +} + +#[derive(Default)] +pub(crate) struct Menu { + pub(crate) active: Option, + selected: usize, +} + +impl Menu { + pub(crate) fn draw_bar(&self, frame: &mut Frame, area: Rect, cpp: bool) { + let base = Style::default().fg(LIGHT_BLUE); + + // App name & version. + let mut spans = vec![ + Span::styled(" PTRE ", base.add_modifier(Modifier::BOLD)), + Span::styled(format!("REL.{} ", env!("CARGO_PKG_VERSION")), base), + ]; + + // App menu + for (index, name) in menus(cpp).iter().enumerate() { + let style = base.add_modifier(Modifier::BOLD); + let indicator = if self.active == Some(index) { + "❃ " + } else { + " " + }; + spans.push(Span::styled(indicator, base)); + spans.push(Span::styled(*name, style)); + spans.push(Span::styled(" ", base)); + } + + if area.height == 0 || area.width == 0 { + return; + } + + let border = if area.width == 1 { + "╭".to_owned() + } else { + format!("╭{}╮", "─".repeat(usize::from(area.width - 2))) + }; + + frame.render_widget( + Paragraph::new(Line::from(spans)).style(base), + Rect::new(area.x, area.y, area.width, 1), + ); + + if area.height > 1 { + frame.render_widget( + Paragraph::new(border).style(base), + Rect::new(area.x, area.y + 1, area.width, 1), + ); + } + } + + // Popup menu. + pub(crate) fn draw_popup( + &self, + frame: &mut Frame, + auto_completion: bool, + nerd_font: bool, + cpp: Option<&Settings>, + ) { + let Some(active) = self.active else { return }; + let screen = frame.area(); + let items = items(active, auto_completion, nerd_font, cpp); + + // The C/C++ menu has no entries once the buffer is not C/C++. + if screen.height <= 1 || screen.width == 0 || items.is_empty() { + return; + } + + let label_width = items + .iter() + .map(|(label, _)| label.len()) + .max() + .unwrap_or(0); + + let shortcut_width = items + .iter() + .map(|(_, shortcut)| shortcut.len()) + .max() + .unwrap_or(0); + + // Borders, selection indicator, side padding, and a two-column gap. + let width = (label_width + shortcut_width + 7) as u16; + let width = width.min(screen.width); + // Each menu name takes its length plus four columns of indicator and padding. + let before: usize = MENUS[..active].iter().map(|name| name.len() + 4).sum(); + let offset = (10 + env!("CARGO_PKG_VERSION").len() + before) as u16; + let area = Rect::new( + screen.x + offset.min(screen.width.saturating_sub(width)), + screen.y + 1, + width, + (items.len() as u16 + 2).min(screen.height - 1), + ); + + let rows: Vec<_> = items + .iter() + .map(|(label, shortcut)| { + ListItem::new(format!( + " {label:shortcut_width$} " + )) + }) + .collect(); + + let list = List::new(rows) + .style(Style::default().fg(LIGHT_BLUE)) + .block( + Block::bordered() + .border_type(BorderType::Rounded) + .border_style(Style::default().fg(LIGHT_BLUE)), + ) + .highlight_style(Style::default().fg(LIGHT_BLUE).add_modifier(Modifier::BOLD)) + .highlight_symbol("·"); + frame.render_widget(Clear, area); + frame.render_stateful_widget( + list, + area, + &mut ListState::default().with_selected(Some(self.selected)), + ); + } +} + +impl App { + // Decide whether to use nerd font. + fn toggle_nerd_font(&mut self) { + self.nerd_font = !self.nerd_font; + } + + // Invoke and activated menu. + pub(crate) fn handle_menu_key(&mut self, key: KeyEvent) -> bool { + let requested = match (key.code, key.modifiers) { + (KeyCode::F(10), _) => Some(0), + (KeyCode::Char('f' | 'F'), KeyModifiers::ALT) => Some(0), + (KeyCode::Char('e' | 'E'), KeyModifiers::ALT) => Some(1), + _ => None, + }; + + if let Some(index) = requested { + self.menu.active = if self.menu.active == Some(index) { + None + } else { + Some(index) + }; + self.menu.selected = 0; + return true; + } + + let Some(active) = self.menu.active else { + return false; + }; + + let cpp = self.is_c_or_cpp(); + let settings = cpp.then_some(&self.cpp_checks.settings); + let count = items(active, true, true, settings).len(); + + // Close the C/C++ menu popup after the buffer changed language. + if count == 0 { + self.menu.active = None; + return false; + } + + let menu_count = menus(cpp).len(); + match key.code { + KeyCode::Esc => self.menu.active = None, + KeyCode::Left | KeyCode::Right | KeyCode::Tab => { + let step = if key.code == KeyCode::Left { + menu_count - 1 + } else { + 1 + }; + self.menu.active = Some((active + step) % menu_count); + self.menu.selected = 0; + } + KeyCode::Down => self.menu.selected = (self.menu.selected + 1) % count, + KeyCode::Up => self.menu.selected = (self.menu.selected + count - 1) % count, + KeyCode::Enter => { + let selected = self.menu.selected; + self.menu.active = None; + 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, + )); + } else if active == BUFFER_MENU { + if selected == 3 { + self.handle_key(KeyEvent::new(KeyCode::Char('g'), alt)); + self.handle_key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE)); + } else { + let (code, modifiers) = [('s', ctrl), ('r', ctrl), ('%', alt)][selected]; + self.handle_key(KeyEvent::new(KeyCode::Char(code), modifiers)); + } + } else if active == LSP_MENU { + if selected == 0 { + self.handle_key(KeyEvent::new(KeyCode::Char('c'), ctrl)); + self.handle_key(KeyEvent::new(KeyCode::Char('l'), alt)); + } else if selected == 1 { + self.handle_key(KeyEvent::new(KeyCode::Char('/'), alt)); + } else { + self.handle_key(KeyEvent::new(KeyCode::Char('c'), ctrl)); + self.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); + } + } else if active == WINDOW_MENU { + self.toggle_nerd_font(); + } else if active == CPP_MENU { + // selected indexes the same entries the popup showed. + match cpp_entries(&self.cpp_checks.settings)[selected].2 { + CppAction::Toggle(tool) => self.toggle_cpp_check(tool), + CppAction::Run(tool) => self.run_cpp_check(tool), + } + } else { + if selected == 0 { + self.handle_key(KeyEvent::new(KeyCode::Char('x'), ctrl)); + self.handle_key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE)); + return true; + } + let (code, modifiers) = + [('_', ctrl | alt), ('w', ctrl), ('w', alt), ('y', ctrl)][selected - 1]; + self.handle_key(KeyEvent::new(KeyCode::Char(code), modifiers)); + } + } + _ => {} + } + true + } +} + +#[cfg(test)] +mod tests; diff --git a/src/buffers/menu/tests.rs b/src/buffers/menu/tests.rs new file mode 100644 index 0000000..4111246 --- /dev/null +++ b/src/buffers/menu/tests.rs @@ -0,0 +1,302 @@ +// 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}; + +#[test] +fn cpp_menu_hides_checks_that_cannot_run() { + let mut settings = Settings::default(); + assert_eq!(menus(false), ["FILE", "EDIT", "BUFFER", "LSP", "WINDOW"]); + assert_eq!( + menus(true), + ["FILE", "EDIT", "BUFFER", "LSP", "WINDOW", "C/C++"] + ); + assert_eq!(items(LSP_MENU, true, false, Some(&settings)).len(), 3); + let labels = |settings: &Settings| { + let entries = items(CPP_MENU, true, false, Some(settings)); + entries + .into_iter() + .map(|(label, _)| label) + .collect::>() + }; + assert_eq!(labels(&settings), ["Clang-tidy: Off", "Cpplint: Off"]); + settings.tidy = true; + assert_eq!( + labels(&settings), + ["Clang-tidy: On", "Cpplint: Off", "Run Clang-tidy"] + ); + + // Cpplint also needs an executable file as its path. + settings.cpplint = true; + for path in ["", "/ptre-missing/cpplint", "/", "Cargo.toml"] { + settings.cpplint_path = path.into(); + assert_eq!(labels(&settings).len(), 3, "{path:?}"); + } + settings.cpplint_path = std::env::current_exe().unwrap().display().to_string(); + assert_eq!( + items(CPP_MENU, true, false, Some(&settings))[3], + ("Run Cpplint", "C-c l") + ); + assert!(items(CPP_MENU, true, false, None).is_empty()); + assert_eq!(items(0, true, false, Some(&settings)), FILE); +} + +#[test] +fn cpp_menu_shows_only_for_c_and_cpp_buffers() { + let dir = std::env::temp_dir().join(format!("ptre-menu-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let bar = |app: &mut App| { + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + (0..80).map(|x| screen[(x, 0)].symbol()).collect::() + }; + for (file, cpp) in [("main.c", true), ("main.cpp", true), ("notes.txt", false)] { + let path = dir.join(file); + std::fs::write(&path, "text").unwrap(); + let mut app = App::default(); + app.buffer.open(path).unwrap(); + assert_eq!(bar(&mut app).contains("C/C++"), cpp, "{file}"); + + // Left from FILE wraps to the last menu shown. + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + assert_eq!( + app.menu.active, + Some(if cpp { CPP_MENU } else { WINDOW_MENU }) + ); + } + + // With "Run Clang-tidy" hidden, the third entry runs Cpplint. + let mut app = App::default(); + app.buffer.open(dir.join("main.c")).unwrap(); + let settings = &mut app.cpp_checks.settings; + settings.cpplint = true; + settings.cpplint_path = std::env::current_exe().unwrap().display().to_string(); + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.status_bar_text, "Running Cpplint…"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn renders_light_blue_menu_and_separator() { + let mut app = 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 title: String = (0..80).map(|x| screen[(x, 0)].symbol()).collect(); + assert!(title.contains(&format!("PTRE REL.{}", env!("CARGO_PKG_VERSION")))); + assert!(title.contains("FILE")); + assert!(title.contains("EDIT")); + assert_eq!(screen[(0, 0)].bg, Color::Reset); + assert_eq!(screen[(2, 0)].fg, LIGHT_BLUE); + assert_eq!(screen[(0, 1)].symbol(), "╭"); + assert_eq!(screen[(79, 1)].symbol(), "╮"); + for x in 1..79 { + assert_eq!(screen[(x, 1)].symbol(), "─"); + } + for x in 0..80 { + assert!(!screen[(x, 0)].modifier.contains(Modifier::UNDERLINED)); + assert_eq!(screen[(x, 1)].fg, LIGHT_BLUE); + assert_eq!(screen[(x, 1)].bg, Color::Reset); + } + app.menu.active = Some(0); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + let popup_x = 10 + env!("CARGO_PKG_VERSION").len() as u16; + assert_eq!(screen[(popup_x, 1)].bg, Color::Reset); + assert_eq!(screen[(popup_x, 1)].fg, LIGHT_BLUE); +} + +#[test] +fn active_menu_and_popup_use_markers_without_underlines() { + for active in 0..3 { + let mut app = App::default(); + app.menu.active = Some(active); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + let popup_x = 10 + env!("CARGO_PKG_VERSION").len() as u16 + active as u16 * 8; + 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]; + 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(), " "); + for y in 0..4 { + for x in 0..80 { + let cell = &screen[(x, y)]; + assert!( + !cell + .modifier + .intersects(Modifier::REVERSED | Modifier::UNDERLINED) + ); + assert_eq!(cell.bg, Color::Reset); + } + } + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let screen = terminal.backend().buffer(); + assert_eq!(screen[(popup_x + 1, 2)].symbol(), " "); + assert_eq!(screen[(popup_x + 1, 3)].symbol(), "·"); + } +} + +#[test] +fn menu_consumes_typing_and_save_opens_prompt() { + 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.menu.active.is_none()); +} + +#[test] +fn edit_menu_undo_and_escape() { + let mut app = App::default(); + app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::ALT)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.buffer.editor.get_content(), ""); + app.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::ALT)); + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.buffer.editor.get_content(), "a"); + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert_eq!(app.menu.active, Some(1)); + app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert!(app.menu.active.is_none()); +} + +#[test] +fn lsp_menu_toggles_auto_completion_and_opens_popup() { + let mut app = App::default(); + app.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::ALT)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert_eq!(app.menu.active, Some(BUFFER_MENU)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert_eq!(app.menu.active, Some(LSP_MENU)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert_eq!(app.menu.active, Some(WINDOW_MENU)); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + assert_eq!(app.menu.active, Some(LSP_MENU)); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + let row = |app: &mut App, terminal: &mut Terminal| { + terminal.draw(|frame| app.draw(frame)).unwrap(); + (0..80) + .map(|x| terminal.backend().buffer()[(x, 2)].symbol().to_owned()) + .collect::() + }; + assert!(row(&mut app, &mut terminal).contains("Auto Complete: On C-c M-l")); + + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(!app.completion.auto_enabled()); + assert!(app.menu.active.is_none()); + // FILE, EDIT, BUFFER, LSP from the left. + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert!(row(&mut app, &mut terminal).contains("Auto Complete: Off C-c M-l")); + + app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + for c in "hello he".chars() { + app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); + } + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.buffer.editor.get_content(), "hello hello"); +} + +#[test] +fn tiny_terminals_do_not_panic() { + for (width, height) in [(1, 1), (5, 2), (20, 4)] { + let mut app = App::default(); + app.menu.active = Some(2); + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + } +} + +#[test] +fn window_menu_toggles_nerd_font_icons() { + let mut app = App::default(); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + let screen = |app: &mut App, terminal: &mut Terminal| { + terminal.draw(|frame| app.draw(frame)).unwrap(); + let buffer = terminal.backend().buffer(); + (0..3) + .map(|y| (0..80).map(|x| buffer[(x, y)].symbol()).collect::()) + .collect::>() + }; + + // In a text buffer, Left from FILE reaches WINDOW, the last menu. + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + assert_eq!(app.menu.active, Some(WINDOW_MENU)); + let rows = screen(&mut app, &mut terminal); + assert!(rows[0].contains("❃ WINDOW")); + assert!(rows[2].contains("NF Mode: Off")); + + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(app.nerd_font); + assert!(app.status_bar_text.is_empty(), "no status message"); + app.handle_key(KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + assert!(screen(&mut app, &mut terminal)[2].contains("NF Mode: On")); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(!app.nerd_font); +} + +#[test] +fn buffer_menu_starts_search_and_replace() { + let mut app = App::default(); + app.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::ALT)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert_eq!(app.menu.active, Some(BUFFER_MENU)); + assert_eq!( + items(BUFFER_MENU, true, false, None), + [ + ("Search Forward", "C-s"), + ("Search Backward", "C-r"), + ("Query Replace", "M-%"), + ("Go to Line", "M-g g"), + ] + ); + app.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(app.goto_line.is_open()); + app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + + app.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::ALT)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.search.prompt().as_deref(), Some("Query replace: █")); +} diff --git a/src/buffers/mod.rs b/src/buffers/mod.rs index 45545bc..28cc449 100644 --- a/src/buffers/mod.rs +++ b/src/buffers/mod.rs @@ -19,5 +19,7 @@ mod dialog; pub(crate) mod editor; mod editor_status; pub(crate) mod fixes; +pub(crate) mod goto_line; pub(crate) mod menu; mod render; +pub(crate) mod search; diff --git a/src/buffers/render.rs b/src/buffers/render.rs index 9bfecdc..6fcc3e7 100644 --- a/src/buffers/render.rs +++ b/src/buffers/render.rs @@ -61,6 +61,7 @@ impl App { super::editor_status::draw( &self.buffer.editor, self.diagnostic_counts(), + self.nerd_font, frame, buffer_status_area, editor_area, @@ -71,6 +72,8 @@ impl App { self.draw_diagnostic_popup(frame); if !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() && let Some((x, y)) = self.buffer.editor.get_visible_cursor(&self.editor_area) @@ -84,6 +87,8 @@ impl App { " Cpplint path: {input}█ ※ Enter: enable Esc: cancel ※ {}", self.status_bar_text ) + } else if let Some(prompt) = self.search.prompt() { + format!(" {prompt}") } else if let Some(path_input) = &self.save_path_input { format!( " Save as: {path_input}█ ※ Enter: save Esc: cancel ※ {}", @@ -130,9 +135,11 @@ impl App { self.menu.draw_popup( frame, self.completion.auto_enabled(), + self.nerd_font, self.is_c_or_cpp().then_some(&self.cpp_checks.settings), ); + self.draw_goto_line(frame); self.draw_cpp_check(frame); if self.overwrite_confirm { diff --git a/src/buffers/search/incremental_search.rs b/src/buffers/search/incremental_search.rs new file mode 100644 index 0000000..b404d52 --- /dev/null +++ b/src/buffers/search/incremental_search.rs @@ -0,0 +1,169 @@ +// 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 . + +// Incremental search. + +use super::{Mode, find_all}; +use crate::app::App; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use std::ops::Range; + +pub(super) struct IncrementalSearch { + query: String, + forward: bool, + + // Where the search started. + origin: usize, + // The match shown now. + current: Option>, + + // Nothing more was found while failing. + failing: bool, + wrapped: bool, +} + +impl IncrementalSearch { + pub(super) fn prompt(&self) -> String { + let failing = if self.failing { "Failing " } else { "" }; + let wrapped = if self.wrapped { "Wrapped " } else { "" }; + let backward = if self.forward { "" } else { " backward" }; + format!("{failing}{wrapped}I-search{backward}: {}", self.query) + } + + // The match to show. + fn choose(&self, matches: &[Range], next: bool) -> Option> { + let current = self.current.as_ref(); + let found = if self.forward { + let from = current.map_or(self.origin, |c| c.start + usize::from(next)); + matches.iter().find(|m| m.start >= from) + } else { + matches.iter().rev().find(|m| match current { + Some(c) if next => m.start < c.start, + Some(c) => m.start <= c.start, + None => m.end <= self.origin, + }) + }; + + found.cloned() + } +} + +impl App { + pub(super) fn start_incremental_search(&mut self, forward: bool) { + let origin = self.buffer.editor.get_cursor(); + self.search.mode = Some(Mode::IncrementalSearch(IncrementalSearch { + query: String::new(), + forward, + origin, + current: None, + failing: false, + wrapped: false, + })); + } + + pub(super) fn incremental_search_key(&mut self, key: KeyEvent) -> bool { + let Some(Mode::IncrementalSearch(mut state)) = self.search.mode.take() else { + return false; + }; + let control = key.modifiers == KeyModifiers::CONTROL; + let plain = !key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT); + match key.code { + KeyCode::Char('s') if control => self.incremental_search_next(&mut state, true), + KeyCode::Char('r') if control => self.incremental_search_next(&mut state, false), + KeyCode::Char('g') if control => { + self.move_cursor(state.origin); + self.end_incremental_search(state); + return true; + } + + KeyCode::Enter => { + self.end_incremental_search(state); + return true; + } + + KeyCode::Backspace => { + state.query.pop(); + self.incremental_search_update(&mut state, false); + } + + KeyCode::Char(c) if plain => { + state.query.push(c); + self.incremental_search_update(&mut state, false); + } + + // Unexpected line here :( + _ => { + self.end_incremental_search(state); + return false; + } + } + self.search.mode = Some(Mode::IncrementalSearch(state)); + true + } + + // C-s or C-r: go on in that direction. + fn incremental_search_next(&mut self, state: &mut IncrementalSearch, forward: bool) { + state.forward = forward; + if state.query.is_empty() { + state.query = self.search.last.clone(); + self.incremental_search_update(state, false); + } else { + self.incremental_search_update(state, true); + } + } + + fn incremental_search_update(&mut self, state: &mut IncrementalSearch, next: bool) { + let matches = find_all(&self.buffer.editor.get_content(), &state.query); + let mut found = state.choose(&matches, next); + // After a failing search, one more step starts again from the other end. + if found.is_none() && next && state.failing { + let first = if state.forward { + matches.first() + } else { + matches.last() + }; + found = first.cloned(); + state.wrapped |= found.is_some(); + } + state.failing = found.is_none() && !state.query.is_empty(); + if let Some(found) = found { + // Like Emacs: after the match going forward, before it going backward. + self.move_cursor(if state.forward { + found.end + } else { + found.start + }); + state.current = Some(found); + } else if state.query.is_empty() { + self.move_cursor(state.origin); + state.current = None; + } + self.highlight_matches(&state.query, state.current.as_ref()); + } + + fn end_incremental_search(&mut self, state: IncrementalSearch) { + if !state.query.is_empty() { + self.search.last = state.query; + } + self.buffer.editor.remove_marks(); + } + + // Put the cursor at offset and scroll it into view. + pub(super) fn move_cursor(&mut self, offset: usize) { + self.buffer.editor.set_cursor(offset); + self.buffer.editor.focus(&self.editor_area); + } +} diff --git a/src/buffers/search/mod.rs b/src/buffers/search/mod.rs new file mode 100644 index 0000000..3526d10 --- /dev/null +++ b/src/buffers/search/mod.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Emacs-style search and replace. + +mod incremental_search; +mod replace; +#[cfg(test)] +mod tests; + +use crate::app::App; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use incremental_search::IncrementalSearch; +use replace::Replacing; +use std::ops::Range; +const CURRENT_MATCH: &str = "#4f6f9f"; +const OTHER_MATCH: &str = "#2c3a4c"; + +#[derive(Default)] +pub(crate) struct Search { + mode: Option, + // The last search string, reused by C-s or C-r on an empty search. + last: String, +} + +enum Mode { + IncrementalSearch(IncrementalSearch), + ReplaceFrom(String), + ReplaceTo(String, String), + Replacing(Replacing), +} + +impl Search { + // The status bar text. + pub(crate) fn prompt(&self) -> Option { + Some(match self.mode.as_ref()? { + Mode::IncrementalSearch(incremental_search) => incremental_search.prompt(), + Mode::ReplaceFrom(from) => format!("Query replace: {from}█"), + Mode::ReplaceTo(from, to) => format!("Query replace {from} with: {to}█"), + Mode::Replacing(replacing) => replacing.prompt(), + }) + } + + // True while the user types into the status bar. + // This hides the cursor. + pub(crate) fn reads_input(&self) -> bool { + matches!(self.mode, Some(Mode::ReplaceFrom(_) | Mode::ReplaceTo(..))) + } +} + +impl App { + // Keys of search and replace. + pub(crate) fn handle_search_key(&mut self, key: KeyEvent) -> bool { + // C-c chords belong to completion and the checks; go to line keeps its own keys. + if self.ctrl_c_wait_flag || self.goto_line.is_busy() { + return false; + } + match self.search.mode { + None => self.start_search(key), + Some(Mode::IncrementalSearch(_)) => self.incremental_search_key(key), + Some(Mode::ReplaceFrom(_) | Mode::ReplaceTo(..)) => self.replace_prompt_key(key), + Some(Mode::Replacing(_)) => self.replacing_key(key), + } + } + + fn start_search(&mut self, key: KeyEvent) -> bool { + let control = key.modifiers == KeyModifiers::CONTROL; + // M-% is Alt + Shift + 5. + let meta = key.modifiers.contains(KeyModifiers::ALT) + && !key.modifiers.contains(KeyModifiers::CONTROL); + match key.code { + KeyCode::Char('s') if control => self.start_incremental_search(true), + KeyCode::Char('r') if control => self.start_incremental_search(false), + KeyCode::Char('%') if meta => self.start_replace(), + _ => return false, + } + self.completion.close(); + true + } + + // Mark every match of query, the current one brighter than the others. + fn highlight_matches(&mut self, query: &str, current: Option<&Range>) { + let text = self.buffer.editor.get_content(); + let marks: Vec<_> = find_all(&text, query) + .into_iter() + .map(|found| { + let color = if Some(&found) == current { + CURRENT_MATCH + } else { + OTHER_MATCH + }; + (found.start, found.end, color) + }) + .collect(); + if marks.is_empty() { + self.buffer.editor.remove_marks(); + } else { + self.buffer.editor.set_marks(marks); + } + } +} + +// Char ranges of the matches of query in text. +fn find_all(text: &str, query: &str) -> Vec> { + let fold = !query.chars().any(char::is_uppercase); + let same = |t: char, q: char| t == q || (fold && t.to_lowercase().eq(q.to_lowercase())); + let text: Vec = text.chars().collect(); + let query: Vec = query.chars().collect(); + let mut found = Vec::new(); + let mut start = 0; + while !query.is_empty() && start + query.len() <= text.len() { + if query.iter().zip(&text[start..]).all(|(&q, &t)| same(t, q)) { + found.push(start..start + query.len()); + start += query.len(); + } else { + start += 1; + } + } + found +} diff --git a/src/buffers/search/replace.rs b/src/buffers/search/replace.rs new file mode 100644 index 0000000..fd9ea28 --- /dev/null +++ b/src/buffers/search/replace.rs @@ -0,0 +1,198 @@ +// 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 . + +// Query replace (M-%). + +use super::{Mode, find_all}; +use crate::app::App; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use std::ops::Range; + +pub(super) struct Replacing { + from: String, + to: String, + + // The match. + current: Range, + count: usize, + + // The cursor before the first replacement, restored by undo. + origin: usize, + + // All replacements form one undo step, opened at the first one. + open: bool, +} + +impl Replacing { + pub(super) fn prompt(&self) -> String { + format!( + "Query replacing {} with {}: (y, n, !, ., q)", + self.from, self.to + ) + } +} + +impl App { + pub(super) fn start_replace(&mut self) { + self.search.mode = Some(Mode::ReplaceFrom(String::new())); + } + + // Typing the text to replace and its replacement. + pub(super) fn replace_prompt_key(&mut self, key: KeyEvent) -> bool { + let control = key.modifiers == KeyModifiers::CONTROL; + let plain = !key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT); + let Some(Mode::ReplaceFrom(input) | Mode::ReplaceTo(_, input)) = &mut self.search.mode + else { + return false; + }; + match key.code { + KeyCode::Char(c) if plain => input.push(c), + KeyCode::Backspace => { + input.pop(); + } + KeyCode::Enter => self.replace_prompt_enter(), + KeyCode::Esc => self.search.mode = None, + KeyCode::Char('g') if control => self.search.mode = None, + // Other keys do nothing while typing. + _ => {} + } + true + } + + fn replace_prompt_enter(&mut self) { + match self.search.mode.take() { + // Nothing to replace: give up quietly, as Emacs does. + Some(Mode::ReplaceFrom(from)) if from.is_empty() => {} + Some(Mode::ReplaceFrom(from)) => { + self.search.mode = Some(Mode::ReplaceTo(from, String::new())); + } + Some(Mode::ReplaceTo(from, to)) => { + let origin = self.buffer.editor.get_cursor(); + let state = self.next_match(&from, origin).map(|current| Replacing { + from, + to, + current, + count: 0, + origin, + open: false, + }); + match state { + Some(state) => self.ask_replace(state), + None => self.status_bar_text = "Replaced 0 occurrences".into(), + } + } + other => self.search.mode = other, + } + } + + // Answers to "replace this match?". + pub(super) fn replacing_key(&mut self, key: KeyEvent) -> bool { + let Some(Mode::Replacing(mut state)) = self.search.mode.take() else { + return false; + }; + let control = key.modifiers == KeyModifiers::CONTROL; + let plain = !key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT); + match key.code { + KeyCode::Char('y' | ' ') if plain => { + let end = self.replace_one(&mut state); + self.replace_next(state, end); + } + KeyCode::Char('n') if plain => { + let end = state.current.end; + self.replace_next(state, end); + } + KeyCode::Backspace => { + let end = state.current.end; + self.replace_next(state, end); + } + KeyCode::Char('!') if plain => { + // Replace this match and every one after it. + let mut end = self.replace_one(&mut state); + while let Some(found) = self.next_match(&state.from, end) { + state.current = found; + end = self.replace_one(&mut state); + } + self.finish_replace(state); + } + KeyCode::Char('.') if plain => { + self.replace_one(&mut state); + self.finish_replace(state); + } + KeyCode::Char('q') if plain => self.finish_replace(state), + KeyCode::Enter | KeyCode::Esc => self.finish_replace(state), + KeyCode::Char('g') if control => self.finish_replace(state), + // Any other key ends replacing and is then handled as usual. + _ => { + self.finish_replace(state); + return false; + } + } + true + } + + // Replace the current match; returns where its replacement ends. + fn replace_one(&mut self, state: &mut Replacing) -> usize { + let code = self.buffer.editor.code_mut(); + if !state.open { + code.tx(); + code.set_state_before(state.origin, None); + state.open = true; + } + let start = state.current.start; + code.remove(start, state.current.end); + code.insert(start, &state.to); + state.count += 1; + let end = start + state.to.chars().count(); + self.buffer.editor.reset_highlight_cache(); + self.move_cursor(end); + end + } + + fn next_match(&self, from: &str, after: usize) -> Option> { + let text = self.buffer.editor.get_content(); + find_all(&text, from).into_iter().find(|m| m.start >= after) + } + + fn replace_next(&mut self, mut state: Replacing, after: usize) { + match self.next_match(&state.from, after) { + Some(found) => { + state.current = found; + self.ask_replace(state); + } + None => self.finish_replace(state), + } + } + + fn ask_replace(&mut self, state: Replacing) { + self.move_cursor(state.current.end); + self.highlight_matches(&state.from, Some(&state.current)); + self.search.mode = Some(Mode::Replacing(state)); + } + + fn finish_replace(&mut self, state: Replacing) { + if state.open { + let cursor = self.buffer.editor.get_cursor(); + let code = self.buffer.editor.code_mut(); + code.set_state_after(cursor, None); + code.commit(); + } + self.buffer.editor.remove_marks(); + let plural = if state.count == 1 { "" } else { "s" }; + self.status_bar_text = format!("Replaced {} occurrence{plural}", state.count); + } +} diff --git a/src/buffers/search/tests.rs b/src/buffers/search/tests.rs new file mode 100644 index 0000000..cd5bccb --- /dev/null +++ b/src/buffers/search/tests.rs @@ -0,0 +1,219 @@ +// 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, layout::Rect}; + +fn app_with(text: &str, cursor: usize) -> App { + let mut app = App::default(); + app.editor_area = Rect::new(1, 1, 78, 22); + app.buffer.editor.set_content(text); + app.buffer.editor.set_cursor(cursor); + app +} + +fn press(app: &mut App, code: KeyCode, modifiers: KeyModifiers) { + app.handle_key(KeyEvent::new(code, modifiers)); +} + +fn ctrl(app: &mut App, c: char) { + press(app, KeyCode::Char(c), KeyModifiers::CONTROL); +} + +fn type_text(app: &mut App, text: &str) { + for c in text.chars() { + let code = if c == '\n' { + KeyCode::Enter + } else { + KeyCode::Char(c) + }; + press(app, code, KeyModifiers::NONE); + } +} + +fn replace(app: &mut App, from: &str, to: &str) { + press(app, KeyCode::Char('%'), KeyModifiers::ALT); + type_text(app, &format!("{from}\n{to}\n")); +} + +fn cursor(app: &App) -> usize { + app.buffer.editor.get_cursor() +} + +#[test] +fn matches_ignore_case_only_for_lowercase_queries() { + assert_eq!(find_all("Foo foo FOO", "foo"), [0..3, 4..7, 8..11]); + let only_first = Range { start: 0, end: 3 }; + assert_eq!(find_all("Foo foo FOO", "Foo"), [only_first]); + assert_eq!(find_all("aaaa", "aa"), [0..2, 2..4], "no overlaps"); + assert_eq!(find_all("中文中文", "中"), [0..1, 2..3]); + assert!(find_all("abc", "").is_empty()); + assert!(find_all("ab", "abc").is_empty()); +} + +#[test] +fn incremental_search_moves_fails_wraps_and_ends_at_the_match() { + let mut app = app_with("one two one two", 0); + ctrl(&mut app, 's'); + type_text(&mut app, "two"); + assert_eq!(cursor(&app), 7, "after the first match"); + assert_eq!(app.search.prompt().as_deref(), Some("I-search: two")); + assert_eq!(app.buffer.editor.get_marks().map(Vec::len), Some(2)); + assert_eq!(app.buffer.editor.get_content(), "one two one two"); + + ctrl(&mut app, 's'); + assert_eq!(cursor(&app), 15); + ctrl(&mut app, 's'); + assert_eq!(cursor(&app), 15); + assert_eq!( + app.search.prompt().as_deref(), + Some("Failing I-search: two") + ); + ctrl(&mut app, 's'); + assert_eq!(cursor(&app), 7); + assert_eq!( + app.search.prompt().as_deref(), + Some("Wrapped I-search: two") + ); + + press(&mut app, KeyCode::Enter, KeyModifiers::NONE); + assert!(app.search.prompt().is_none()); + assert_eq!(cursor(&app), 7); + assert!(!app.buffer.editor.has_marks()); +} + +#[test] +fn incremental_search_backward_cancel_other_keys_and_repeat() { + let mut app = app_with("one two one two", 15); + ctrl(&mut app, 'r'); + type_text(&mut app, "one"); + assert_eq!(cursor(&app), 8, "before the nearest match"); + assert_eq!( + app.search.prompt().as_deref(), + Some("I-search backward: one") + ); + ctrl(&mut app, 'g'); + assert_eq!(cursor(&app), 15, "C-g goes back"); + assert!(app.search.prompt().is_none()); + + // Another key ends the search and still does its job. + app.buffer.editor.set_cursor(0); + ctrl(&mut app, 's'); + type_text(&mut app, "two"); + press(&mut app, KeyCode::Left, KeyModifiers::NONE); + assert!(app.search.prompt().is_none()); + assert_eq!(cursor(&app), 6); + + // C-s on an empty search repeats the last one; Backspace shortens it. + ctrl(&mut app, 's'); + ctrl(&mut app, 's'); + assert_eq!(app.search.prompt().as_deref(), Some("I-search: two")); + assert_eq!(cursor(&app), 15); + press(&mut app, KeyCode::Backspace, KeyModifiers::NONE); + assert_eq!(cursor(&app), 14); + press(&mut app, KeyCode::Enter, KeyModifiers::NONE); + + // A capital letter makes the search case-sensitive. + let mut app = app_with("foo Foo", 0); + ctrl(&mut app, 's'); + type_text(&mut app, "F"); + assert_eq!(cursor(&app), 5); +} + +#[test] +fn query_replace_asks_at_each_match_and_undoes_in_one_step() { + let mut app = app_with("a b a b a", 0); + press(&mut app, KeyCode::Char('%'), KeyModifiers::ALT); + assert_eq!(app.search.prompt().as_deref(), Some("Query replace: █")); + type_text(&mut app, "a\n"); + assert_eq!( + app.search.prompt().as_deref(), + Some("Query replace a with: █") + ); + type_text(&mut app, "x\n"); + assert_eq!( + app.search.prompt().as_deref(), + Some("Query replacing a with x: (y, n, !, ., q)") + ); + assert_eq!(cursor(&app), 1); + + type_text(&mut app, "y"); + assert_eq!(app.buffer.editor.get_content(), "x b a b a"); + assert_eq!(cursor(&app), 5, "at the next match"); + type_text(&mut app, "n"); + assert_eq!(cursor(&app), 9); + type_text(&mut app, "!"); + assert_eq!(app.buffer.editor.get_content(), "x b a b x"); + assert_eq!(app.status_bar_text, "Replaced 2 occurrences"); + assert!(app.search.prompt().is_none()); + assert!(!app.buffer.editor.has_marks()); + + ctrl(&mut app, 'z'); + assert_eq!(app.buffer.editor.get_content(), "a b a b a"); +} + +#[test] +fn query_replace_answers_and_edge_cases() { + // "." replaces this match and stops. + let mut app = app_with("cat cat cat", 0); + replace(&mut app, "cat", "dog"); + type_text(&mut app, "."); + assert_eq!(app.buffer.editor.get_content(), "dog cat cat"); + assert_eq!(app.status_bar_text, "Replaced 1 occurrence"); + + // "q" stops without changes; a replacement holding the text does not loop. + let mut app = app_with("a a", 0); + replace(&mut app, "a", "aa"); + type_text(&mut app, "q"); + assert_eq!(app.status_bar_text, "Replaced 0 occurrences"); + // Replacing starts at the cursor, which "q" left after the first match. + app.buffer.editor.set_cursor(0); + replace(&mut app, "a", "aa"); + type_text(&mut app, "!"); + assert_eq!(app.buffer.editor.get_content(), "aa aa"); + + // Only matches after the cursor count; an empty text cancels. + let mut app = app_with("a b", 3); + replace(&mut app, "a", "x"); + assert_eq!(app.status_bar_text, "Replaced 0 occurrences"); + assert!(app.search.prompt().is_none()); + press( + &mut app, + KeyCode::Char('%'), + KeyModifiers::ALT | KeyModifiers::SHIFT, + ); + type_text(&mut app, "\n"); + assert!(app.search.prompt().is_none()); + assert_eq!(app.buffer.editor.get_content(), "a b"); + + // Another key ends replacing and still does its job. + let mut app = app_with("ab ab", 0); + replace(&mut app, "ab", "x"); + press(&mut app, KeyCode::Left, KeyModifiers::NONE); + assert!(app.search.prompt().is_none()); + assert_eq!(cursor(&app), 1); +} + +#[test] +fn status_bar_shows_the_prompt() { + let mut app = app_with("one two", 0); + ctrl(&mut app, 's'); + type_text(&mut app, "tw"); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal.draw(|frame| app.draw(frame)).unwrap(); + let status: String = (0..80) + .map(|x| terminal.backend().buffer()[(x, 23)].symbol()) + .collect(); + assert!(status.starts_with(" I-search: tw"), "{status}"); +}