feat(editor): support moving cursor with arrow keys

This commit is contained in:
Harsh Shandilya 2022-08-07 22:25:05 +05:30
parent 753d07579a
commit aff2d24d33
No known key found for this signature in database
GPG Key ID: 366D7BBAD1031E80

View File

@ -47,6 +47,7 @@ impl Editor {
let pressed_key = Terminal::read_key()?;
match pressed_key {
Key::Ctrl('q') => self.should_quit = true,
Key::Up | Key::Left | Key::Right | Key::Down => self.move_cursor(pressed_key),
_ => (),
};
Ok(())
@ -88,6 +89,29 @@ impl Editor {
}
}
}
fn move_cursor(&mut self, key: Key) {
let Position { mut y, mut x } = self.cursor_position;
let size = self.terminal.size();
let height = size.height.saturating_sub(1) as usize;
let width = size.width.saturating_sub(1) as usize;
match key {
Key::Up => y = y.saturating_sub(1),
Key::Down => {
if y < height {
y = y.saturating_add(1);
}
}
Key::Left => x = x.saturating_sub(1),
Key::Right => {
if x < width {
x = x.saturating_add(1);
}
}
_ => (),
}
self.cursor_position = Position { x, y }
}
}
fn die(e: std::io::Error) {