From 0d3ed442e4f381af5afc45f10540bd43c31973f9 Mon Sep 17 00:00:00 2001 From: "Timothy J. Warren" Date: Fri, 12 Mar 2021 12:00:39 -0500 Subject: [PATCH] Basic incremental search --- src/editor.rs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/editor.rs b/src/editor.rs index 470cf39..1b866b3 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -161,7 +161,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."); return; @@ -196,7 +196,15 @@ impl Editor { }, 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 { @@ -237,14 +245,18 @@ impl Editor { Ok(()) } - 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) => { @@ -258,6 +270,8 @@ impl Editor { } _ => (), } + + callback(self, key, &result); } self.status_message = StatusMessage::default();