1use crate::change::ChangeSet;
4use crate::editor::EditorId;
5use crate::selection::Selections;
6
7#[derive(Clone, Debug)]
9pub struct Transaction {
10 pub changes: ChangeSet,
11 pub inverse: ChangeSet,
12 pub before: Selections,
13 pub after: Selections,
14 pub origin: EditorId,
16}
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum EditKind {
21 Typing,
23 Deleting,
25 Other,
27}
28
29#[derive(Clone, Debug)]
31pub struct UndoStep {
32 pub transactions: Vec<Transaction>,
33 kind: EditKind,
34}
35
36#[derive(Clone, Debug)]
37pub struct History {
38 undo: Vec<UndoStep>,
39 redo: Vec<UndoStep>,
40 group_open: bool,
41 limit: usize,
42}
43
44impl Default for History {
45 fn default() -> Self {
46 Self::with_limit(1000)
47 }
48}
49
50impl History {
51 pub fn with_limit(limit: usize) -> Self {
53 Self { undo: Vec::new(), redo: Vec::new(), group_open: false, limit: limit.max(1) }
54 }
55
56 pub fn push(&mut self, tx: Transaction, kind: EditKind) {
57 self.redo.clear();
58 match self.undo.last_mut() {
59 Some(step)
60 if self.group_open
61 && kind != EditKind::Other
62 && step.kind == kind
63 && step.transactions.last().is_some_and(|t| t.origin == tx.origin) =>
64 {
65 step.transactions.push(tx);
66 }
67 _ => {
68 self.undo.push(UndoStep { transactions: vec![tx], kind });
69 if self.undo.len() > self.limit {
70 self.undo.remove(0);
71 }
72 }
73 }
74 self.group_open = true;
75 }
76
77 pub fn break_group(&mut self) {
80 self.group_open = false;
81 }
82
83 pub fn can_undo(&self) -> bool {
84 !self.undo.is_empty()
85 }
86
87 pub fn can_redo(&self) -> bool {
88 !self.redo.is_empty()
89 }
90
91 pub(crate) fn pop_undo(&mut self) -> Option<UndoStep> {
92 self.group_open = false;
93 self.undo.pop()
94 }
95
96 pub(crate) fn pop_redo(&mut self) -> Option<UndoStep> {
97 self.group_open = false;
98 self.redo.pop()
99 }
100
101 pub(crate) fn push_redo(&mut self, step: UndoStep) {
102 self.redo.push(step);
103 }
104
105 pub(crate) fn push_undo(&mut self, step: UndoStep) {
106 self.undo.push(step);
107 }
108}