Basic search

This commit is contained in:
Timothy Warren 2021-03-12 11:50:28 -05:00
parent ec01b65bce
commit 6efb73ff2b
3 changed files with 35 additions and 1 deletions

View File

@ -103,6 +103,16 @@ impl Document {
self.dirty
}
pub fn find(&self, query: &str) -> Option<Position> {
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;

View File

@ -63,7 +63,7 @@ impl Editor {
pub fn default() -> Self {
let args: Vec<String> = 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);

View File

@ -126,4 +126,19 @@ impl Row {
pub fn as_bytes(&self) -> &[u8] {
self.string.as_bytes()
}
pub fn find(&self, query: &str) -> Option<usize> {
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
}
}