Skip to content

Commit

Permalink
Make history example into an interactive client example
Browse files Browse the repository at this point in the history
  • Loading branch information
evenorog committed Sep 21, 2023
1 parent 0281392 commit d01c3a5
Showing 1 changed file with 46 additions and 28 deletions.
74 changes: 46 additions & 28 deletions examples/history.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,56 @@
use chrono::{DateTime, Local};
use std::io;
use std::io::BufRead;
use std::time::SystemTime;
use undo::{Add, History};
use undo::{Add, At, History};

fn custom_st_fmt(_: SystemTime, at: SystemTime) -> String {
let dt = DateTime::<Local>::from(at);
dt.format("%H:%M:%S").to_string()
}

fn main() {
let mut target = String::new();
let mut history = History::new();

history.edit(&mut target, Add('a'));
history.edit(&mut target, Add('b'));
history.edit(&mut target, Add('c'));
assert_eq!(target, "abc");

let abc = history.head();

history.undo(&mut target);
assert_eq!(target, "ab");

history.edit(&mut target, Add('d'));
history.edit(&mut target, Add('e'));
history.edit(&mut target, Add('f'));
assert_eq!(target, "abdef");
fn main() -> io::Result<()> {
let stdin = io::stdin();
let mut stdin = stdin.lock();

let abdef = history.head();

history.go_to(&mut target, abc);
assert_eq!(target, "abc");

history.go_to(&mut target, abdef);
assert_eq!(target, "abdef");

println!("{}", history.display().set_st_fmt(&custom_st_fmt));
let mut target = String::new();
let mut record = History::new();
loop {
println!("Enter a string to edit. Use '-' to undo, '+' to redo, and '! i-j' for goto: ");
let mut string = String::new();
let n = stdin.read_line(&mut string)?;
if n == 0 {
return Ok(());
}

// Clears the terminal.
print!("{}c", 27 as char);

let mut chars = string.trim().chars();
while let Some(c) = chars.next() {
if c == '!' {
let rest = chars.collect::<String>();
let mut at = rest
.trim()
.split('-')
.filter_map(|n| n.parse::<usize>().ok());

if let (Some(root), Some(index)) = (at.next(), at.next()) {
record.go_to(&mut target, At::new(root, index));
} else {
println!("Expected input as '! i-j', e.g. '! 1-5'.\n");
}
break;
} else if c == '<' {
record.undo(&mut target);
} else if c == '>' {
record.redo(&mut target);
} else {
record.edit(&mut target, Add(c));
}
}

println!("{}\n", record.display().set_st_fmt(&custom_st_fmt));
println!("Target: {target}");
}
}

0 comments on commit d01c3a5

Please sign in to comment.