Row splitting and joining

This commit is contained in:
Timothy Warren 2021-03-10 14:37:58 -05:00
parent a46c474a00
commit 2697d41264
2 changed files with 44 additions and 3 deletions

View File

@ -37,6 +37,11 @@ impl Document {
} }
pub fn insert(&mut self, at: &Position, c: char) { pub fn insert(&mut self, at: &Position, c: char) {
if c == '\n' {
self.insert_newline(at);
return;
}
if at.y == self.len() { if at.y == self.len() {
let mut row = Row::default(); let mut row = Row::default();
row.insert(0, c); row.insert(0, c);
@ -48,11 +53,32 @@ impl Document {
} }
pub fn delete(&mut self, at: &Position) { pub fn delete(&mut self, at: &Position) {
if at.y >= self.len() { let len = self.len();
if at.y >= len {
return return
} }
let row = self.rows.get_mut(at.y).unwrap(); if at.x == self.rows.get_mut(at.y).unwrap().len() && at.y < len - 1 {
row.delete(at.x); 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);
}
}
fn insert_newline(&mut self, at: &Position) {
if at.y > self.len() {
return;
}
if at.y == self.len() {
self.rows.push(Row::default());
return;
}
let new_row = self.rows.get_mut(at.y).unwrap().split(at.x);
self.rows.insert(at.y + 1, new_row);
} }
} }

View File

@ -83,4 +83,19 @@ impl Row {
self.update_len(); self.update_len();
} }
pub fn append(&mut self, new: &Self) {
self.string = format!("{}{}", self.string, new.string);
self.update_len();
}
pub fn split(&mut self, at: usize) -> Self {
let beginning: String = self.string[..].graphemes(true).take(at).collect();
let remainder: String = self.string[..].graphemes(true).skip(at).collect();
self.string = beginning;
self.update_len();
Self::from(&remainder[..])
}
} }