1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use crate::{
    selection::SelectionSet,
    session::SessionId,
    text::{Edit, Text},
};

#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub struct History {
    text: Text,
    current_desc: Option<GroupDesc>,
    undo_stack: Stack,
    redo_stack: Stack,
}

impl History {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn as_text(&self) -> &Text {
        &self.text
    }

    pub fn force_new_group(&mut self) {
        self.current_desc = None;
    }

    pub fn push_or_extend_group(
        &mut self,
        session_id: SessionId,
        edit_kind: EditKind,
        selections: &SelectionSet,
    ) {
        let desc = GroupDesc {
            session_id,
            edit_kind,
        };
        if !self
            .current_desc
            .map_or(false, |current_desc| current_desc.can_merge_with(desc))
        {
            self.undo_stack.push_group(selections.clone());
            self.current_desc = Some(desc);
        }
    }

    pub fn apply_edit(&mut self, edit: Edit) {
        let inverted_edit = edit.clone().invert(&self.text);
        self.text.apply_change(edit.change);
        self.undo_stack.push_edit(inverted_edit);
        self.redo_stack.clear();
    }

    pub fn undo(
        &mut self,
        selections: &SelectionSet,
        edits: &mut Vec<Edit>,
    ) -> Option<SelectionSet> {
        if let Some(new_selections) = self.undo_stack.pop_group(edits) {
            self.redo_stack.push_group(selections.clone());
            for edit in edits {
                let inverted_edit = edit.clone().invert(&self.text);
                self.text.apply_change(edit.change.clone());
                self.redo_stack.push_edit(inverted_edit);
            }
            self.current_desc = None;
            Some(new_selections)
        } else {
            None
        }
    }

    pub fn redo(
        &mut self,
        selections: &SelectionSet,
        edits: &mut Vec<Edit>,
    ) -> Option<SelectionSet> {
        if let Some(new_selections) = self.redo_stack.pop_group(edits) {
            self.undo_stack.push_group(selections.clone());
            for edit in edits {
                let inverted_edit = edit.clone().invert(&self.text);
                self.text.apply_change(edit.change.clone());
                self.undo_stack.push_edit(inverted_edit);
            }
            self.current_desc = None;
            Some(new_selections)
        } else {
            None
        }
    }

    pub fn into_text(self) -> Text {
        self.text
    }
}

impl From<Text> for History {
    fn from(text: Text) -> Self {
        Self {
            text,
            ..Self::default()
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum EditKind {
    Insert,
    InsertSpace,
    Delete,
    Indent,
    Outdent,
    Other,
}

impl EditKind {
    fn can_merge_with(self, other: Self) -> bool {
        if self == Self::Other {
            return false;
        }
        self == other
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct GroupDesc {
    session_id: SessionId,
    edit_kind: EditKind,
}

impl GroupDesc {
    fn can_merge_with(self, other: GroupDesc) -> bool {
        self.session_id == other.session_id && self.edit_kind.can_merge_with(other.edit_kind)
    }
}

#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
struct Stack {
    groups: Vec<Group>,
    edits: Vec<Edit>,
}

impl Stack {
    fn push_group(&mut self, selections: SelectionSet) {
        self.groups.push(Group {
            selections,
            edit_start: self.edits.len(),
        });
    }

    fn push_edit(&mut self, edit: Edit) {
        self.edits.push(edit);
    }

    fn pop_group(&mut self, edits: &mut Vec<Edit>) -> Option<SelectionSet> {
        match self.groups.pop() {
            Some(group) => {
                edits.extend(self.edits.drain(group.edit_start..).rev());
                Some(group.selections)
            }
            None => None,
        }
    }

    fn clear(&mut self) {
        self.groups.clear();
        self.edits.clear();
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct Group {
    selections: SelectionSet,
    edit_start: usize,
}