1use crate::buffer::LineBuffer;
4use crate::cursor::{Position, Selection};
5
6#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum EditOperation {
9 Insert {
10 pos: Position,
11 text: String,
12 },
13 Delete {
14 start: Position,
15 end: Position,
16 text: String,
17 },
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct EditorTransaction {
23 pub operations: Vec<EditOperation>,
24 pub before_cursors: Vec<Selection>,
25 pub after_cursors: Vec<Selection>,
26 pub timestamp_ms: u64,
27}
28
29impl EditorTransaction {
30 pub fn new(
31 operations: Vec<EditOperation>,
32 before_cursors: Vec<Selection>,
33 after_cursors: Vec<Selection>,
34 ) -> Self {
35 let timestamp_ms = std::time::SystemTime::now()
36 .duration_since(std::time::UNIX_EPOCH)
37 .map_or(0, |d| d.as_millis() as u64);
38
39 Self {
40 operations,
41 before_cursors,
42 after_cursors,
43 timestamp_ms,
44 }
45 }
46}
47
48#[derive(Debug, Clone)]
50pub struct HistoryStack {
51 undo_stack: Vec<EditorTransaction>,
52 redo_stack: Vec<EditorTransaction>,
53 max_depth: usize,
54}
55
56impl Default for HistoryStack {
57 fn default() -> Self {
58 Self::new(1000)
59 }
60}
61
62impl HistoryStack {
63 pub fn new(max_depth: usize) -> Self {
64 Self {
65 undo_stack: Vec::new(),
66 redo_stack: Vec::new(),
67 max_depth,
68 }
69 }
70
71 pub fn can_undo(&self) -> bool {
72 !self.undo_stack.is_empty()
73 }
74
75 pub fn can_redo(&self) -> bool {
76 !self.redo_stack.is_empty()
77 }
78
79 pub fn record_insert(
81 &mut self,
82 pos: Position,
83 text: &str,
84 before_cursors: Vec<Selection>,
85 after_cursors: Vec<Selection>,
86 ) {
87 self.redo_stack.clear();
88 let now_ms = std::time::SystemTime::now()
89 .duration_since(std::time::UNIX_EPOCH)
90 .map_or(0, |d| d.as_millis() as u64);
91
92 if let Some(last) = self.undo_stack.last_mut() {
94 if now_ms.saturating_sub(last.timestamp_ms) < 400 && last.operations.len() == 1 {
95 if let EditOperation::Insert {
96 text: ref mut prev_text,
97 ..
98 } = last.operations[0]
99 {
100 if !prev_text.contains('\n') && !text.contains('\n') {
101 prev_text.push_str(text);
102 last.after_cursors = after_cursors;
103 last.timestamp_ms = now_ms;
104 return;
105 }
106 }
107 }
108 }
109
110 let tx = EditorTransaction {
111 operations: vec![EditOperation::Insert {
112 pos,
113 text: text.to_string(),
114 }],
115 before_cursors,
116 after_cursors,
117 timestamp_ms: now_ms,
118 };
119
120 self.push_transaction(tx);
121 }
122
123 pub fn record_delete(
125 &mut self,
126 start: Position,
127 end: Position,
128 text: &str,
129 before_cursors: Vec<Selection>,
130 after_cursors: Vec<Selection>,
131 ) {
132 self.redo_stack.clear();
133 let now_ms = std::time::SystemTime::now()
134 .duration_since(std::time::UNIX_EPOCH)
135 .map_or(0, |d| d.as_millis() as u64);
136
137 let tx = EditorTransaction {
138 operations: vec![EditOperation::Delete {
139 start,
140 end,
141 text: text.to_string(),
142 }],
143 before_cursors,
144 after_cursors,
145 timestamp_ms: now_ms,
146 };
147
148 self.push_transaction(tx);
149 }
150
151 pub fn push_transaction(&mut self, tx: EditorTransaction) {
153 if self.undo_stack.len() >= self.max_depth {
154 self.undo_stack.remove(0);
155 }
156 self.undo_stack.push(tx);
157 }
158
159 pub fn undo(&mut self, buffer: &mut LineBuffer) -> Option<Vec<Selection>> {
161 self.undo_with_edits(buffer).map(|(cursors, _)| cursors)
162 }
163
164 pub fn undo_with_edits(
167 &mut self,
168 buffer: &mut LineBuffer,
169 ) -> Option<(Vec<Selection>, Vec<tree_sitter::InputEdit>)> {
170 let tx = self.undo_stack.pop()?;
171 let mut edits = Vec::with_capacity(tx.operations.len());
172
173 for op in tx.operations.iter().rev() {
175 match op {
176 EditOperation::Insert { pos, text } => {
177 let lines: Vec<&str> = text.split('\n').collect();
179 let end_line = pos.line + lines.len() - 1;
180 let end_col = if lines.len() == 1 {
181 pos.col + lines[0].chars().count()
182 } else {
183 lines[lines.len() - 1].chars().count()
184 };
185 let end = Position::new(end_line, end_col);
186 let (edit, _) = buffer.compute_input_edit(*pos, end, "");
187 buffer.delete_range(pos.line, pos.col, end_line, end_col);
188 edits.push(edit);
189 }
190 EditOperation::Delete { start, text, .. } => {
191 let (edit, _) = buffer.compute_input_edit(*start, *start, text);
193 buffer.insert_str(start.line, start.col, text);
194 edits.push(edit);
195 }
196 }
197 }
198
199 let restore_cursors = tx.before_cursors.clone();
200 self.redo_stack.push(tx);
201 Some((restore_cursors, edits))
202 }
203
204 pub fn redo(&mut self, buffer: &mut LineBuffer) -> Option<Vec<Selection>> {
206 self.redo_with_edits(buffer).map(|(cursors, _)| cursors)
207 }
208
209 pub fn redo_with_edits(
212 &mut self,
213 buffer: &mut LineBuffer,
214 ) -> Option<(Vec<Selection>, Vec<tree_sitter::InputEdit>)> {
215 let tx = self.redo_stack.pop()?;
216 let mut edits = Vec::with_capacity(tx.operations.len());
217
218 for op in &tx.operations {
219 match op {
220 EditOperation::Insert { pos, text } => {
221 let (edit, _) = buffer.compute_input_edit(*pos, *pos, text);
222 buffer.insert_str(pos.line, pos.col, text);
223 edits.push(edit);
224 }
225 EditOperation::Delete { start, end, .. } => {
226 let (edit, _) = buffer.compute_input_edit(*start, *end, "");
227 buffer.delete_range(start.line, start.col, end.line, end.col);
228 edits.push(edit);
229 }
230 }
231 }
232
233 let restore_cursors = tx.after_cursors.clone();
234 self.undo_stack.push(tx);
235 Some((restore_cursors, edits))
236 }
237}