From 5909dd66db0370bc20f1cbb99d1f74d9fd40ee6a Mon Sep 17 00:00:00 2001 From: Artem Streltsov Date: Mon, 19 Feb 2024 12:56:26 +0000 Subject: [PATCH] add incremental search --- src/editor.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/editor.rs b/src/editor.rs index 56494b2..99fda24 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -107,7 +107,13 @@ impl Editor { match pressed_key { Key::Ctrl('s') => self.save(), Key::Ctrl('f') => { - if let Some(query) = self.prompt("Search: ").unwrap_or(None) { + if let Some(query) = self + .prompt("Search: ", |editor, _, query| { + if let Some(position) = editor.document.find(&query) { + editor.cursor_position = position; + editor.scroll(); + } + }).unwrap_or(None) { if let Some(position) = self.document.find(&query[..]) { self.cursor_position = position; } else { @@ -318,12 +324,16 @@ impl Editor { print!("{}", text); } } - fn prompt(&mut self, prompt: &str) -> Result, std::io::Error> { + fn prompt(&mut self, prompt: &str, callback: C) -> Result, std::io::Error> + where + C: Fn(&mut Self, Key, &String), + { let mut result = String::new(); loop { self.status_message = StatusMessage::from(format!("{}{}", prompt, result)); self.refresh_screen()?; - match Terminal::read_key()? { + let key = Terminal::read_key()?; + match key { Key::Backspace => result.truncate(result.len().saturating_sub(1)), Key::Char('\n') => break, Key::Char(c) => { @@ -337,6 +347,7 @@ impl Editor { } _ => () } + callback(self, key, &result); } self.status_message = StatusMessage::from(String::new()); if result.is_empty() { @@ -346,7 +357,7 @@ impl Editor { } fn save(&mut self) { if self.document.file_name.is_none() { - let new_name = self.prompt("Save as: ").unwrap_or(None); + let new_name = self.prompt("Save as: ", |_, _, _| {}).unwrap_or(None); if new_name.is_none() { self.status_message = StatusMessage::from("Save aborted.".to_string()); return;