Skip to content

Instantly share code, notes, and snippets.

@adrianparvino
Created August 10, 2018 16:00
Show Gist options
  • Save adrianparvino/649b79abd01a39a453cc39a83c2eace0 to your computer and use it in GitHub Desktop.
Save adrianparvino/649b79abd01a39a453cc39a83c2eace0 to your computer and use it in GitHub Desktop.
use std::cmp;
use std::mem;
/// 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;
// 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(&mut self) {
let oldcur = mem::replace(&mut self.cur, "".to_string());
match self.prev.pop() {
Some (newcur) => {
self.cur = newcur.to_string();
self.next.push(oldcur.as_str());
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