Skip to content

Commit

Permalink
refactor the character deletion in a function
Browse files Browse the repository at this point in the history
  • Loading branch information
amtoine committed Aug 22, 2023
1 parent 2c21c3a commit 6151071
Showing 1 changed file with 19 additions and 18 deletions.
37 changes: 19 additions & 18 deletions src/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,29 +51,30 @@ impl Editor {
self.move_cursor_right();
}

fn delete_char(&mut self) {
/// TODO: documentation
fn delete_char(&mut self, offset: i32) {
let position = self.cursor_position + (offset as usize);

// NOTE: work on the chars and do not use remove which works on bytes
self.buffer = self
.buffer
.chars()
.take(position)
.chain(self.buffer.chars().skip(position + 1))
.collect();
}

fn delete_char_before_cursor(&mut self) {
let is_not_cursor_leftmost = self.cursor_position != 0;

if is_not_cursor_leftmost {
// NOTE: work on the chars and do not use remove which works on bytes
self.buffer = self
.buffer
.chars()
.take(self.cursor_position - 1)
.chain(self.buffer.chars().skip(self.cursor_position))
.collect();
self.delete_char(-1);
self.move_cursor_left();
}
}

fn delete_char_backward(&mut self) {
// NOTE: work on the chars and do not use remove which works on bytes
self.buffer = self
.buffer
.chars()
.take(self.cursor_position)
.chain(self.buffer.chars().skip(self.cursor_position + 1))
.collect();
fn delete_char_under_cursor(&mut self) {
self.delete_char(0);
}

/// TODO: documentation
Expand All @@ -82,8 +83,8 @@ impl Editor {
Key::ArrowLeft => self.move_cursor_left(),
Key::ArrowRight => self.move_cursor_right(),
Key::Char(c) => self.enter_char(*c),
Key::Backspace => self.delete_char(),
Key::Del => self.delete_char_backward(),
Key::Backspace => self.delete_char_before_cursor(),
Key::Del => self.delete_char_under_cursor(),
Key::Enter => {
let val = Value::String {
val: self.buffer.clone(),
Expand Down

0 comments on commit 6151071

Please sign in to comment.