From a2146a01684878e7659219be89aefa106748f4ff Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Mon, 6 May 2024 01:53:27 -0400 Subject: [PATCH] Add some basic editing facilities --- editor-challenge/src/state.rs | 12 ++++++++++++ editor-challenge/src/types.rs | 36 +++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/editor-challenge/src/state.rs b/editor-challenge/src/state.rs index 803adb7..be32879 100644 --- a/editor-challenge/src/state.rs +++ b/editor-challenge/src/state.rs @@ -57,6 +57,18 @@ impl AppState { KeyCode::Left => { self.cursor_left(); } + KeyCode::Backspace => { + self.contents.backspace(&mut self.cursor); + } + KeyCode::Delete => { + self.contents.delete_at(&mut self.cursor); + } + KeyCode::Enter => { + self.contents.new_line(&mut self.cursor); + } + KeyCode::Char(c) => { + self.contents.insert_at(&mut self.cursor, c); + } _ => {} }; } diff --git a/editor-challenge/src/types.rs b/editor-challenge/src/types.rs index 82e4b33..582f56f 100644 --- a/editor-challenge/src/types.rs +++ b/editor-challenge/src/types.rs @@ -1,3 +1,7 @@ + +// TODO: I'm increasingly feeling that cursors are per-document, not per-application. So I think I +// want to move the cursor into here, and then rendering requires asking for the cursor for the +// current document. #[derive(Default)] pub struct Document { rows: Vec @@ -24,6 +28,38 @@ impl Document { pub fn row_count(&self) -> usize { self.rows.len() } + + pub fn insert_at(&mut self, cursor: &mut Cursor, c: char){ + let (row, column) = cursor.addr(); + + self.rows[row].insert(column, c); + cursor.cursor_right(self); + } + + pub fn backspace(&mut self, cursor: &mut Cursor) { + let (row, column) = cursor.addr(); + if cursor.column > 0 { + let _ = self.rows[row].remove(column - 1); + cursor.cursor_left(); + } + } + + pub fn delete_at(&mut self, cursor: &mut Cursor) { + let (row, column) = cursor.addr(); + if cursor.column < self.rows[row].len() { + self.rows[row].remove(column); + cursor.correct_columns(self); + } + } + + pub fn new_line(&mut self, cursor: &mut Cursor) { + // when doing a newline, take everything to the right of the cursor from the current line + // and move it to the next line. + let (row, _) = cursor.addr(); + + self.rows.insert(row, String::new()); + cursor.cursor_down(&self); + } } #[derive(Default)]