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
53// Allow unwrap on Mutex since this is safe in the single-threaded GUI context
54// The mutex is only used for interior mutability, not actual multi-threading
55#![allow(clippy::unwrap_used)]
56// The Mutex cannot be poisoned in our single-threaded context, so panics documented
57// below would never actually occur in practice
58#![allow(clippy::missing_panics_doc)]
59
60use super::command::{Command, CompositeCommand};
61use crate::buffer::TextBuffer;
62use crate::canvas_editor::CodeEditor;
63use std::collections::VecDeque;
64use std::sync::{Arc, Mutex};
65
66/// Manages command history for undo/redo operations.
67///
68/// The history maintains two stacks:
69/// - Undo stack: Commands that can be undone
70/// - Redo stack: Commands that can be redone (cleared when new commands are added)
71///
72/// Thread-safe using Arc<Mutex<>> for interior mutability.
73#[derive(Debug, Clone)]
74pub struct CommandHistory {
75    inner: Arc<Mutex<HistoryInner>>,
76}
77
78#[derive(Debug)]
79struct HistoryInner {
80    /// Stack of commands that can be undone
81    undo_stack: VecDeque<Box<dyn Command>>,
82    /// Stack of commands that can be redone
83    redo_stack: Vec<Box<dyn Command>>,
84    /// Maximum number of commands to keep in history
85    max_size: usize,
86    /// Index in undo_stack where document was last saved (None if never saved)
87    save_point: Option<usize>,
88    /// Current composite command being built (for grouping)
89    current_group: Option<CompositeCommand>,
90}
91
92impl HistoryInner {
93    /// Trims `undo_stack` down to `max_size`, discarding the oldest commands
94    /// first and shifting `save_point` to stay aligned with what remains.
95    ///
96    /// If a discarded command was the one marked as the save point, the save
97    /// point is cleared instead, since that saved state is no longer
98    /// reachable via undo.
99    fn enforce_size_limit(&mut self) {
100        while self.undo_stack.len() > self.max_size {
101            self.undo_stack.pop_front();
102            if let Some(ref mut sp) = self.save_point {
103                if *sp > 0 {
104                    *sp -= 1;
105                } else {
106                    self.save_point = None;
107                }
108            }
109        }
110    }
111}
112
113impl CommandHistory {
114    /// Creates a new command history with the specified size limit.
115    ///
116    /// # Arguments
117    ///
118    /// * `max_size` - Maximum number of commands to keep in history
119    ///
120    /// # Returns
121    ///
122    /// A new `CommandHistory` instance
123    ///
124    /// # Example
125    ///
126    /// ```
127    /// use iced_code_editor::CommandHistory;
128    ///
129    /// let history = CommandHistory::new(100);
130    /// ```
131    pub fn new(max_size: usize) -> Self {
132        Self {
133            inner: Arc::new(Mutex::new(HistoryInner {
134                undo_stack: VecDeque::with_capacity(max_size.min(100)),
135                redo_stack: Vec::with_capacity(max_size.min(100)),
136                max_size,
137                save_point: None,
138                current_group: None,
139            })),
140        }
141    }
142
143    /// Adds a command to the history.
144    ///
145    /// This clears the redo stack and adds the command to the undo stack.
146    /// If currently grouping commands, adds to the current group instead.
147    ///
148    /// # Arguments
149    ///
150    /// * `command` - The command to add
151    pub fn push(&self, command: Box<dyn Command>) {
152        let mut inner = self.inner.lock().unwrap();
153
154        // If we're building a composite, add to it
155        if let Some(ref mut group) = inner.current_group {
156            group.add(command);
157            return;
158        }
159
160        // The save point may sit ahead of the current position (the user
161        // undid past it). Pushing a new command here clears the redo stack,
162        // permanently discarding the path back to that saved state, so the
163        // save point can never be reached again and must be invalidated.
164        // Otherwise, if the new undo stack happens to reach the same length
165        // later, `is_modified()` would wrongly report "not modified" even
166        // though the actual command sequence has diverged.
167        if inner.save_point.is_some_and(|sp| sp > inner.undo_stack.len()) {
168            inner.save_point = None;
169        }
170
171        // Clear redo stack when new command is added
172        inner.redo_stack.clear();
173
174        // Add to undo stack
175        inner.undo_stack.push_back(command);
176
177        inner.enforce_size_limit();
178    }
179
180    /// Undoes the last command.
181    ///
182    /// # Arguments
183    ///
184    /// * `buffer` - The text buffer to modify
185    /// * `cursor` - The cursor position to update
186    ///
187    /// # Returns
188    ///
189    /// `true` if a command was undone, `false` if nothing to undo
190    pub fn undo(
191        &self,
192        buffer: &mut TextBuffer,
193        cursor: &mut (usize, usize),
194    ) -> bool {
195        let mut inner = self.inner.lock().unwrap();
196
197        // End any current grouping
198        if inner.current_group.is_some() {
199            Self::end_group_internal(&mut inner);
200        }
201
202        if let Some(mut command) = inner.undo_stack.pop_back() {
203            command.undo(buffer, cursor);
204            inner.redo_stack.push(command);
205            true
206        } else {
207            false
208        }
209    }
210
211    /// Redoes the last undone command.
212    ///
213    /// # Arguments
214    ///
215    /// * `buffer` - The text buffer to modify
216    /// * `cursor` - The cursor position to update
217    ///
218    /// # Returns
219    ///
220    /// `true` if a command was redone, `false` if nothing to redo
221    pub fn redo(
222        &self,
223        buffer: &mut TextBuffer,
224        cursor: &mut (usize, usize),
225    ) -> bool {
226        let mut inner = self.inner.lock().unwrap();
227
228        if let Some(mut command) = inner.redo_stack.pop() {
229            command.execute(buffer, cursor);
230            inner.undo_stack.push_back(command);
231            true
232        } else {
233            false
234        }
235    }
236
237    /// Returns whether there are commands that can be undone.
238    #[must_use]
239    pub fn can_undo(&self) -> bool {
240        let inner = self.inner.lock().unwrap();
241        !inner.undo_stack.is_empty() || inner.current_group.is_some()
242    }
243
244    /// Returns whether there are commands that can be redone.
245    #[must_use]
246    pub fn can_redo(&self) -> bool {
247        let inner = self.inner.lock().unwrap();
248        !inner.redo_stack.is_empty()
249    }
250
251    /// Marks the current position as the save point.
252    ///
253    /// This is used to track whether the document has been modified since
254    /// the last save. Call this after successfully saving the file.
255    pub fn mark_saved(&self) {
256        let mut inner = self.inner.lock().unwrap();
257        inner.save_point = Some(inner.undo_stack.len());
258    }
259
260    /// Returns whether the document has been modified since the last save.
261    ///
262    /// # Returns
263    ///
264    /// `true` if there are unsaved changes, `false` otherwise
265    #[must_use]
266    pub fn is_modified(&self) -> bool {
267        let inner = self.inner.lock().unwrap();
268
269        // If we're currently in a group, we're modified
270        if inner.current_group.is_some() {
271            return true;
272        }
273
274        match inner.save_point {
275            None => !inner.undo_stack.is_empty(),
276            Some(sp) => sp != inner.undo_stack.len(),
277        }
278    }
279
280    /// Clears all history.
281    ///
282    /// This removes all undo/redo commands and resets the save point.
283    /// Useful when starting a new document or resetting the editor state.
284    ///
285    /// # Example
286    ///
287    /// ```
288    /// use iced_code_editor::CommandHistory;
289    ///
290    /// let history = CommandHistory::new(100);
291    /// // ... perform some operations ...
292    ///
293    /// // Clear everything when opening a new document
294    /// history.clear();
295    /// assert_eq!(history.undo_count(), 0);
296    /// assert_eq!(history.redo_count(), 0);
297    /// assert!(!history.is_modified());
298    /// ```
299    pub fn clear(&self) {
300        let mut inner = self.inner.lock().unwrap();
301        inner.undo_stack.clear();
302        inner.redo_stack.clear();
303        inner.save_point = None;
304        inner.current_group = None;
305    }
306
307    /// Begins grouping subsequent commands into a composite.
308    ///
309    /// All commands added via `push()` will be grouped together until
310    /// `end_group()` is called. This is useful for grouping consecutive
311    /// typing operations.
312    pub fn begin_group(&self) {
313        let mut inner = self.inner.lock().unwrap();
314        if inner.current_group.is_none() {
315            inner.current_group = Some(CompositeCommand::new());
316        }
317    }
318
319    /// Ends the current command grouping.
320    ///
321    /// The grouped commands are added to the history as a single composite
322    /// command. If no commands were grouped, nothing is added.
323    pub fn end_group(&self) {
324        let mut inner = self.inner.lock().unwrap();
325        Self::end_group_internal(&mut inner);
326    }
327
328    /// Internal helper to end grouping (used when lock is already held).
329    fn end_group_internal(inner: &mut HistoryInner) {
330        if let Some(group) = inner.current_group.take()
331            && !group.is_empty()
332        {
333            // See the matching comment in `push`: a save point ahead of the
334            // current position can never be reached again once the redo
335            // stack backing it is cleared here.
336            if inner.save_point.is_some_and(|sp| sp > inner.undo_stack.len()) {
337                inner.save_point = None;
338            }
339
340            // Clear redo stack
341            inner.redo_stack.clear();
342
343            // Add composite to undo stack
344            inner.undo_stack.push_back(Box::new(group));
345
346            inner.enforce_size_limit();
347        }
348    }
349
350    /// Returns the maximum history size.
351    ///
352    /// # Returns
353    ///
354    /// The maximum number of commands that can be stored in history.
355    ///
356    /// # Example
357    ///
358    /// ```
359    /// use iced_code_editor::CommandHistory;
360    ///
361    /// let history = CommandHistory::new(100);
362    /// assert_eq!(history.max_size(), 100);
363    /// ```
364    #[must_use]
365    pub fn max_size(&self) -> usize {
366        let inner = self.inner.lock().unwrap();
367        inner.max_size
368    }
369
370    /// Sets the maximum history size.
371    ///
372    /// If the current history exceeds the new size, older commands are removed.
373    /// This is useful for adjusting memory usage based on system resources.
374    ///
375    /// # Arguments
376    ///
377    /// * `max_size` - New maximum size (number of commands to keep)
378    ///
379    /// # Example
380    ///
381    /// ```
382    /// use iced_code_editor::CommandHistory;
383    ///
384    /// let history = CommandHistory::new(100);
385    ///
386    /// // Increase limit for memory-rich environments
387    /// history.set_max_size(500);
388    /// assert_eq!(history.max_size(), 500);
389    ///
390    /// // Decrease limit for constrained environments
391    /// history.set_max_size(50);
392    /// assert_eq!(history.max_size(), 50);
393    /// ```
394    pub fn set_max_size(&self, max_size: usize) {
395        let mut inner = self.inner.lock().unwrap();
396        inner.max_size = max_size;
397        inner.enforce_size_limit();
398    }
399
400    /// Returns the current number of undo operations available.
401    ///
402    /// This can be useful for displaying history statistics or managing
403    /// UI state (e.g., enabling/disabling undo buttons).
404    ///
405    /// # Returns
406    ///
407    /// The number of commands that can be undone.
408    ///
409    /// # Example
410    ///
411    /// ```
412    /// use iced_code_editor::CommandHistory;
413    ///
414    /// let history = CommandHistory::new(100);
415    /// assert_eq!(history.undo_count(), 0);
416    ///
417    /// // After adding commands...
418    /// // assert!(history.undo_count() > 0);
419    /// ```
420    #[must_use]
421    pub fn undo_count(&self) -> usize {
422        let inner = self.inner.lock().unwrap();
423        inner.undo_stack.len()
424    }
425
426    /// Returns the current number of redo operations available.
427    ///
428    /// This can be useful for displaying history statistics or managing
429    /// UI state (e.g., enabling/disabling redo buttons).
430    ///
431    /// # Returns
432    ///
433    /// The number of commands that can be redone.
434    ///
435    /// # Example
436    ///
437    /// ```
438    /// use iced_code_editor::CommandHistory;
439    ///
440    /// let history = CommandHistory::new(100);
441    /// assert_eq!(history.redo_count(), 0);
442    ///
443    /// // After undoing some commands...
444    /// // assert!(history.redo_count() > 0);
445    /// ```
446    #[must_use]
447    pub fn redo_count(&self) -> usize {
448        let inner = self.inner.lock().unwrap();
449        inner.redo_stack.len()
450    }
451}
452
453// Implement Default for convenient usage
454impl Default for CommandHistory {
455    fn default() -> Self {
456        Self::new(100)
457    }
458}
459
460impl CodeEditor {
461    /// Returns whether the editor has unsaved changes.
462    ///
463    /// # Returns
464    ///
465    /// `true` if there are unsaved modifications, `false` otherwise
466    pub fn is_modified(&self) -> bool {
467        self.history.is_modified()
468    }
469
470    /// Marks the current state as saved.
471    ///
472    /// Call this after successfully saving the file to reset the modified state.
473    pub fn mark_saved(&mut self) {
474        self.history.mark_saved();
475    }
476
477    /// Returns whether undo is available.
478    pub fn can_undo(&self) -> bool {
479        self.history.can_undo()
480    }
481
482    /// Returns whether redo is available.
483    pub fn can_redo(&self) -> bool {
484        self.history.can_redo()
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491    use crate::canvas_editor::editing::command::InsertCharCommand;
492
493    #[test]
494    fn test_new_history() {
495        let history = CommandHistory::new(50);
496        assert_eq!(history.max_size(), 50);
497        assert!(!history.can_undo());
498        assert!(!history.can_redo());
499    }
500
501    #[test]
502    fn test_push_and_undo() {
503        let mut buffer = TextBuffer::new("hello");
504        let mut cursor = (0, 5);
505        let history = CommandHistory::new(10);
506
507        let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
508        cmd.execute(&mut buffer, &mut cursor);
509        history.push(Box::new(cmd));
510
511        assert!(history.can_undo());
512        assert_eq!(buffer.line(0), "hello!");
513
514        history.undo(&mut buffer, &mut cursor);
515        assert_eq!(buffer.line(0), "hello");
516        assert_eq!(cursor, (0, 5));
517    }
518
519    #[test]
520    fn test_redo() {
521        let mut buffer = TextBuffer::new("hello");
522        let mut cursor = (0, 5);
523        let history = CommandHistory::new(10);
524
525        let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
526        cmd.execute(&mut buffer, &mut cursor);
527        history.push(Box::new(cmd));
528
529        history.undo(&mut buffer, &mut cursor);
530        assert_eq!(buffer.line(0), "hello");
531
532        assert!(history.can_redo());
533        history.redo(&mut buffer, &mut cursor);
534        assert_eq!(buffer.line(0), "hello!");
535        assert_eq!(cursor, (0, 6));
536    }
537
538    #[test]
539    fn test_save_point() {
540        let mut buffer = TextBuffer::new("hello");
541        let mut cursor = (0, 5);
542        let history = CommandHistory::new(10);
543
544        assert!(!history.is_modified()); // New document is not modified
545
546        let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
547        cmd.execute(&mut buffer, &mut cursor);
548        history.push(Box::new(cmd));
549
550        assert!(history.is_modified()); // Now modified
551
552        history.mark_saved();
553        assert!(!history.is_modified()); // Saved
554
555        let mut cmd2 = InsertCharCommand::new(0, 6, '?', cursor);
556        cmd2.execute(&mut buffer, &mut cursor);
557        history.push(Box::new(cmd2));
558
559        assert!(history.is_modified()); // Modified again
560    }
561
562    #[test]
563    fn test_save_point_invalidated_after_undo_then_diverging_edit() {
564        // Regression test: save -> undo -> push a new (different) command
565        // must never be reported as "not modified", even if the undo stack
566        // happens to return to the same length as the save point.
567        let mut buffer = TextBuffer::new("hello");
568        let mut cursor = (0, 5);
569        let history = CommandHistory::new(10);
570
571        // Type 'A' and mark the document as saved (undo depth 1).
572        let mut cmd_a = InsertCharCommand::new(0, 5, 'A', cursor);
573        cmd_a.execute(&mut buffer, &mut cursor);
574        history.push(Box::new(cmd_a));
575        history.mark_saved();
576        assert!(!history.is_modified());
577
578        // Undo it (undo depth 0), then type a *different* character 'B'.
579        history.undo(&mut buffer, &mut cursor);
580        assert!(history.is_modified());
581        let mut cmd_b = InsertCharCommand::new(0, 5, 'B', cursor);
582        cmd_b.execute(&mut buffer, &mut cursor);
583        history.push(Box::new(cmd_b));
584
585        // The undo depth (1) matches the save point again, but the buffer
586        // content ("helloB") differs from what was actually saved
587        // ("helloA"): the document must still be reported as modified.
588        assert_eq!(buffer.line(0), "helloB");
589        assert!(history.is_modified());
590    }
591
592    #[test]
593    fn test_save_point_invalidated_after_undo_then_group_diverges() {
594        // Same regression as above, but through `begin_group`/`end_group`
595        // (composite commands), which has its own save-point handling.
596        let mut buffer = TextBuffer::new("hello");
597        let mut cursor = (0, 5);
598        let history = CommandHistory::new(10);
599
600        history.begin_group();
601        let mut cmd_a = InsertCharCommand::new(0, 5, 'A', cursor);
602        cmd_a.execute(&mut buffer, &mut cursor);
603        history.push(Box::new(cmd_a));
604        history.end_group();
605        history.mark_saved();
606        assert!(!history.is_modified());
607
608        history.undo(&mut buffer, &mut cursor);
609        assert!(history.is_modified());
610
611        history.begin_group();
612        let mut cmd_b = InsertCharCommand::new(0, 5, 'B', cursor);
613        cmd_b.execute(&mut buffer, &mut cursor);
614        history.push(Box::new(cmd_b));
615        history.end_group();
616
617        assert_eq!(buffer.line(0), "helloB");
618        assert!(history.is_modified());
619    }
620
621    #[test]
622    fn test_clear() {
623        let mut buffer = TextBuffer::new("hello");
624        let mut cursor = (0, 5);
625        let history = CommandHistory::new(10);
626
627        let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
628        cmd.execute(&mut buffer, &mut cursor);
629        history.push(Box::new(cmd));
630
631        assert!(history.can_undo());
632        history.clear();
633        assert!(!history.can_undo());
634        assert!(!history.is_modified());
635    }
636
637    #[test]
638    fn test_size_limit() {
639        let mut buffer = TextBuffer::new("a");
640        let mut cursor = (0, 1);
641        let history = CommandHistory::new(3);
642
643        // Add 5 commands (exceeds limit of 3)
644        for i in 0..5 {
645            let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
646            cmd.execute(&mut buffer, &mut cursor);
647            cursor.1 += 1;
648            history.push(Box::new(cmd));
649        }
650
651        // Should only have 3 in history
652        assert_eq!(history.undo_count(), 3);
653    }
654
655    #[test]
656    fn test_grouping() {
657        let mut buffer = TextBuffer::new("hello");
658        let mut cursor = (0, 5);
659        let history = CommandHistory::new(10);
660
661        history.begin_group();
662
663        // Add multiple characters
664        for ch in "!!!".chars() {
665            let mut cmd = InsertCharCommand::new(0, cursor.1, ch, cursor);
666            cmd.execute(&mut buffer, &mut cursor);
667            // Don't manually increment cursor - execute() does it
668            history.push(Box::new(cmd));
669        }
670
671        history.end_group();
672
673        assert_eq!(buffer.line(0), "hello!!!");
674        assert_eq!(history.undo_count(), 1); // All grouped into one
675
676        // Single undo should remove all three characters
677        history.undo(&mut buffer, &mut cursor);
678        assert_eq!(buffer.line(0), "hello");
679        assert_eq!(cursor, (0, 5));
680    }
681
682    #[test]
683    fn test_enforce_size_limit_adjusts_save_point() {
684        let mut buffer = TextBuffer::new("a");
685        let mut cursor = (0, 1);
686        let history = CommandHistory::new(3);
687
688        // Fill to the limit and mark this state as saved.
689        for i in 0..3 {
690            let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
691            cmd.execute(&mut buffer, &mut cursor);
692            cursor.1 += 1;
693            history.push(Box::new(cmd));
694        }
695        history.mark_saved();
696        assert!(!history.is_modified());
697
698        // Pushing one more command exceeds max_size (3), trimming the
699        // oldest command and shifting the save point down by one to stay
700        // aligned with the commands that remain.
701        let mut cmd = InsertCharCommand::new(0, cursor.1, 'x', cursor);
702        cmd.execute(&mut buffer, &mut cursor);
703        history.push(Box::new(cmd));
704        assert_eq!(history.undo_count(), 3);
705        assert!(history.is_modified()); // the just-pushed command is unsaved
706
707        // Undoing the new command should land exactly back on the saved
708        // state, proving the save point still points at the correct
709        // (shifted) index after trimming.
710        history.undo(&mut buffer, &mut cursor);
711        assert!(!history.is_modified());
712    }
713
714    #[test]
715    fn test_enforce_size_limit_clears_save_point_when_trimmed_away() {
716        let mut buffer = TextBuffer::new("a");
717        let mut cursor = (0, 1);
718        let history = CommandHistory::new(3);
719
720        // Mark saved at the very first command (save_point = 1), then push
721        // enough commands that the first one gets trimmed away entirely.
722        let mut cmd = InsertCharCommand::new(0, 1, 'x', cursor);
723        cmd.execute(&mut buffer, &mut cursor);
724        cursor.1 += 1;
725        history.push(Box::new(cmd));
726        history.mark_saved();
727
728        for i in 0..3 {
729            let mut cmd = InsertCharCommand::new(0, cursor.1 + i, 'x', cursor);
730            cmd.execute(&mut buffer, &mut cursor);
731            cursor.1 += 1;
732            history.push(Box::new(cmd));
733        }
734
735        // The saved command has been trimmed out of the undo stack, so the
736        // save point can never be reached again and must report modified.
737        assert!(history.is_modified());
738    }
739
740    #[test]
741    fn test_set_max_size_trims_multiple_entries_in_one_call() {
742        let mut buffer = TextBuffer::new("a");
743        let mut cursor = (0, 1);
744        let history = CommandHistory::new(10);
745
746        for i in 0..5 {
747            let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
748            cmd.execute(&mut buffer, &mut cursor);
749            cursor.1 += 1;
750            history.push(Box::new(cmd));
751        }
752        assert_eq!(history.undo_count(), 5);
753
754        // Shrinking by more than one below the current length must trim
755        // more than one command in a single `set_max_size` call.
756        history.set_max_size(2);
757        assert_eq!(history.undo_count(), 2);
758    }
759
760    #[test]
761    fn test_push_clears_redo() {
762        let mut buffer = TextBuffer::new("hello");
763        let mut cursor = (0, 5);
764        let history = CommandHistory::new(10);
765
766        let mut cmd1 = InsertCharCommand::new(0, 5, '!', cursor);
767        cmd1.execute(&mut buffer, &mut cursor);
768        history.push(Box::new(cmd1));
769
770        history.undo(&mut buffer, &mut cursor);
771        assert!(history.can_redo());
772
773        // Push new command should clear redo stack
774        let mut cmd2 = InsertCharCommand::new(0, 5, '?', cursor);
775        cmd2.execute(&mut buffer, &mut cursor);
776        history.push(Box::new(cmd2));
777
778        assert!(!history.can_redo());
779    }
780}