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 let tx = self.undo_stack.pop()?;
162
163 for op in tx.operations.iter().rev() {
165 match op {
166 EditOperation::Insert { pos, text } => {
167 let lines: Vec<&str> = text.split('\n').collect();
169 let end_line = pos.line + lines.len() - 1;
170 let end_col = if lines.len() == 1 {
171 pos.col + lines[0].len()
172 } else {
173 lines[lines.len() - 1].len()
174 };
175 buffer.delete_range(pos.line, pos.col, end_line, end_col);
176 }
177 EditOperation::Delete { start, text, .. } => {
178 buffer.insert_str(start.line, start.col, text);
180 }
181 }
182 }
183
184 let restore_cursors = tx.before_cursors.clone();
185 self.redo_stack.push(tx);
186 Some(restore_cursors)
187 }
188
189 pub fn redo(&mut self, buffer: &mut LineBuffer) -> Option<Vec<Selection>> {
191 let tx = self.redo_stack.pop()?;
192
193 for op in &tx.operations {
194 match op {
195 EditOperation::Insert { pos, text } => {
196 buffer.insert_str(pos.line, pos.col, text);
197 }
198 EditOperation::Delete { start, end, .. } => {
199 buffer.delete_range(start.line, start.col, end.line, end.col);
200 }
201 }
202 }
203
204 let restore_cursors = tx.after_cursors.clone();
205 self.undo_stack.push(tx);
206 Some(restore_cursors)
207 }
208}