Skip to content

Commit

Permalink
add deletion
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-streltsov committed Feb 14, 2024
1 parent 8633a15 commit 7ef125f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,19 @@ impl Document {
row.insert(at.x, c);
}
}
pub fn delete(&mut self, at: &Position) {
let len = self.len();
if at.y >= len {
return;
}

if at.x == self.rows.get_mut(at.y).unwrap().len() && at.y < len - 1 {
let next_row = self.rows.remove(at.y + 1);
let row = self.rows.get_mut(at.y).unwrap();
row.append(&next_row);
} else {
let row = self.rows.get_mut(at.y).unwrap();
row.delete(at.x);
}
}
}
7 changes: 7 additions & 0 deletions src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,13 @@ impl Editor {
self.document.insert(&self.cursor_position, c);
self.move_cursor(Key::Right);
}
Key::Delete => self.document.delete(&self.cursor_position),
Key::Backspace => {
if self.cursor_position.x > 0 || self.cursor_position.y > 0 {
self.move_cursor(Key::Left);
self.document.delete(&self.cursor_position);
}
}
Key::Up
| Key::Down
| Key::Left
Expand Down
15 changes: 15 additions & 0 deletions src/row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,19 @@ impl Row {
}
self.update_len();
}
pub fn delete(&mut self, at: usize) {
if at >= self.len() {
return;
} else {
let mut result: String = self.string[..].graphemes(true).take(at).collect();
let remainder: String = self.string[..].graphemes(true).skip(at + 1).collect();
result.push_str(&remainder);
self.string = result;
}
self.update_len();
}
pub fn append(&mut self, new: &Self) {
self.string = format!("{}{}", self.string, new.string);
self.update_len();
}
}

0 comments on commit 7ef125f

Please sign in to comment.