Skip to content

Commit

Permalink
add incremental search
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-streltsov committed Feb 19, 2024
1 parent da824a1 commit 5909dd6
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -318,12 +324,16 @@ impl Editor {
print!("{}", text);
}
}
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();
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) => {
Expand All @@ -337,6 +347,7 @@ impl Editor {
}
_ => ()
}
callback(self, key, &result);
}
self.status_message = StatusMessage::from(String::new());
if result.is_empty() {
Expand All @@ -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;
Expand Down

0 comments on commit 5909dd6

Please sign in to comment.