1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
use crate::text_input::{Cursor, Value}; pub struct Editor<'a> { value: &'a mut Value, cursor: &'a mut Cursor, } impl<'a> Editor<'a> { pub fn new(value: &'a mut Value, cursor: &'a mut Cursor) -> Editor<'a> { Editor { value, cursor } } pub fn contents(&self) -> String { self.value.to_string() } pub fn insert(&mut self, character: char) { match self.cursor.selection(self.value) { Some((left, right)) => { self.cursor.move_left(self.value); self.value.remove_many(left, right); } _ => (), } self.value.insert(self.cursor.end(self.value), character); self.cursor.move_right(self.value); } pub fn paste(&mut self, content: Value) { let length = content.len(); match self.cursor.selection(self.value) { Some((left, right)) => { self.cursor.move_left(self.value); self.value.remove_many(left, right); } _ => (), } self.value.insert_many(self.cursor.end(self.value), content); self.cursor.move_right_by_amount(self.value, length); } pub fn backspace(&mut self) { match self.cursor.selection(self.value) { Some((start, end)) => { self.cursor.move_left(self.value); self.value.remove_many(start, end); } None => { let start = self.cursor.start(self.value); if start > 0 { self.cursor.move_left(self.value); self.value.remove(start - 1); } } } } pub fn delete(&mut self) { match self.cursor.selection(self.value) { Some(_) => { self.backspace(); } None => { let end = self.cursor.end(self.value); if end < self.value.len() { self.value.remove(end); } } } } }