Created
August 10, 2018 15:17
-
-
Save adrianparvino/912cce6328a6c7b870f67517041197df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cmp; | |
/// Position within a line | |
pub type Pos = usize; | |
/// Text zipper | |
pub struct Zip<'a> { | |
/// Lines before the current line | |
prev: Vec<&'a str>, | |
/// Position within a line | |
pos: Pos, | |
/// Current working line | |
cur: String, | |
/// Lines after the current line, reversed | |
next: Vec<&'a str> | |
} | |
impl<'a> Zip<'a> { | |
pub fn new() -> Self { | |
Zip { | |
prev: Vec::new(), | |
pos: 0, | |
cur: "".to_string(), | |
next: Vec::new() | |
} | |
} | |
pub fn print(&self, editor_line : Pos) { | |
for str in (self.prev.iter().take(editor_line)) { | |
println!("{}", str); | |
} | |
} | |
pub fn to_string(&self) -> String { | |
let mut str = self.prev.clone(); | |
str.push(&self.cur); | |
str.extend(self.next.iter()); | |
str.join("\n") | |
} | |
pub fn from_string(str: &'a str) -> Self { | |
let mut strs = str.split("\n"); | |
let cur = strs.next().unwrap().to_string(); | |
let mut next = Vec::new(); | |
for str in strs { | |
next.push(str); | |
} | |
Zip { | |
prev: Vec::new(), | |
pos: 0, | |
cur, | |
next | |
} | |
} | |
pub fn new_line_before(&mut self) { | |
self.prev.push(""); | |
} | |
pub fn new_line_after(&mut self) { | |
self.next.push(""); | |
} | |
pub fn insert(&mut self, | |
str: &str) { | |
let mut strs = str.split("\n"); | |
let str = strs.next().unwrap(); | |
self.cur.insert_str(self.pos, str); | |
self.pos += str.len(); | |
// let tail = &self.cur.split_off(self.pos); | |
// for str in strs { | |
// { | |
// self.prev.push(&self.cur); | |
// } | |
// self.cur = str.to_string(); | |
// self.pos = str.len(); | |
// } | |
// self.cur.insert_str(self.pos, tail); | |
} | |
pub fn down(&mut self) { | |
match self.next.pop() { | |
Some (cur_) => { | |
self.cur = cur_.to_string(); | |
} | |
_ => {} | |
} | |
} | |
pub fn up(&'a mut self) { | |
match self.prev.pop() { | |
Some (cur_) => { | |
self.next.push(&self.cur); | |
self.cur = cur_.to_string(); | |
self.pos = cmp::min(self.pos, self.cur.len()); | |
} | |
_ => {} | |
} | |
} | |
pub fn left(&mut self) { | |
if (self.pos == 0) { return; } | |
self.pos -= 1; | |
} | |
pub fn right(&mut self) { | |
if (self.pos == self.cur.len()) { return; } | |
self.pos += 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment