iced_code_editor/canvas_editor/editing/history.rs
1//! Command history management for undo/redo functionality.
2//!
3//! This module provides thread-safe command history tracking with configurable
4//! size limits and save point tracking for modified state detection.
5//!
6//! # Examples
7//!
8//! ## Basic Usage
9//!
10//! ```
11//! use iced_code_editor::CommandHistory;
12//!
13//! // Create a history with a limit of 100 operations
14//! let history = CommandHistory::new(100);
15//!
16//! // Check state
17//! assert_eq!(history.undo_count(), 0);
18//! assert_eq!(history.redo_count(), 0);
19//! assert!(!history.can_undo());
20//! ```
21//!
22//! ## Dynamic Configuration
23//!
24//! ```
25//! use iced_code_editor::CommandHistory;
26//!
27//! let history = CommandHistory::new(100);
28//!
29//! // Adjust history size based on available memory
30//! history.set_max_size(500);
31//! assert_eq!(history.max_size(), 500);
32//!
33//! // Clear all history when starting a new document
34//! history.clear();
35//! ```
36//!
37//! ## Save Point Tracking
38//!
39//! ```
40//! use iced_code_editor::CommandHistory;
41//!
42//! let history = CommandHistory::new(100);
43//!
44//! // Mark the current state as saved
45//! history.mark_saved();
46//! assert!(!history.is_modified());
47//!
48//! // After user makes changes...
49//! // history.push(some_command);
50//! // assert!(history.is_modified());
51//! ```
52
53use super::command::{Command, CompositeCommand};
54use crate::buffer::TextBuffer;
55use crate::canvas_editor::CodeEditor;
56use std::collections::VecDeque;
57use std::sync::{Arc, Mutex, MutexGuard};
58
59/// Manages command history for undo/redo operations.
60///
61/// The history maintains two stacks:
62/// - Undo stack: Commands that can be undone
63/// - Redo stack: Commands that can be redone (cleared when new commands are added)
64///
65/// Thread-safe using Arc<Mutex<>> for interior mutability. Cloning shares the
66/// same history: every clone reads and writes the one set of stacks.
67///
68/// No method on this type panics on a poisoned mutex: a poisoned lock is
69/// recovered rather than propagated, so a panic inside one caller's `Command`
70/// cannot leave the history permanently unusable for everyone else.
71///
72/// Each [`CodeEditor`] owns one of these and records every edit into it, so
73/// most applications observe it through [`CodeEditor::can_undo`],
74/// [`CodeEditor::is_modified`], and the [`Message::Undo`] / [`Message::Redo`]
75/// messages rather than constructing one directly.
76///
77/// # Example
78///
79/// ```
80/// use iced_code_editor::{CodeEditor, Message};
81///
82/// let mut editor = CodeEditor::new("hello", "rs");
83/// assert!(!editor.can_undo());
84///
85/// let _ = editor.update(&Message::Paste(" world".to_string()));
86/// assert!(editor.can_undo());
87/// assert!(editor.is_modified());
88///
89/// let _ = editor.update(&Message::Undo);
90/// assert_eq!(editor.content(), "hello");
91/// assert!(editor.can_redo());
92/// ```
93///
94/// [`Message::Undo`]: crate::Message::Undo
95/// [`Message::Redo`]: crate::Message::Redo
96#[derive(Debug, Clone)]
97pub struct CommandHistory {
98 inner: Arc<Mutex<HistoryInner>>,
99}
100
101#[derive(Debug)]
102struct HistoryInner {
103 /// Stack of commands that can be undone
104 undo_stack: VecDeque<Box<dyn Command>>,
105 /// Stack of commands that can be redone
106 redo_stack: Vec<Box<dyn Command>>,
107 /// Maximum number of commands to keep in history
108 max_size: usize,
109 /// Index in undo_stack where document was last saved (None if never saved)
110 save_point: Option<usize>,
111 /// Current composite command being built (for grouping)
112 current_group: Option<CompositeCommand>,
113}
114
115impl HistoryInner {
116 /// Trims `undo_stack` down to `max_size`, discarding the oldest commands
117 /// first and shifting `save_point` to stay aligned with what remains.
118 ///
119 /// If a discarded command was the one marked as the save point, the save
120 /// point is cleared instead, since that saved state is no longer
121 /// reachable via undo.
122 fn enforce_size_limit(&mut self) {
123 while self.undo_stack.len() > self.max_size {
124 self.undo_stack.pop_front();
125 if let Some(ref mut sp) = self.save_point {
126 if *sp > 0 {
127 *sp -= 1;
128 } else {
129 self.save_point = None;
130 }
131 }
132 }
133 }
134}
135
136impl CommandHistory {
137 /// Locks the shared state, recovering the guard if the mutex was poisoned.
138 ///
139 /// Poisoning is reachable here without a second thread. [`Self::undo`] and
140 /// [`Self::redo`] run `Command::undo` / `Command::execute` *while holding
141 /// this guard*, and [`Command`] is a public trait: a panic inside a
142 /// caller-supplied implementation poisons the mutex on this very thread.
143 /// Panicking again on every subsequent lock would turn one recoverable
144 /// mistake into a dead editor, because the render path calls
145 /// [`Self::can_undo`] on each frame and every [`Clone`] of this handle
146 /// shares the same poisoned mutex.
147 ///
148 /// Taking the guard is safe to do here: the only invariant a poisoned
149 /// `HistoryInner` can break is "the undo stack matches the buffer", which a
150 /// caller recovers from with [`Self::clear`]. This matches the policy the
151 /// LSP client applies to its own shared state.
152 fn lock_inner(&self) -> MutexGuard<'_, HistoryInner> {
153 self.inner.lock().unwrap_or_else(|error| error.into_inner())
154 }
155
156 /// Creates a new command history with the specified size limit.
157 ///
158 /// # Arguments
159 ///
160 /// * `max_size` - Maximum number of commands to keep in history
161 ///
162 /// # Returns
163 ///
164 /// A new `CommandHistory` instance
165 ///
166 /// # Example
167 ///
168 /// ```
169 /// use iced_code_editor::CommandHistory;
170 ///
171 /// let history = CommandHistory::new(100);
172 /// ```
173 pub fn new(max_size: usize) -> Self {
174 Self {
175 inner: Arc::new(Mutex::new(HistoryInner {
176 undo_stack: VecDeque::with_capacity(max_size.min(100)),
177 redo_stack: Vec::with_capacity(max_size.min(100)),
178 max_size,
179 save_point: None,
180 current_group: None,
181 })),
182 }
183 }
184
185 /// Adds a command to the history.
186 ///
187 /// This clears the redo stack and adds the command to the undo stack.
188 /// If currently grouping commands, adds to the current group instead.
189 ///
190 /// The `Command` trait is internal to this crate, so an application does
191 /// not call this directly — [`CodeEditor`] pushes a command for each edit
192 /// it performs. The example below shows the observable effect.
193 ///
194 /// # Arguments
195 ///
196 /// * `command` - The command to add
197 ///
198 /// # Example
199 ///
200 /// ```
201 /// use iced_code_editor::{CodeEditor, Message};
202 ///
203 /// let mut editor = CodeEditor::new("hello", "rs");
204 ///
205 /// // Each edit the editor performs pushes a command.
206 /// let _ = editor.update(&Message::Paste("!".to_string()));
207 /// assert!(editor.can_undo());
208 ///
209 /// // Pushing after an undo discards the redo stack: the alternative
210 /// // future is gone once a new edit diverges from it.
211 /// let _ = editor.update(&Message::Undo);
212 /// assert!(editor.can_redo());
213 /// let _ = editor.update(&Message::Paste("?".to_string()));
214 /// assert!(!editor.can_redo());
215 /// ```
216 pub fn push(&self, command: Box<dyn Command>) {
217 let mut inner = self.lock_inner();
218
219 // If we're building a composite, add to it
220 if let Some(ref mut group) = inner.current_group {
221 group.add(command);
222 return;
223 }
224
225 // The save point may sit ahead of the current position (the user
226 // undid past it). Pushing a new command here clears the redo stack,
227 // permanently discarding the path back to that saved state, so the
228 // save point can never be reached again and must be invalidated.
229 // Otherwise, if the new undo stack happens to reach the same length
230 // later, `is_modified()` would wrongly report "not modified" even
231 // though the actual command sequence has diverged.
232 if inner.save_point.is_some_and(|sp| sp > inner.undo_stack.len()) {
233 inner.save_point = None;
234 }
235
236 // Clear redo stack when new command is added
237 inner.redo_stack.clear();
238
239 // Add to undo stack
240 inner.undo_stack.push_back(command);
241
242 inner.enforce_size_limit();
243 }
244
245 /// Undoes the last command.
246 ///
247 /// Any open group is closed first, so an in-progress run of typing undoes
248 /// as one unit rather than being left half-open.
249 ///
250 /// `TextBuffer` is internal to this crate, so an application drives this
251 /// through [`Message::Undo`] rather than calling it directly.
252 ///
253 /// # Arguments
254 ///
255 /// * `buffer` - The text buffer to modify
256 /// * `cursor` - The cursor position to update
257 ///
258 /// # Returns
259 ///
260 /// `true` if a command was undone, `false` if nothing to undo
261 ///
262 /// # Example
263 ///
264 /// ```
265 /// use iced_code_editor::{CodeEditor, Message};
266 ///
267 /// let mut editor = CodeEditor::new("hello", "rs");
268 /// let _ = editor.update(&Message::Paste(" world".to_string()));
269 /// assert_eq!(editor.content(), " worldhello");
270 ///
271 /// let _ = editor.update(&Message::Undo);
272 /// assert_eq!(editor.content(), "hello");
273 ///
274 /// // Undoing with an empty stack is a harmless no-op.
275 /// let _ = editor.update(&Message::Undo);
276 /// assert_eq!(editor.content(), "hello");
277 /// ```
278 ///
279 /// [`Message::Undo`]: crate::Message::Undo
280 pub fn undo(&self, buffer: &mut TextBuffer, cursor: &mut (usize, usize)) -> bool {
281 let mut inner = self.lock_inner();
282
283 // End any current grouping
284 if inner.current_group.is_some() {
285 Self::end_group_internal(&mut inner);
286 }
287
288 if let Some(mut command) = inner.undo_stack.pop_back() {
289 command.undo(buffer, cursor);
290 inner.redo_stack.push(command);
291 true
292 } else {
293 false
294 }
295 }
296
297 /// Redoes the last undone command.
298 ///
299 /// `TextBuffer` is internal to this crate, so an application drives this
300 /// through [`Message::Redo`] rather than calling it directly.
301 ///
302 /// # Arguments
303 ///
304 /// * `buffer` - The text buffer to modify
305 /// * `cursor` - The cursor position to update
306 ///
307 /// # Returns
308 ///
309 /// `true` if a command was redone, `false` if nothing to redo
310 ///
311 /// # Example
312 ///
313 /// ```
314 /// use iced_code_editor::{CodeEditor, Message};
315 ///
316 /// let mut editor = CodeEditor::new("hello", "rs");
317 /// let _ = editor.update(&Message::Paste(" world".to_string()));
318 /// let _ = editor.update(&Message::Undo);
319 /// assert_eq!(editor.content(), "hello");
320 ///
321 /// let _ = editor.update(&Message::Redo);
322 /// assert_eq!(editor.content(), " worldhello");
323 /// ```
324 ///
325 /// [`Message::Redo`]: crate::Message::Redo
326 pub fn redo(&self, buffer: &mut TextBuffer, cursor: &mut (usize, usize)) -> bool {
327 let mut inner = self.lock_inner();
328
329 if let Some(mut command) = inner.redo_stack.pop() {
330 command.execute(buffer, cursor);
331 inner.undo_stack.push_back(command);
332 true
333 } else {
334 false
335 }
336 }
337
338 /// Returns whether there are commands that can be undone.
339 ///
340 /// An open group counts as undoable even before it is closed, so an
341 /// "Undo" menu item stays enabled while the user is mid-word.
342 ///
343 /// # Returns
344 ///
345 /// `true` if undo would do something, `false` otherwise
346 ///
347 /// # Example
348 ///
349 /// ```
350 /// use iced_code_editor::CommandHistory;
351 ///
352 /// let history = CommandHistory::new(100);
353 /// assert!(!history.can_undo());
354 /// ```
355 #[must_use]
356 pub fn can_undo(&self) -> bool {
357 let inner = self.lock_inner();
358 !inner.undo_stack.is_empty() || inner.current_group.is_some()
359 }
360
361 /// Returns whether there are commands that can be redone.
362 ///
363 /// # Returns
364 ///
365 /// `true` if redo would do something, `false` otherwise
366 ///
367 /// # Example
368 ///
369 /// ```
370 /// use iced_code_editor::{CodeEditor, Message};
371 ///
372 /// let mut editor = CodeEditor::new("hello", "rs");
373 /// assert!(!editor.can_redo());
374 ///
375 /// // Redo only becomes available after an undo.
376 /// let _ = editor.update(&Message::Paste("!".to_string()));
377 /// assert!(!editor.can_redo());
378 /// let _ = editor.update(&Message::Undo);
379 /// assert!(editor.can_redo());
380 /// ```
381 #[must_use]
382 pub fn can_redo(&self) -> bool {
383 let inner = self.lock_inner();
384 !inner.redo_stack.is_empty()
385 }
386
387 /// Marks the current position as the save point.
388 ///
389 /// This is used to track whether the document has been modified since
390 /// the last save. Call this after successfully saving the file.
391 ///
392 /// # Example
393 ///
394 /// ```
395 /// use iced_code_editor::{CodeEditor, Message};
396 ///
397 /// let mut editor = CodeEditor::new("hello", "rs");
398 /// let _ = editor.update(&Message::Paste("!".to_string()));
399 /// assert!(editor.is_modified());
400 ///
401 /// // After the host has written the file to disk.
402 /// editor.mark_saved();
403 /// assert!(!editor.is_modified());
404 ///
405 /// // Undoing back past the save point marks the document dirty again.
406 /// let _ = editor.update(&Message::Undo);
407 /// assert!(editor.is_modified());
408 /// ```
409 pub fn mark_saved(&self) {
410 let mut inner = self.lock_inner();
411 inner.save_point = Some(inner.undo_stack.len());
412 }
413
414 /// Returns whether the document has been modified since the last save.
415 ///
416 /// Compares the current undo depth against the depth recorded by
417 /// [`Self::mark_saved`], so undoing back to the saved state reports "not
418 /// modified" again rather than staying permanently dirty.
419 ///
420 /// # Returns
421 ///
422 /// `true` if there are unsaved changes, `false` otherwise
423 ///
424 /// # Example
425 ///
426 /// ```
427 /// use iced_code_editor::CommandHistory;
428 ///
429 /// let history = CommandHistory::new(100);
430 /// // A fresh history has nothing to save.
431 /// assert!(!history.is_modified());
432 /// ```
433 #[must_use]
434 pub fn is_modified(&self) -> bool {
435 let inner = self.lock_inner();
436
437 // If we're currently in a group, we're modified
438 if inner.current_group.is_some() {
439 return true;
440 }
441
442 match inner.save_point {
443 None => !inner.undo_stack.is_empty(),
444 Some(sp) => sp != inner.undo_stack.len(),
445 }
446 }
447
448 /// Clears all history.
449 ///
450 /// This removes all undo/redo commands and resets the save point.
451 /// Useful when starting a new document or resetting the editor state.
452 ///
453 /// # Example
454 ///
455 /// ```
456 /// use iced_code_editor::CommandHistory;
457 ///
458 /// let history = CommandHistory::new(100);
459 /// // ... perform some operations ...
460 ///
461 /// // Clear everything when opening a new document
462 /// history.clear();
463 /// assert_eq!(history.undo_count(), 0);
464 /// assert_eq!(history.redo_count(), 0);
465 /// assert!(!history.is_modified());
466 /// ```
467 pub fn clear(&self) {
468 let mut inner = self.lock_inner();
469 inner.undo_stack.clear();
470 inner.redo_stack.clear();
471 inner.save_point = None;
472 inner.current_group = None;
473 }
474
475 /// Begins grouping subsequent commands into a composite.
476 ///
477 /// All commands added via `push()` will be grouped together until
478 /// `end_group()` is called. This is useful for grouping consecutive
479 /// typing operations, so one undo removes a whole word rather than one
480 /// character at a time.
481 ///
482 /// Calling this while a group is already open does nothing, so grouping
483 /// does not nest.
484 ///
485 /// # Example
486 ///
487 /// ```
488 /// use iced_code_editor::CommandHistory;
489 ///
490 /// let history = CommandHistory::new(100);
491 ///
492 /// history.begin_group();
493 /// // An open group counts as undoable, so an "Undo" menu item stays
494 /// // enabled while the user is still typing.
495 /// assert!(history.can_undo());
496 ///
497 /// // Nothing was actually pushed, so closing it adds no entry.
498 /// history.end_group();
499 /// assert_eq!(history.undo_count(), 0);
500 /// ```
501 pub fn begin_group(&self) {
502 let mut inner = self.lock_inner();
503 if inner.current_group.is_none() {
504 inner.current_group = Some(CompositeCommand::new());
505 }
506 }
507
508 /// Ends the current command grouping.
509 ///
510 /// The grouped commands are added to the history as a single composite
511 /// command, so one undo reverses all of them. If no commands were grouped,
512 /// nothing is added — an empty group leaves no trace.
513 ///
514 /// Safe to call when no group is open.
515 ///
516 /// # Example
517 ///
518 /// ```
519 /// use iced_code_editor::CommandHistory;
520 ///
521 /// let history = CommandHistory::new(100);
522 ///
523 /// history.begin_group();
524 /// history.end_group();
525 /// // An empty group adds nothing to the undo stack.
526 /// assert_eq!(history.undo_count(), 0);
527 /// assert!(!history.can_undo());
528 ///
529 /// // Closing when nothing is open is harmless.
530 /// history.end_group();
531 /// ```
532 pub fn end_group(&self) {
533 let mut inner = self.lock_inner();
534 Self::end_group_internal(&mut inner);
535 }
536
537 /// Internal helper to end grouping (used when lock is already held).
538 fn end_group_internal(inner: &mut HistoryInner) {
539 if let Some(group) = inner.current_group.take()
540 && !group.is_empty()
541 {
542 // See the matching comment in `push`: a save point ahead of the
543 // current position can never be reached again once the redo
544 // stack backing it is cleared here.
545 if inner.save_point.is_some_and(|sp| sp > inner.undo_stack.len()) {
546 inner.save_point = None;
547 }
548
549 // Clear redo stack
550 inner.redo_stack.clear();
551
552 // Add composite to undo stack
553 inner.undo_stack.push_back(Box::new(group));
554
555 inner.enforce_size_limit();
556 }
557 }
558
559 /// Returns the maximum history size.
560 ///
561 /// # Returns
562 ///
563 /// The maximum number of commands that can be stored in history.
564 ///
565 /// # Example
566 ///
567 /// ```
568 /// use iced_code_editor::CommandHistory;
569 ///
570 /// let history = CommandHistory::new(100);
571 /// assert_eq!(history.max_size(), 100);
572 /// ```
573 #[must_use]
574 pub fn max_size(&self) -> usize {
575 let inner = self.lock_inner();
576 inner.max_size
577 }
578
579 /// Sets the maximum history size.
580 ///
581 /// If the current history exceeds the new size, older commands are removed.
582 /// This is useful for adjusting memory usage based on system resources.
583 ///
584 /// # Arguments
585 ///
586 /// * `max_size` - New maximum size (number of commands to keep)
587 ///
588 /// # Example
589 ///
590 /// ```
591 /// use iced_code_editor::CommandHistory;
592 ///
593 /// let history = CommandHistory::new(100);
594 ///
595 /// // Increase limit for memory-rich environments
596 /// history.set_max_size(500);
597 /// assert_eq!(history.max_size(), 500);
598 ///
599 /// // Decrease limit for constrained environments
600 /// history.set_max_size(50);
601 /// assert_eq!(history.max_size(), 50);
602 /// ```
603 pub fn set_max_size(&self, max_size: usize) {
604 let mut inner = self.lock_inner();
605 inner.max_size = max_size;
606 inner.enforce_size_limit();
607 }
608
609 /// Returns the current number of undo operations available.
610 ///
611 /// This can be useful for displaying history statistics or managing
612 /// UI state (e.g., enabling/disabling undo buttons).
613 ///
614 /// # Returns
615 ///
616 /// The number of commands that can be undone.
617 ///
618 /// # Example
619 ///
620 /// ```
621 /// use iced_code_editor::CommandHistory;
622 ///
623 /// let history = CommandHistory::new(100);
624 /// assert_eq!(history.undo_count(), 0);
625 ///
626 /// // After adding commands...
627 /// // assert!(history.undo_count() > 0);
628 /// ```
629 #[must_use]
630 pub fn undo_count(&self) -> usize {
631 let inner = self.lock_inner();
632 inner.undo_stack.len()
633 }
634
635 /// Returns the current number of redo operations available.
636 ///
637 /// This can be useful for displaying history statistics or managing
638 /// UI state (e.g., enabling/disabling redo buttons).
639 ///
640 /// # Returns
641 ///
642 /// The number of commands that can be redone.
643 ///
644 /// # Example
645 ///
646 /// ```
647 /// use iced_code_editor::CommandHistory;
648 ///
649 /// let history = CommandHistory::new(100);
650 /// assert_eq!(history.redo_count(), 0);
651 ///
652 /// // After undoing some commands...
653 /// // assert!(history.redo_count() > 0);
654 /// ```
655 #[must_use]
656 pub fn redo_count(&self) -> usize {
657 let inner = self.lock_inner();
658 inner.redo_stack.len()
659 }
660}
661
662// Implement Default for convenient usage
663impl Default for CommandHistory {
664 fn default() -> Self {
665 Self::new(100)
666 }
667}
668
669impl CodeEditor {
670 /// Returns whether the editor has unsaved changes.
671 ///
672 /// Use this to drive a "modified" indicator in a tab title, or to prompt
673 /// before closing.
674 ///
675 /// # Returns
676 ///
677 /// `true` if there are unsaved modifications, `false` otherwise
678 ///
679 /// # Example
680 ///
681 /// ```
682 /// use iced_code_editor::{CodeEditor, Message};
683 ///
684 /// let mut editor = CodeEditor::new("hello", "rs");
685 /// assert!(!editor.is_modified());
686 ///
687 /// let _ = editor.update(&Message::Paste("!".to_string()));
688 /// assert!(editor.is_modified());
689 /// ```
690 pub fn is_modified(&self) -> bool {
691 self.history.is_modified()
692 }
693
694 /// Marks the current state as saved.
695 ///
696 /// Call this after successfully saving the file to reset the modified state.
697 ///
698 /// # Example
699 ///
700 /// ```
701 /// use iced_code_editor::{CodeEditor, Message};
702 ///
703 /// let mut editor = CodeEditor::new("hello", "rs");
704 /// let _ = editor.update(&Message::Paste("!".to_string()));
705 ///
706 /// editor.mark_saved();
707 /// assert!(!editor.is_modified());
708 /// ```
709 pub fn mark_saved(&mut self) {
710 self.history.mark_saved();
711 }
712
713 /// Returns whether undo is available.
714 ///
715 /// # Returns
716 ///
717 /// `true` if undo would do something, `false` otherwise
718 ///
719 /// # Example
720 ///
721 /// ```
722 /// use iced_code_editor::{CodeEditor, Message};
723 ///
724 /// let mut editor = CodeEditor::new("hello", "rs");
725 /// assert!(!editor.can_undo());
726 ///
727 /// let _ = editor.update(&Message::Paste("!".to_string()));
728 /// assert!(editor.can_undo());
729 /// ```
730 pub fn can_undo(&self) -> bool {
731 self.history.can_undo()
732 }
733
734 /// Returns whether redo is available.
735 ///
736 /// # Returns
737 ///
738 /// `true` if redo would do something, `false` otherwise
739 ///
740 /// # Example
741 ///
742 /// ```
743 /// use iced_code_editor::{CodeEditor, Message};
744 ///
745 /// let mut editor = CodeEditor::new("hello", "rs");
746 /// let _ = editor.update(&Message::Paste("!".to_string()));
747 /// assert!(!editor.can_redo());
748 ///
749 /// let _ = editor.update(&Message::Undo);
750 /// assert!(editor.can_redo());
751 /// ```
752 pub fn can_redo(&self) -> bool {
753 self.history.can_redo()
754 }
755}
756
757#[cfg(test)]
758mod tests {
759 use super::*;
760 use crate::canvas_editor::editing::command::InsertCharCommand;
761
762 #[test]
763 fn test_new_history() {
764 let history = CommandHistory::new(50);
765 assert_eq!(history.max_size(), 50);
766 assert!(!history.can_undo());
767 assert!(!history.can_redo());
768 }
769
770 #[test]
771 fn test_push_and_undo() {
772 let mut buffer = TextBuffer::new("hello");
773 let mut cursor = (0, 5);
774 let history = CommandHistory::new(10);
775
776 let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
777 cmd.execute(&mut buffer, &mut cursor);
778 history.push(Box::new(cmd));
779
780 assert!(history.can_undo());
781 assert_eq!(buffer.line(0), "hello!");
782
783 history.undo(&mut buffer, &mut cursor);
784 assert_eq!(buffer.line(0), "hello");
785 assert_eq!(cursor, (0, 5));
786 }
787
788 #[test]
789 fn test_redo() {
790 let mut buffer = TextBuffer::new("hello");
791 let mut cursor = (0, 5);
792 let history = CommandHistory::new(10);
793
794 let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
795 cmd.execute(&mut buffer, &mut cursor);
796 history.push(Box::new(cmd));
797
798 history.undo(&mut buffer, &mut cursor);
799 assert_eq!(buffer.line(0), "hello");
800
801 assert!(history.can_redo());
802 history.redo(&mut buffer, &mut cursor);
803 assert_eq!(buffer.line(0), "hello!");
804 assert_eq!(cursor, (0, 6));
805 }
806
807 #[test]
808 fn test_save_point() {
809 let mut buffer = TextBuffer::new("hello");
810 let mut cursor = (0, 5);
811 let history = CommandHistory::new(10);
812
813 assert!(!history.is_modified()); // New document is not modified
814
815 let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
816 cmd.execute(&mut buffer, &mut cursor);
817 history.push(Box::new(cmd));
818
819 assert!(history.is_modified()); // Now modified
820
821 history.mark_saved();
822 assert!(!history.is_modified()); // Saved
823
824 let mut cmd2 = InsertCharCommand::new(0, 6, '?', cursor);
825 cmd2.execute(&mut buffer, &mut cursor);
826 history.push(Box::new(cmd2));
827
828 assert!(history.is_modified()); // Modified again
829 }
830
831 #[test]
832 fn test_save_point_invalidated_after_undo_then_diverging_edit() {
833 // Regression test: save -> undo -> push a new (different) command
834 // must never be reported as "not modified", even if the undo stack
835 // happens to return to the same length as the save point.
836 let mut buffer = TextBuffer::new("hello");
837 let mut cursor = (0, 5);
838 let history = CommandHistory::new(10);
839
840 // Type 'A' and mark the document as saved (undo depth 1).
841 let mut cmd_a = InsertCharCommand::new(0, 5, 'A', cursor);
842 cmd_a.execute(&mut buffer, &mut cursor);
843 history.push(Box::new(cmd_a));
844 history.mark_saved();
845 assert!(!history.is_modified());
846
847 // Undo it (undo depth 0), then type a *different* character 'B'.
848 history.undo(&mut buffer, &mut cursor);
849 assert!(history.is_modified());
850 let mut cmd_b = InsertCharCommand::new(0, 5, 'B', cursor);
851 cmd_b.execute(&mut buffer, &mut cursor);
852 history.push(Box::new(cmd_b));
853
854 // The undo depth (1) matches the save point again, but the buffer
855 // content ("helloB") differs from what was actually saved
856 // ("helloA"): the document must still be reported as modified.
857 assert_eq!(buffer.line(0), "helloB");
858 assert!(history.is_modified());
859 }
860
861 #[test]
862 fn test_save_point_invalidated_after_undo_then_group_diverges() {
863 // Same regression as above, but through `begin_group`/`end_group`
864 // (composite commands), which has its own save-point handling.
865 let mut buffer = TextBuffer::new("hello");
866 let mut cursor = (0, 5);
867 let history = CommandHistory::new(10);
868
869 history.begin_group();
870 let mut cmd_a = InsertCharCommand::new(0, 5, 'A', cursor);
871 cmd_a.execute(&mut buffer, &mut cursor);
872 history.push(Box::new(cmd_a));
873 history.end_group();
874 history.mark_saved();
875 assert!(!history.is_modified());
876
877 history.undo(&mut buffer, &mut cursor);
878 assert!(history.is_modified());
879
880 history.begin_group();
881 let mut cmd_b = InsertCharCommand::new(0, 5, 'B', cursor);
882 cmd_b.execute(&mut buffer, &mut cursor);
883 history.push(Box::new(cmd_b));
884 history.end_group();
885
886 assert_eq!(buffer.line(0), "helloB");
887 assert!(history.is_modified());
888 }
889
890 #[test]
891 fn test_clear() {
892 let mut buffer = TextBuffer::new("hello");
893 let mut cursor = (0, 5);
894 let history = CommandHistory::new(10);
895
896 let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
897 cmd.execute(&mut buffer, &mut cursor);
898 history.push(Box::new(cmd));
899
900 assert!(history.can_undo());
901 history.clear();
902 assert!(!history.can_undo());
903 assert!(!history.is_modified());
904 }
905
906 #[test]
907 fn test_size_limit() {
908 let mut buffer = TextBuffer::new("a");
909 let mut cursor = (0, 1);
910 let history = CommandHistory::new(3);
911
912 // Add 5 commands (exceeds limit of 3)
913 for i in 0..5 {
914 let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
915 cmd.execute(&mut buffer, &mut cursor);
916 cursor.1 += 1;
917 history.push(Box::new(cmd));
918 }
919
920 // Should only have 3 in history
921 assert_eq!(history.undo_count(), 3);
922 }
923
924 #[test]
925 fn test_grouping() {
926 let mut buffer = TextBuffer::new("hello");
927 let mut cursor = (0, 5);
928 let history = CommandHistory::new(10);
929
930 history.begin_group();
931
932 // Add multiple characters
933 for ch in "!!!".chars() {
934 let mut cmd = InsertCharCommand::new(0, cursor.1, ch, cursor);
935 cmd.execute(&mut buffer, &mut cursor);
936 // Don't manually increment cursor - execute() does it
937 history.push(Box::new(cmd));
938 }
939
940 history.end_group();
941
942 assert_eq!(buffer.line(0), "hello!!!");
943 assert_eq!(history.undo_count(), 1); // All grouped into one
944
945 // Single undo should remove all three characters
946 history.undo(&mut buffer, &mut cursor);
947 assert_eq!(buffer.line(0), "hello");
948 assert_eq!(cursor, (0, 5));
949 }
950
951 #[test]
952 fn test_enforce_size_limit_adjusts_save_point() {
953 let mut buffer = TextBuffer::new("a");
954 let mut cursor = (0, 1);
955 let history = CommandHistory::new(3);
956
957 // Fill to the limit and mark this state as saved.
958 for i in 0..3 {
959 let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
960 cmd.execute(&mut buffer, &mut cursor);
961 cursor.1 += 1;
962 history.push(Box::new(cmd));
963 }
964 history.mark_saved();
965 assert!(!history.is_modified());
966
967 // Pushing one more command exceeds max_size (3), trimming the
968 // oldest command and shifting the save point down by one to stay
969 // aligned with the commands that remain.
970 let mut cmd = InsertCharCommand::new(0, cursor.1, 'x', cursor);
971 cmd.execute(&mut buffer, &mut cursor);
972 history.push(Box::new(cmd));
973 assert_eq!(history.undo_count(), 3);
974 assert!(history.is_modified()); // the just-pushed command is unsaved
975
976 // Undoing the new command should land exactly back on the saved
977 // state, proving the save point still points at the correct
978 // (shifted) index after trimming.
979 history.undo(&mut buffer, &mut cursor);
980 assert!(!history.is_modified());
981 }
982
983 #[test]
984 fn test_enforce_size_limit_clears_save_point_when_trimmed_away() {
985 let mut buffer = TextBuffer::new("a");
986 let mut cursor = (0, 1);
987 let history = CommandHistory::new(3);
988
989 // Mark saved at the very first command (save_point = 1), then push
990 // enough commands that the first one gets trimmed away entirely.
991 let mut cmd = InsertCharCommand::new(0, 1, 'x', cursor);
992 cmd.execute(&mut buffer, &mut cursor);
993 cursor.1 += 1;
994 history.push(Box::new(cmd));
995 history.mark_saved();
996
997 for i in 0..3 {
998 let mut cmd = InsertCharCommand::new(0, cursor.1 + i, 'x', cursor);
999 cmd.execute(&mut buffer, &mut cursor);
1000 cursor.1 += 1;
1001 history.push(Box::new(cmd));
1002 }
1003
1004 // The saved command has been trimmed out of the undo stack, so the
1005 // save point can never be reached again and must report modified.
1006 assert!(history.is_modified());
1007 }
1008
1009 #[test]
1010 fn test_set_max_size_trims_multiple_entries_in_one_call() {
1011 let mut buffer = TextBuffer::new("a");
1012 let mut cursor = (0, 1);
1013 let history = CommandHistory::new(10);
1014
1015 for i in 0..5 {
1016 let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
1017 cmd.execute(&mut buffer, &mut cursor);
1018 cursor.1 += 1;
1019 history.push(Box::new(cmd));
1020 }
1021 assert_eq!(history.undo_count(), 5);
1022
1023 // Shrinking by more than one below the current length must trim
1024 // more than one command in a single `set_max_size` call.
1025 history.set_max_size(2);
1026 assert_eq!(history.undo_count(), 2);
1027 }
1028
1029 #[test]
1030 fn test_push_clears_redo() {
1031 let mut buffer = TextBuffer::new("hello");
1032 let mut cursor = (0, 5);
1033 let history = CommandHistory::new(10);
1034
1035 let mut cmd1 = InsertCharCommand::new(0, 5, '!', cursor);
1036 cmd1.execute(&mut buffer, &mut cursor);
1037 history.push(Box::new(cmd1));
1038
1039 history.undo(&mut buffer, &mut cursor);
1040 assert!(history.can_redo());
1041
1042 // Push new command should clear redo stack
1043 let mut cmd2 = InsertCharCommand::new(0, 5, '?', cursor);
1044 cmd2.execute(&mut buffer, &mut cursor);
1045 history.push(Box::new(cmd2));
1046
1047 assert!(!history.can_redo());
1048 }
1049
1050 /// A caller-supplied command whose `undo` panics, standing in for a buggy
1051 /// [`Command`] implementation in a downstream crate.
1052 ///
1053 /// The panic is raised by an out-of-bounds index rather than `panic!`,
1054 /// which is denied workspace-wide.
1055 #[derive(Debug)]
1056 struct PanickingUndoCommand;
1057
1058 impl Command for PanickingUndoCommand {
1059 fn execute(&mut self, _buffer: &mut TextBuffer, _cursor: &mut (usize, usize)) {}
1060
1061 fn undo(&mut self, _buffer: &mut TextBuffer, _cursor: &mut (usize, usize)) {
1062 let empty: Vec<u8> = Vec::new();
1063 let _ = empty[0];
1064 }
1065 }
1066
1067 /// A panic inside a caller's `Command` poisons the history mutex on this
1068 /// very thread, because `undo` runs the command while holding the guard.
1069 /// Every later call must still work: `can_undo` is on the render path, so
1070 /// panicking again there would take the whole editor down permanently.
1071 ///
1072 /// Compiled only under `panic = "unwind"`; the release profile sets
1073 /// `panic = "abort"`, where the panic below cannot be caught at all.
1074 #[test]
1075 #[cfg(panic = "unwind")]
1076 fn test_history_survives_a_panicking_command() {
1077 let mut buffer = TextBuffer::new("hello");
1078 let mut cursor = (0, 5);
1079 let history = CommandHistory::new(10);
1080 history.push(Box::new(PanickingUndoCommand));
1081 assert_eq!(history.undo_count(), 1);
1082
1083 // Swallow the panic message so the test output stays readable, then
1084 // restore the default hook for the rest of the suite.
1085 let previous_hook = std::panic::take_hook();
1086 std::panic::set_hook(Box::new(|_| {}));
1087 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1088 history.undo(&mut buffer, &mut cursor)
1089 }));
1090 std::panic::set_hook(previous_hook);
1091 assert!(outcome.is_err(), "the command under test must panic");
1092
1093 // The mutex is now poisoned. Every read must still answer rather than
1094 // panic, and the state is the one the unwind left behind: `undo` had
1095 // already popped the command off the undo stack, and never reached the
1096 // push onto the redo stack.
1097 assert!(!history.can_undo());
1098 assert!(!history.can_redo());
1099 assert_eq!(history.undo_count(), 0);
1100 assert_eq!(history.redo_count(), 0);
1101 assert!(!history.is_modified());
1102
1103 // The history must also remain usable, not merely readable.
1104 history.clear();
1105
1106 let mut command = InsertCharCommand::new(0, 5, '!', cursor);
1107 command.execute(&mut buffer, &mut cursor);
1108 history.push(Box::new(command));
1109 assert!(history.undo(&mut buffer, &mut cursor));
1110 assert_eq!(buffer.to_string(), "hello");
1111 }
1112}