use super::buffer::TextBuffer;
use super::position::{Position, Range};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Edit {
pub range: Range,
pub removed: String,
pub inserted: String,
pub inserted_end: Position,
pub cursor_before: Position,
pub cursor_after: Position,
}
impl Edit {
pub fn inserted_range(&self) -> Range {
Range::new(self.range.start, self.inserted_end)
}
pub fn apply(&self, buffer: &mut TextBuffer) {
buffer.replace_range(self.range, &self.inserted);
}
pub fn revert(&self, buffer: &mut TextBuffer) {
buffer.replace_range(self.inserted_range(), &self.removed);
}
pub fn is_pure_insert(&self) -> bool {
self.removed.is_empty() && !self.inserted.is_empty()
}
pub fn is_pure_delete(&self) -> bool {
self.inserted.is_empty() && !self.removed.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Group {
edits: Vec<Edit>,
state_id: u64,
}
impl Group {
pub fn edits(&self) -> &[Edit] {
&self.edits
}
pub fn state_id(&self) -> u64 {
self.state_id
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Restored {
pub cursor: Position,
}
#[derive(Debug, Clone, Default)]
pub struct History {
undo_stack: Vec<Group>,
redo_stack: Vec<Group>,
pending: Vec<Edit>,
next_state_id: u64,
saved_state_id: u64,
}
impl History {
pub fn new() -> Self {
Self {
undo_stack: Vec::new(),
redo_stack: Vec::new(),
pending: Vec::new(),
next_state_id: 1,
saved_state_id: 0,
}
}
pub fn record(&mut self, edit: Edit) {
self.redo_stack.clear();
self.pending.push(edit);
}
pub fn seal(&mut self) {
if self.pending.is_empty() {
return;
}
let edits = std::mem::take(&mut self.pending);
let state_id = self.next_state_id;
self.next_state_id += 1;
self.undo_stack.push(Group { edits, state_id });
}
pub fn undo(&mut self, buffer: &mut TextBuffer) -> Option<Restored> {
self.seal();
let group = self.undo_stack.pop()?;
for edit in group.edits.iter().rev() {
edit.revert(buffer);
}
let cursor = group
.edits
.first()
.map_or(Position::ORIGIN, |edit| edit.cursor_before);
self.redo_stack.push(group);
Some(Restored { cursor })
}
pub fn redo(&mut self, buffer: &mut TextBuffer) -> Option<Restored> {
let group = self.redo_stack.pop()?;
for edit in &group.edits {
edit.apply(buffer);
}
let cursor = group
.edits
.last()
.map_or(Position::ORIGIN, |edit| edit.cursor_after);
self.undo_stack.push(group);
Some(Restored { cursor })
}
pub fn can_undo(&self) -> bool {
!self.undo_stack.is_empty() || !self.pending.is_empty()
}
pub fn can_redo(&self) -> bool {
!self.redo_stack.is_empty()
}
pub fn current_state_id(&self) -> u64 {
if !self.pending.is_empty() {
return u64::MAX;
}
self.undo_stack.last().map_or(0, Group::state_id)
}
pub fn mark_saved(&mut self) {
self.seal();
self.saved_state_id = self.current_state_id();
}
pub fn is_modified(&self) -> bool {
self.current_state_id() != self.saved_state_id
}
pub fn undo_depth(&self) -> usize {
self.undo_stack.len()
}
pub fn redo_depth(&self) -> usize {
self.redo_stack.len()
}
pub fn reset(&mut self) {
self.undo_stack.clear();
self.redo_stack.clear();
self.pending.clear();
self.next_state_id = 1;
self.saved_state_id = 0;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn edit(
buffer: &mut TextBuffer,
history: &mut History,
range: Range,
text: &str,
cursor_before: Position,
) {
let result = buffer.replace_range(range, text);
history.record(Edit {
range,
removed: result.removed,
inserted: text.to_owned(),
inserted_end: result.end,
cursor_before,
cursor_after: result.end,
});
}
#[test]
fn undo_restores_the_previous_text() {
let mut buffer = TextBuffer::from_text("mov rax, 1");
let mut history = History::new();
let range = Range::new(Position::new(0, 4), Position::new(0, 7));
edit(&mut buffer, &mut history, range, "rbx", Position::new(0, 7));
assert_eq!(buffer.to_text(), "mov rbx, 1");
let restored = history.undo(&mut buffer).expect("undo available");
assert_eq!(buffer.to_text(), "mov rax, 1");
assert_eq!(restored.cursor, Position::new(0, 7));
}
#[test]
fn redo_reapplies_an_undone_edit() {
let mut buffer = TextBuffer::from_text("ret");
let mut history = History::new();
edit(
&mut buffer,
&mut history,
Range::empty(Position::new(0, 3)),
"\nnop",
Position::new(0, 3),
);
history.undo(&mut buffer);
assert_eq!(buffer.to_text(), "ret");
let restored = history.redo(&mut buffer).expect("redo available");
assert_eq!(buffer.to_text(), "ret\nnop");
assert_eq!(restored.cursor, Position::new(1, 3));
}
#[test]
fn a_sealed_group_undoes_as_one_step() {
let mut buffer = TextBuffer::new();
let mut history = History::new();
for (index, ch) in "mov".chars().enumerate() {
edit(
&mut buffer,
&mut history,
Range::empty(Position::new(0, index)),
&ch.to_string(),
Position::new(0, index),
);
}
history.seal();
assert_eq!(history.undo_depth(), 1, "typing burst is one undo step");
history.undo(&mut buffer);
assert_eq!(buffer.to_text(), "");
}
#[test]
fn sealing_splits_edits_into_separate_steps() {
let mut buffer = TextBuffer::new();
let mut history = History::new();
edit(
&mut buffer,
&mut history,
Range::empty(Position::ORIGIN),
"mov",
Position::ORIGIN,
);
history.seal();
edit(
&mut buffer,
&mut history,
Range::empty(Position::new(0, 3)),
" rax",
Position::new(0, 3),
);
history.seal();
assert_eq!(history.undo_depth(), 2);
history.undo(&mut buffer);
assert_eq!(buffer.to_text(), "mov");
history.undo(&mut buffer);
assert_eq!(buffer.to_text(), "");
}
#[test]
fn sealing_an_empty_group_creates_no_undo_step() {
let mut history = History::new();
history.seal();
history.seal();
assert_eq!(history.undo_depth(), 0);
assert!(!history.can_undo());
}
#[test]
fn recording_after_undo_discards_the_redo_stack() {
let mut buffer = TextBuffer::from_text("a");
let mut history = History::new();
edit(
&mut buffer,
&mut history,
Range::empty(Position::new(0, 1)),
"b",
Position::new(0, 1),
);
history.seal();
history.undo(&mut buffer);
assert!(history.can_redo());
edit(
&mut buffer,
&mut history,
Range::empty(Position::new(0, 1)),
"c",
Position::new(0, 1),
);
assert!(!history.can_redo(), "new edit invalidates the redo future");
}
#[test]
fn undoing_back_to_the_save_point_clears_the_modified_flag() {
let mut buffer = TextBuffer::from_text("section .text");
let mut history = History::new();
assert!(!history.is_modified());
let end = buffer.end_position();
edit(
&mut buffer,
&mut history,
Range::empty(end),
"\nglobal _start",
end,
);
history.seal();
assert!(history.is_modified());
history.undo(&mut buffer);
assert!(
!history.is_modified(),
"undoing to the saved content must clear the modified flag"
);
}
#[test]
fn saving_after_edits_clears_the_modified_flag() {
let mut buffer = TextBuffer::from_text("nop");
let mut history = History::new();
edit(
&mut buffer,
&mut history,
Range::empty(Position::new(0, 3)),
"\nret",
Position::new(0, 3),
);
history.mark_saved();
assert!(!history.is_modified());
history.undo(&mut buffer);
assert!(
history.is_modified(),
"undoing past the save point marks the buffer modified"
);
}
#[test]
fn unsealed_edits_count_as_modified() {
let mut buffer = TextBuffer::from_text("nop");
let mut history = History::new();
edit(
&mut buffer,
&mut history,
Range::empty(Position::new(0, 3)),
"!",
Position::new(0, 3),
);
assert!(history.is_modified());
assert!(history.can_undo());
}
#[test]
fn repeated_undo_and_redo_converge_on_the_same_text() {
let original = "_start:\n mov rax, 60\n xor edi, edi\n syscall\n";
let mut buffer = TextBuffer::from_text(original);
let mut history = History::new();
edit(
&mut buffer,
&mut history,
Range::new(Position::new(1, 8), Position::new(1, 11)),
"rdi",
Position::new(1, 11),
);
history.seal();
edit(
&mut buffer,
&mut history,
Range::new(Position::new(2, 4), Position::new(2, 16)),
"mov edi, 7",
Position::new(2, 16),
);
history.seal();
let edited = buffer.to_text();
for _ in 0..3 {
while history.undo(&mut buffer).is_some() {}
assert_eq!(buffer.to_text(), original);
while history.redo(&mut buffer).is_some() {}
assert_eq!(buffer.to_text(), edited);
}
}
#[test]
fn undo_on_empty_history_reports_nothing_to_do() {
let mut buffer = TextBuffer::from_text("ret");
let mut history = History::new();
assert!(history.undo(&mut buffer).is_none());
assert!(history.redo(&mut buffer).is_none());
assert_eq!(buffer.to_text(), "ret");
}
#[test]
fn reset_clears_every_stack() {
let mut buffer = TextBuffer::from_text("a");
let mut history = History::new();
edit(
&mut buffer,
&mut history,
Range::empty(Position::new(0, 1)),
"b",
Position::new(0, 1),
);
history.seal();
history.reset();
assert!(!history.can_undo());
assert!(!history.can_redo());
assert!(!history.is_modified());
}
#[test]
fn edit_classification_distinguishes_insert_from_delete() {
let insert = Edit {
range: Range::empty(Position::ORIGIN),
removed: String::new(),
inserted: "x".into(),
inserted_end: Position::new(0, 1),
cursor_before: Position::ORIGIN,
cursor_after: Position::new(0, 1),
};
assert!(insert.is_pure_insert());
assert!(!insert.is_pure_delete());
let delete = Edit {
range: Range::new(Position::ORIGIN, Position::new(0, 1)),
removed: "x".into(),
inserted: String::new(),
inserted_end: Position::ORIGIN,
cursor_before: Position::new(0, 1),
cursor_after: Position::ORIGIN,
};
assert!(delete.is_pure_delete());
assert!(!delete.is_pure_insert());
}
}