From 6efb73ff2b750fe73bec7d6d1fc3507d541da227 Mon Sep 17 00:00:00 2001 From: "Timothy J. Warren" Date: Fri, 12 Mar 2021 11:50:28 -0500 Subject: [PATCH] Basic search --- src/document.rs | 10 ++++++++++ src/editor.rs | 11 ++++++++++- src/row.rs | 15 +++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/document.rs b/src/document.rs index 4614895..f65062e 100644 --- a/src/document.rs +++ b/src/document.rs @@ -103,6 +103,16 @@ impl Document { self.dirty } + pub fn find(&self, query: &str) -> Option { + for (y, row) in self.rows.iter().enumerate() { + if let Some(x) = row.find(query) { + return Some(Position { x, y }) + } + } + + None + } + fn insert_newline(&mut self, at: &Position) { if at.y > self.rows.len() { return; diff --git a/src/editor.rs b/src/editor.rs index e39f826..470cf39 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -63,7 +63,7 @@ impl Editor { pub fn default() -> Self { let args: Vec = env::args().collect(); - let mut initial_status = String::from("HELP: Ctrl-S = save | Ctrl-Q = quit"); + let mut initial_status = String::from("HELP: Ctrl-F = find | Ctrl-S = save | Ctrl-Q = quit"); let document = if let Some(file_name) = args.get(1) { let doc = Document::open(&file_name); if let Ok(doc) = doc { @@ -195,6 +195,15 @@ impl Editor { self.should_quit = true }, Key::Ctrl('s') => self.save(), + Key::Ctrl('f') => { + if let Some(query) = self.prompt("Search: ").unwrap_or(None) { + if let Some(position) = self.document.find(&query[..]) { + self.cursor_position = position; + } else { + self.status_message = StatusMessage::from(format!("Not found: {}", query)); + } + } + } Key::Char(c) => { self.document.insert(&self.cursor_position, c); self.move_cursor(Key::Right); diff --git a/src/row.rs b/src/row.rs index f9e46fb..cb04a19 100644 --- a/src/row.rs +++ b/src/row.rs @@ -126,4 +126,19 @@ impl Row { pub fn as_bytes(&self) -> &[u8] { self.string.as_bytes() } + + pub fn find(&self, query: &str) -> Option { + let matching_byte_index = self.string.find(query); + if let Some(matching_byte_index) = matching_byte_index { + for (grapheme_index, (byte_index, _)) in + self.string[..].grapheme_indices(true).enumerate() + { + if matching_byte_index == byte_index { + return Some(grapheme_index); + } + } + } + + None + } } \ No newline at end of file