curd-editor 0.8.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, selection, search and replace, a git menu, and language-server colours, errors and completion
//! What was typed and deleted, so it can be undone and redone.
//!
//! Every change to the text is one character (or line break) going in or
//! coming out. A `Step` is the run of them that one undo takes back: a word
//! typed in one go, a paste, a snippet.

#[cfg(test)]
mod tests;

/// One character put in or taken out at column `x` of line `y`. A line
/// break is the character `'\n'`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Change {
    Insert { x: usize, y: usize, c: char },
    Delete { x: usize, y: usize, c: char },
}

/// The changes one undo takes back, and where the cursor was before and
/// after them.
#[derive(Clone, Debug, PartialEq)]
pub struct Step {
    pub changes: Vec<Change>,
    pub before: (usize, usize),
    pub after: (usize, usize),
    /// Plain typing, which joins up with more typing right after it.
    typing: bool,
}

pub struct History {
    done: Vec<Step>,
    undone: Vec<Step>,
    /// The step being recorded while a key is handled.
    open: Option<Step>,
    /// How many steps were done when the file was last saved (or opened).
    /// `None` when that point can no longer be reached by undo or redo.
    saved: Option<usize>,
    /// True right after a save: the next typing starts a step of its own,
    /// so undo can return to exactly what was saved.
    sealed: bool,
}

impl Default for History {
    fn default() -> Self {
        Self {
            done: Vec::new(),
            undone: Vec::new(),
            open: None,
            saved: Some(0),
            sealed: false,
        }
    }
}

impl History {
    /// Starts recording a step, with the cursor at `cursor`.
    pub fn begin(&mut self, cursor: (usize, usize), typing: bool) {
        self.open = Some(Step {
            changes: Vec::new(),
            before: cursor,
            after: cursor,
            typing,
        });
    }

    /// Notes a change. Outside a step (while undoing, say) it is ignored.
    pub fn record(&mut self, change: Change) {
        if let Some(step) = &mut self.open {
            step.changes.push(change);
        }
    }

    /// Ends the step, with the cursor now at `cursor`. A step that changed
    /// nothing is dropped.
    pub fn commit(&mut self, cursor: (usize, usize)) {
        let Some(mut step) = self.open.take().filter(|step| !step.changes.is_empty()) else {
            return;
        };
        step.after = cursor;
        // A new change means the undone steps can no longer be redone.
        self.undone.clear();
        if self.saved.is_some_and(|saved| saved > self.done.len()) {
            self.saved = None;
        }
        match self.done.last_mut() {
            Some(last) if last.typing && step.typing && last.after == step.before && !self.sealed => {
                last.changes.append(&mut step.changes);
                last.after = step.after;
            }
            _ => self.done.push(step),
        }
        self.sealed = false;
    }

    /// The step to take back, if there is one.
    pub fn undo(&mut self) -> Option<Step> {
        self.open = None;
        let step = self.done.pop()?;
        self.undone.push(step.clone());
        Some(step)
    }

    /// The step to do again, if one was just undone.
    pub fn redo(&mut self) -> Option<Step> {
        self.open = None;
        let step = self.undone.pop()?;
        self.done.push(step.clone());
        Some(step)
    }

    /// Notes that the text as it is now is what is on disk.
    pub fn mark_saved(&mut self) {
        self.saved = Some(self.done.len());
        self.sealed = true;
    }

    /// True when the text is back to what is on disk.
    pub fn is_saved(&self) -> bool {
        self.saved == Some(self.done.len())
    }
}