Skip to main content

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(
281        &self,
282        buffer: &mut TextBuffer,
283        cursor: &mut (usize, usize),
284    ) -> bool {
285        let mut inner = self.lock_inner();
286
287        // End any current grouping
288        if inner.current_group.is_some() {
289            Self::end_group_internal(&mut inner);
290        }
291
292        if let Some(mut command) = inner.undo_stack.pop_back() {
293            command.undo(buffer, cursor);
294            inner.redo_stack.push(command);
295            true
296        } else {
297            false
298        }
299    }
300
301    /// Redoes the last undone command.
302    ///
303    /// `TextBuffer` is internal to this crate, so an application drives this
304    /// through [`Message::Redo`] rather than calling it directly.
305    ///
306    /// # Arguments
307    ///
308    /// * `buffer` - The text buffer to modify
309    /// * `cursor` - The cursor position to update
310    ///
311    /// # Returns
312    ///
313    /// `true` if a command was redone, `false` if nothing to redo
314    ///
315    /// # Example
316    ///
317    /// ```
318    /// use iced_code_editor::{CodeEditor, Message};
319    ///
320    /// let mut editor = CodeEditor::new("hello", "rs");
321    /// let _ = editor.update(&Message::Paste(" world".to_string()));
322    /// let _ = editor.update(&Message::Undo);
323    /// assert_eq!(editor.content(), "hello");
324    ///
325    /// let _ = editor.update(&Message::Redo);
326    /// assert_eq!(editor.content(), " worldhello");
327    /// ```
328    ///
329    /// [`Message::Redo`]: crate::Message::Redo
330    pub fn redo(
331        &self,
332        buffer: &mut TextBuffer,
333        cursor: &mut (usize, usize),
334    ) -> bool {
335        let mut inner = self.lock_inner();
336
337        if let Some(mut command) = inner.redo_stack.pop() {
338            command.execute(buffer, cursor);
339            inner.undo_stack.push_back(command);
340            true
341        } else {
342            false
343        }
344    }
345
346    /// Returns whether there are commands that can be undone.
347    ///
348    /// An open group counts as undoable even before it is closed, so an
349    /// "Undo" menu item stays enabled while the user is mid-word.
350    ///
351    /// # Returns
352    ///
353    /// `true` if undo would do something, `false` otherwise
354    ///
355    /// # Example
356    ///
357    /// ```
358    /// use iced_code_editor::CommandHistory;
359    ///
360    /// let history = CommandHistory::new(100);
361    /// assert!(!history.can_undo());
362    /// ```
363    #[must_use]
364    pub fn can_undo(&self) -> bool {
365        let inner = self.lock_inner();
366        !inner.undo_stack.is_empty() || inner.current_group.is_some()
367    }
368
369    /// Returns whether there are commands that can be redone.
370    ///
371    /// # Returns
372    ///
373    /// `true` if redo would do something, `false` otherwise
374    ///
375    /// # Example
376    ///
377    /// ```
378    /// use iced_code_editor::{CodeEditor, Message};
379    ///
380    /// let mut editor = CodeEditor::new("hello", "rs");
381    /// assert!(!editor.can_redo());
382    ///
383    /// // Redo only becomes available after an undo.
384    /// let _ = editor.update(&Message::Paste("!".to_string()));
385    /// assert!(!editor.can_redo());
386    /// let _ = editor.update(&Message::Undo);
387    /// assert!(editor.can_redo());
388    /// ```
389    #[must_use]
390    pub fn can_redo(&self) -> bool {
391        let inner = self.lock_inner();
392        !inner.redo_stack.is_empty()
393    }
394
395    /// Marks the current position as the save point.
396    ///
397    /// This is used to track whether the document has been modified since
398    /// the last save. Call this after successfully saving the file.
399    ///
400    /// # Example
401    ///
402    /// ```
403    /// use iced_code_editor::{CodeEditor, Message};
404    ///
405    /// let mut editor = CodeEditor::new("hello", "rs");
406    /// let _ = editor.update(&Message::Paste("!".to_string()));
407    /// assert!(editor.is_modified());
408    ///
409    /// // After the host has written the file to disk.
410    /// editor.mark_saved();
411    /// assert!(!editor.is_modified());
412    ///
413    /// // Undoing back past the save point marks the document dirty again.
414    /// let _ = editor.update(&Message::Undo);
415    /// assert!(editor.is_modified());
416    /// ```
417    pub fn mark_saved(&self) {
418        let mut inner = self.lock_inner();
419        inner.save_point = Some(inner.undo_stack.len());
420    }
421
422    /// Returns whether the document has been modified since the last save.
423    ///
424    /// Compares the current undo depth against the depth recorded by
425    /// [`Self::mark_saved`], so undoing back to the saved state reports "not
426    /// modified" again rather than staying permanently dirty.
427    ///
428    /// # Returns
429    ///
430    /// `true` if there are unsaved changes, `false` otherwise
431    ///
432    /// # Example
433    ///
434    /// ```
435    /// use iced_code_editor::CommandHistory;
436    ///
437    /// let history = CommandHistory::new(100);
438    /// // A fresh history has nothing to save.
439    /// assert!(!history.is_modified());
440    /// ```
441    #[must_use]
442    pub fn is_modified(&self) -> bool {
443        let inner = self.lock_inner();
444
445        // If we're currently in a group, we're modified
446        if inner.current_group.is_some() {
447            return true;
448        }
449
450        match inner.save_point {
451            None => !inner.undo_stack.is_empty(),
452            Some(sp) => sp != inner.undo_stack.len(),
453        }
454    }
455
456    /// Clears all history.
457    ///
458    /// This removes all undo/redo commands and resets the save point.
459    /// Useful when starting a new document or resetting the editor state.
460    ///
461    /// # Example
462    ///
463    /// ```
464    /// use iced_code_editor::CommandHistory;
465    ///
466    /// let history = CommandHistory::new(100);
467    /// // ... perform some operations ...
468    ///
469    /// // Clear everything when opening a new document
470    /// history.clear();
471    /// assert_eq!(history.undo_count(), 0);
472    /// assert_eq!(history.redo_count(), 0);
473    /// assert!(!history.is_modified());
474    /// ```
475    pub fn clear(&self) {
476        let mut inner = self.lock_inner();
477        inner.undo_stack.clear();
478        inner.redo_stack.clear();
479        inner.save_point = None;
480        inner.current_group = None;
481    }
482
483    /// Begins grouping subsequent commands into a composite.
484    ///
485    /// All commands added via `push()` will be grouped together until
486    /// `end_group()` is called. This is useful for grouping consecutive
487    /// typing operations, so one undo removes a whole word rather than one
488    /// character at a time.
489    ///
490    /// Calling this while a group is already open does nothing, so grouping
491    /// does not nest.
492    ///
493    /// # Example
494    ///
495    /// ```
496    /// use iced_code_editor::CommandHistory;
497    ///
498    /// let history = CommandHistory::new(100);
499    ///
500    /// history.begin_group();
501    /// // An open group counts as undoable, so an "Undo" menu item stays
502    /// // enabled while the user is still typing.
503    /// assert!(history.can_undo());
504    ///
505    /// // Nothing was actually pushed, so closing it adds no entry.
506    /// history.end_group();
507    /// assert_eq!(history.undo_count(), 0);
508    /// ```
509    pub fn begin_group(&self) {
510        let mut inner = self.lock_inner();
511        if inner.current_group.is_none() {
512            inner.current_group = Some(CompositeCommand::new());
513        }
514    }
515
516    /// Ends the current command grouping.
517    ///
518    /// The grouped commands are added to the history as a single composite
519    /// command, so one undo reverses all of them. If no commands were grouped,
520    /// nothing is added — an empty group leaves no trace.
521    ///
522    /// Safe to call when no group is open.
523    ///
524    /// # Example
525    ///
526    /// ```
527    /// use iced_code_editor::CommandHistory;
528    ///
529    /// let history = CommandHistory::new(100);
530    ///
531    /// history.begin_group();
532    /// history.end_group();
533    /// // An empty group adds nothing to the undo stack.
534    /// assert_eq!(history.undo_count(), 0);
535    /// assert!(!history.can_undo());
536    ///
537    /// // Closing when nothing is open is harmless.
538    /// history.end_group();
539    /// ```
540    pub fn end_group(&self) {
541        let mut inner = self.lock_inner();
542        Self::end_group_internal(&mut inner);
543    }
544
545    /// Internal helper to end grouping (used when lock is already held).
546    fn end_group_internal(inner: &mut HistoryInner) {
547        if let Some(group) = inner.current_group.take()
548            && !group.is_empty()
549        {
550            // See the matching comment in `push`: a save point ahead of the
551            // current position can never be reached again once the redo
552            // stack backing it is cleared here.
553            if inner.save_point.is_some_and(|sp| sp > inner.undo_stack.len()) {
554                inner.save_point = None;
555            }
556
557            // Clear redo stack
558            inner.redo_stack.clear();
559
560            // Add composite to undo stack
561            inner.undo_stack.push_back(Box::new(group));
562
563            inner.enforce_size_limit();
564        }
565    }
566
567    /// Returns the maximum history size.
568    ///
569    /// # Returns
570    ///
571    /// The maximum number of commands that can be stored in history.
572    ///
573    /// # Example
574    ///
575    /// ```
576    /// use iced_code_editor::CommandHistory;
577    ///
578    /// let history = CommandHistory::new(100);
579    /// assert_eq!(history.max_size(), 100);
580    /// ```
581    #[must_use]
582    pub fn max_size(&self) -> usize {
583        let inner = self.lock_inner();
584        inner.max_size
585    }
586
587    /// Sets the maximum history size.
588    ///
589    /// If the current history exceeds the new size, older commands are removed.
590    /// This is useful for adjusting memory usage based on system resources.
591    ///
592    /// # Arguments
593    ///
594    /// * `max_size` - New maximum size (number of commands to keep)
595    ///
596    /// # Example
597    ///
598    /// ```
599    /// use iced_code_editor::CommandHistory;
600    ///
601    /// let history = CommandHistory::new(100);
602    ///
603    /// // Increase limit for memory-rich environments
604    /// history.set_max_size(500);
605    /// assert_eq!(history.max_size(), 500);
606    ///
607    /// // Decrease limit for constrained environments
608    /// history.set_max_size(50);
609    /// assert_eq!(history.max_size(), 50);
610    /// ```
611    pub fn set_max_size(&self, max_size: usize) {
612        let mut inner = self.lock_inner();
613        inner.max_size = max_size;
614        inner.enforce_size_limit();
615    }
616
617    /// Returns the current number of undo operations available.
618    ///
619    /// This can be useful for displaying history statistics or managing
620    /// UI state (e.g., enabling/disabling undo buttons).
621    ///
622    /// # Returns
623    ///
624    /// The number of commands that can be undone.
625    ///
626    /// # Example
627    ///
628    /// ```
629    /// use iced_code_editor::CommandHistory;
630    ///
631    /// let history = CommandHistory::new(100);
632    /// assert_eq!(history.undo_count(), 0);
633    ///
634    /// // After adding commands...
635    /// // assert!(history.undo_count() > 0);
636    /// ```
637    #[must_use]
638    pub fn undo_count(&self) -> usize {
639        let inner = self.lock_inner();
640        inner.undo_stack.len()
641    }
642
643    /// Returns the current number of redo operations available.
644    ///
645    /// This can be useful for displaying history statistics or managing
646    /// UI state (e.g., enabling/disabling redo buttons).
647    ///
648    /// # Returns
649    ///
650    /// The number of commands that can be redone.
651    ///
652    /// # Example
653    ///
654    /// ```
655    /// use iced_code_editor::CommandHistory;
656    ///
657    /// let history = CommandHistory::new(100);
658    /// assert_eq!(history.redo_count(), 0);
659    ///
660    /// // After undoing some commands...
661    /// // assert!(history.redo_count() > 0);
662    /// ```
663    #[must_use]
664    pub fn redo_count(&self) -> usize {
665        let inner = self.lock_inner();
666        inner.redo_stack.len()
667    }
668}
669
670// Implement Default for convenient usage
671impl Default for CommandHistory {
672    fn default() -> Self {
673        Self::new(100)
674    }
675}
676
677impl CodeEditor {
678    /// Returns whether the editor has unsaved changes.
679    ///
680    /// Use this to drive a "modified" indicator in a tab title, or to prompt
681    /// before closing.
682    ///
683    /// # Returns
684    ///
685    /// `true` if there are unsaved modifications, `false` otherwise
686    ///
687    /// # Example
688    ///
689    /// ```
690    /// use iced_code_editor::{CodeEditor, Message};
691    ///
692    /// let mut editor = CodeEditor::new("hello", "rs");
693    /// assert!(!editor.is_modified());
694    ///
695    /// let _ = editor.update(&Message::Paste("!".to_string()));
696    /// assert!(editor.is_modified());
697    /// ```
698    pub fn is_modified(&self) -> bool {
699        self.history.is_modified()
700    }
701
702    /// Marks the current state as saved.
703    ///
704    /// Call this after successfully saving the file to reset the modified state.
705    ///
706    /// # Example
707    ///
708    /// ```
709    /// use iced_code_editor::{CodeEditor, Message};
710    ///
711    /// let mut editor = CodeEditor::new("hello", "rs");
712    /// let _ = editor.update(&Message::Paste("!".to_string()));
713    ///
714    /// editor.mark_saved();
715    /// assert!(!editor.is_modified());
716    /// ```
717    pub fn mark_saved(&mut self) {
718        self.history.mark_saved();
719    }
720
721    /// Returns whether undo is available.
722    ///
723    /// # Returns
724    ///
725    /// `true` if undo would do something, `false` otherwise
726    ///
727    /// # Example
728    ///
729    /// ```
730    /// use iced_code_editor::{CodeEditor, Message};
731    ///
732    /// let mut editor = CodeEditor::new("hello", "rs");
733    /// assert!(!editor.can_undo());
734    ///
735    /// let _ = editor.update(&Message::Paste("!".to_string()));
736    /// assert!(editor.can_undo());
737    /// ```
738    pub fn can_undo(&self) -> bool {
739        self.history.can_undo()
740    }
741
742    /// Returns whether redo is available.
743    ///
744    /// # Returns
745    ///
746    /// `true` if redo would do something, `false` otherwise
747    ///
748    /// # Example
749    ///
750    /// ```
751    /// use iced_code_editor::{CodeEditor, Message};
752    ///
753    /// let mut editor = CodeEditor::new("hello", "rs");
754    /// let _ = editor.update(&Message::Paste("!".to_string()));
755    /// assert!(!editor.can_redo());
756    ///
757    /// let _ = editor.update(&Message::Undo);
758    /// assert!(editor.can_redo());
759    /// ```
760    pub fn can_redo(&self) -> bool {
761        self.history.can_redo()
762    }
763}
764
765#[cfg(test)]
766mod tests {
767    use super::*;
768    use crate::canvas_editor::editing::command::InsertCharCommand;
769
770    #[test]
771    fn test_new_history() {
772        let history = CommandHistory::new(50);
773        assert_eq!(history.max_size(), 50);
774        assert!(!history.can_undo());
775        assert!(!history.can_redo());
776    }
777
778    #[test]
779    fn test_push_and_undo() {
780        let mut buffer = TextBuffer::new("hello");
781        let mut cursor = (0, 5);
782        let history = CommandHistory::new(10);
783
784        let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
785        cmd.execute(&mut buffer, &mut cursor);
786        history.push(Box::new(cmd));
787
788        assert!(history.can_undo());
789        assert_eq!(buffer.line(0), "hello!");
790
791        history.undo(&mut buffer, &mut cursor);
792        assert_eq!(buffer.line(0), "hello");
793        assert_eq!(cursor, (0, 5));
794    }
795
796    #[test]
797    fn test_redo() {
798        let mut buffer = TextBuffer::new("hello");
799        let mut cursor = (0, 5);
800        let history = CommandHistory::new(10);
801
802        let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
803        cmd.execute(&mut buffer, &mut cursor);
804        history.push(Box::new(cmd));
805
806        history.undo(&mut buffer, &mut cursor);
807        assert_eq!(buffer.line(0), "hello");
808
809        assert!(history.can_redo());
810        history.redo(&mut buffer, &mut cursor);
811        assert_eq!(buffer.line(0), "hello!");
812        assert_eq!(cursor, (0, 6));
813    }
814
815    #[test]
816    fn test_save_point() {
817        let mut buffer = TextBuffer::new("hello");
818        let mut cursor = (0, 5);
819        let history = CommandHistory::new(10);
820
821        assert!(!history.is_modified()); // New document is not modified
822
823        let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
824        cmd.execute(&mut buffer, &mut cursor);
825        history.push(Box::new(cmd));
826
827        assert!(history.is_modified()); // Now modified
828
829        history.mark_saved();
830        assert!(!history.is_modified()); // Saved
831
832        let mut cmd2 = InsertCharCommand::new(0, 6, '?', cursor);
833        cmd2.execute(&mut buffer, &mut cursor);
834        history.push(Box::new(cmd2));
835
836        assert!(history.is_modified()); // Modified again
837    }
838
839    #[test]
840    fn test_save_point_invalidated_after_undo_then_diverging_edit() {
841        // Regression test: save -> undo -> push a new (different) command
842        // must never be reported as "not modified", even if the undo stack
843        // happens to return to the same length as the save point.
844        let mut buffer = TextBuffer::new("hello");
845        let mut cursor = (0, 5);
846        let history = CommandHistory::new(10);
847
848        // Type 'A' and mark the document as saved (undo depth 1).
849        let mut cmd_a = InsertCharCommand::new(0, 5, 'A', cursor);
850        cmd_a.execute(&mut buffer, &mut cursor);
851        history.push(Box::new(cmd_a));
852        history.mark_saved();
853        assert!(!history.is_modified());
854
855        // Undo it (undo depth 0), then type a *different* character 'B'.
856        history.undo(&mut buffer, &mut cursor);
857        assert!(history.is_modified());
858        let mut cmd_b = InsertCharCommand::new(0, 5, 'B', cursor);
859        cmd_b.execute(&mut buffer, &mut cursor);
860        history.push(Box::new(cmd_b));
861
862        // The undo depth (1) matches the save point again, but the buffer
863        // content ("helloB") differs from what was actually saved
864        // ("helloA"): the document must still be reported as modified.
865        assert_eq!(buffer.line(0), "helloB");
866        assert!(history.is_modified());
867    }
868
869    #[test]
870    fn test_save_point_invalidated_after_undo_then_group_diverges() {
871        // Same regression as above, but through `begin_group`/`end_group`
872        // (composite commands), which has its own save-point handling.
873        let mut buffer = TextBuffer::new("hello");
874        let mut cursor = (0, 5);
875        let history = CommandHistory::new(10);
876
877        history.begin_group();
878        let mut cmd_a = InsertCharCommand::new(0, 5, 'A', cursor);
879        cmd_a.execute(&mut buffer, &mut cursor);
880        history.push(Box::new(cmd_a));
881        history.end_group();
882        history.mark_saved();
883        assert!(!history.is_modified());
884
885        history.undo(&mut buffer, &mut cursor);
886        assert!(history.is_modified());
887
888        history.begin_group();
889        let mut cmd_b = InsertCharCommand::new(0, 5, 'B', cursor);
890        cmd_b.execute(&mut buffer, &mut cursor);
891        history.push(Box::new(cmd_b));
892        history.end_group();
893
894        assert_eq!(buffer.line(0), "helloB");
895        assert!(history.is_modified());
896    }
897
898    #[test]
899    fn test_clear() {
900        let mut buffer = TextBuffer::new("hello");
901        let mut cursor = (0, 5);
902        let history = CommandHistory::new(10);
903
904        let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
905        cmd.execute(&mut buffer, &mut cursor);
906        history.push(Box::new(cmd));
907
908        assert!(history.can_undo());
909        history.clear();
910        assert!(!history.can_undo());
911        assert!(!history.is_modified());
912    }
913
914    #[test]
915    fn test_size_limit() {
916        let mut buffer = TextBuffer::new("a");
917        let mut cursor = (0, 1);
918        let history = CommandHistory::new(3);
919
920        // Add 5 commands (exceeds limit of 3)
921        for i in 0..5 {
922            let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
923            cmd.execute(&mut buffer, &mut cursor);
924            cursor.1 += 1;
925            history.push(Box::new(cmd));
926        }
927
928        // Should only have 3 in history
929        assert_eq!(history.undo_count(), 3);
930    }
931
932    #[test]
933    fn test_grouping() {
934        let mut buffer = TextBuffer::new("hello");
935        let mut cursor = (0, 5);
936        let history = CommandHistory::new(10);
937
938        history.begin_group();
939
940        // Add multiple characters
941        for ch in "!!!".chars() {
942            let mut cmd = InsertCharCommand::new(0, cursor.1, ch, cursor);
943            cmd.execute(&mut buffer, &mut cursor);
944            // Don't manually increment cursor - execute() does it
945            history.push(Box::new(cmd));
946        }
947
948        history.end_group();
949
950        assert_eq!(buffer.line(0), "hello!!!");
951        assert_eq!(history.undo_count(), 1); // All grouped into one
952
953        // Single undo should remove all three characters
954        history.undo(&mut buffer, &mut cursor);
955        assert_eq!(buffer.line(0), "hello");
956        assert_eq!(cursor, (0, 5));
957    }
958
959    #[test]
960    fn test_enforce_size_limit_adjusts_save_point() {
961        let mut buffer = TextBuffer::new("a");
962        let mut cursor = (0, 1);
963        let history = CommandHistory::new(3);
964
965        // Fill to the limit and mark this state as saved.
966        for i in 0..3 {
967            let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
968            cmd.execute(&mut buffer, &mut cursor);
969            cursor.1 += 1;
970            history.push(Box::new(cmd));
971        }
972        history.mark_saved();
973        assert!(!history.is_modified());
974
975        // Pushing one more command exceeds max_size (3), trimming the
976        // oldest command and shifting the save point down by one to stay
977        // aligned with the commands that remain.
978        let mut cmd = InsertCharCommand::new(0, cursor.1, 'x', cursor);
979        cmd.execute(&mut buffer, &mut cursor);
980        history.push(Box::new(cmd));
981        assert_eq!(history.undo_count(), 3);
982        assert!(history.is_modified()); // the just-pushed command is unsaved
983
984        // Undoing the new command should land exactly back on the saved
985        // state, proving the save point still points at the correct
986        // (shifted) index after trimming.
987        history.undo(&mut buffer, &mut cursor);
988        assert!(!history.is_modified());
989    }
990
991    #[test]
992    fn test_enforce_size_limit_clears_save_point_when_trimmed_away() {
993        let mut buffer = TextBuffer::new("a");
994        let mut cursor = (0, 1);
995        let history = CommandHistory::new(3);
996
997        // Mark saved at the very first command (save_point = 1), then push
998        // enough commands that the first one gets trimmed away entirely.
999        let mut cmd = InsertCharCommand::new(0, 1, 'x', cursor);
1000        cmd.execute(&mut buffer, &mut cursor);
1001        cursor.1 += 1;
1002        history.push(Box::new(cmd));
1003        history.mark_saved();
1004
1005        for i in 0..3 {
1006            let mut cmd = InsertCharCommand::new(0, cursor.1 + i, 'x', cursor);
1007            cmd.execute(&mut buffer, &mut cursor);
1008            cursor.1 += 1;
1009            history.push(Box::new(cmd));
1010        }
1011
1012        // The saved command has been trimmed out of the undo stack, so the
1013        // save point can never be reached again and must report modified.
1014        assert!(history.is_modified());
1015    }
1016
1017    #[test]
1018    fn test_set_max_size_trims_multiple_entries_in_one_call() {
1019        let mut buffer = TextBuffer::new("a");
1020        let mut cursor = (0, 1);
1021        let history = CommandHistory::new(10);
1022
1023        for i in 0..5 {
1024            let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
1025            cmd.execute(&mut buffer, &mut cursor);
1026            cursor.1 += 1;
1027            history.push(Box::new(cmd));
1028        }
1029        assert_eq!(history.undo_count(), 5);
1030
1031        // Shrinking by more than one below the current length must trim
1032        // more than one command in a single `set_max_size` call.
1033        history.set_max_size(2);
1034        assert_eq!(history.undo_count(), 2);
1035    }
1036
1037    #[test]
1038    fn test_push_clears_redo() {
1039        let mut buffer = TextBuffer::new("hello");
1040        let mut cursor = (0, 5);
1041        let history = CommandHistory::new(10);
1042
1043        let mut cmd1 = InsertCharCommand::new(0, 5, '!', cursor);
1044        cmd1.execute(&mut buffer, &mut cursor);
1045        history.push(Box::new(cmd1));
1046
1047        history.undo(&mut buffer, &mut cursor);
1048        assert!(history.can_redo());
1049
1050        // Push new command should clear redo stack
1051        let mut cmd2 = InsertCharCommand::new(0, 5, '?', cursor);
1052        cmd2.execute(&mut buffer, &mut cursor);
1053        history.push(Box::new(cmd2));
1054
1055        assert!(!history.can_redo());
1056    }
1057
1058    /// A caller-supplied command whose `undo` panics, standing in for a buggy
1059    /// [`Command`] implementation in a downstream crate.
1060    ///
1061    /// The panic is raised by an out-of-bounds index rather than `panic!`,
1062    /// which is denied workspace-wide.
1063    #[derive(Debug)]
1064    struct PanickingUndoCommand;
1065
1066    impl Command for PanickingUndoCommand {
1067        fn execute(
1068            &mut self,
1069            _buffer: &mut TextBuffer,
1070            _cursor: &mut (usize, usize),
1071        ) {
1072        }
1073
1074        fn undo(
1075            &mut self,
1076            _buffer: &mut TextBuffer,
1077            _cursor: &mut (usize, usize),
1078        ) {
1079            let empty: Vec<u8> = Vec::new();
1080            let _ = empty[0];
1081        }
1082    }
1083
1084    /// A panic inside a caller's `Command` poisons the history mutex on this
1085    /// very thread, because `undo` runs the command while holding the guard.
1086    /// Every later call must still work: `can_undo` is on the render path, so
1087    /// panicking again there would take the whole editor down permanently.
1088    ///
1089    /// Compiled only under `panic = "unwind"`; the release profile sets
1090    /// `panic = "abort"`, where the panic below cannot be caught at all.
1091    #[test]
1092    #[cfg(panic = "unwind")]
1093    fn test_history_survives_a_panicking_command() {
1094        let mut buffer = TextBuffer::new("hello");
1095        let mut cursor = (0, 5);
1096        let history = CommandHistory::new(10);
1097        history.push(Box::new(PanickingUndoCommand));
1098        assert_eq!(history.undo_count(), 1);
1099
1100        // Swallow the panic message so the test output stays readable, then
1101        // restore the default hook for the rest of the suite.
1102        let previous_hook = std::panic::take_hook();
1103        std::panic::set_hook(Box::new(|_| {}));
1104        let outcome =
1105            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1106                history.undo(&mut buffer, &mut cursor)
1107            }));
1108        std::panic::set_hook(previous_hook);
1109        assert!(outcome.is_err(), "the command under test must panic");
1110
1111        // The mutex is now poisoned. Every read must still answer rather than
1112        // panic, and the state is the one the unwind left behind: `undo` had
1113        // already popped the command off the undo stack, and never reached the
1114        // push onto the redo stack.
1115        assert!(!history.can_undo());
1116        assert!(!history.can_redo());
1117        assert_eq!(history.undo_count(), 0);
1118        assert_eq!(history.redo_count(), 0);
1119        assert!(!history.is_modified());
1120
1121        // The history must also remain usable, not merely readable.
1122        history.clear();
1123
1124        let mut command = InsertCharCommand::new(0, 5, '!', cursor);
1125        command.execute(&mut buffer, &mut cursor);
1126        history.push(Box::new(command));
1127        assert!(history.undo(&mut buffer, &mut cursor));
1128        assert_eq!(buffer.to_string(), "hello");
1129    }
1130}