Skip to content

Commit

Permalink
add basic search
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-streltsov committed Feb 19, 2024
1 parent 05671dd commit da824a1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,12 @@ impl Document {
pub fn is_dirty(&self) -> bool {
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
}
}
11 changes: 10 additions & 1 deletion src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,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 {
Expand Down Expand Up @@ -106,6 +106,15 @@ impl Editor {
let pressed_key = Terminal::read_key()?;
match pressed_key {
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::Ctrl('q') => {
if self.quit_times > 0 && self.document.is_dirty() {
self.status_message = StatusMessage::from(format!(
Expand Down
13 changes: 12 additions & 1 deletion src/row.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::cmp;
use std::{cmp, usize};
use unicode_segmentation::UnicodeSegmentation;

#[derive(Default)]
Expand Down Expand Up @@ -98,4 +98,15 @@ 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
}
}

0 comments on commit da824a1

Please sign in to comment.