Basic incremental search

This commit is contained in:
Timothy Warren 2021-03-12 12:00:39 -05:00
parent 6efb73ff2b
commit 0d3ed442e4

View File

@ -161,7 +161,7 @@ impl Editor {
fn save(&mut self) { fn save(&mut self) {
if self.document.file_name.is_none() { 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() { if new_name.is_none() {
self.status_message = StatusMessage::from("Save aborted."); self.status_message = StatusMessage::from("Save aborted.");
return; return;
@ -196,7 +196,15 @@ impl Editor {
}, },
Key::Ctrl('s') => self.save(), Key::Ctrl('s') => self.save(),
Key::Ctrl('f') => { 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[..]) { if let Some(position) = self.document.find(&query[..]) {
self.cursor_position = position; self.cursor_position = position;
} else { } else {
@ -237,14 +245,18 @@ impl Editor {
Ok(()) Ok(())
} }
fn prompt(&mut self, prompt: &str) -> Result<Option<String>, std::io::Error> { fn prompt<C>(&mut self, prompt: &str, callback: C) -> Result<Option<String>, std::io::Error>
where
C: Fn(&mut Self, Key, &String),
{
let mut result = String::new(); let mut result = String::new();
loop { loop {
self.status_message = StatusMessage::from(format!("{}{}", prompt, result)); self.status_message = StatusMessage::from(format!("{}{}", prompt, result));
self.refresh_screen()?; self.refresh_screen()?;
match Terminal::read_key()? { let key = Terminal::read_key()?;
match key {
Key::Backspace => result.truncate(result.len().saturating_sub(1)), Key::Backspace => result.truncate(result.len().saturating_sub(1)),
Key::Char('\n') => break, Key::Char('\n') => break,
Key::Char(c) => { Key::Char(c) => {
@ -258,6 +270,8 @@ impl Editor {
} }
_ => (), _ => (),
} }
callback(self, key, &result);
} }
self.status_message = StatusMessage::default(); self.status_message = StatusMessage::default();