Sub topic 11
Undo and Redo with Two Stacks
This chapter assumes you can write a Python class, know the push, pop and peek operations from the earlier chapters, and understand O(1) versus O(n) cost.
The idea
An editor needs to reverse its latest action first, then the one before it. That is last in, first out, so a stack fits. Redo needs a second stack. When you undo an action, it moves from the undo stack to the redo stack. When you redo, it moves back.
The two stacks hold the history on either side of the present moment.
A working implementation
This example edits a text buffer. Each action is stored as the text it appended. That is enough to reverse it.
class Editor:
def __init__(self):
self.text = ""
self._undo = []
self._redo = []
def type(self, chunk):
self.text += chunk
self._undo.append(chunk)
self._redo.clear() # a new action ends the old redo branch
def undo(self):
if not self._undo:
return False
chunk = self._undo.pop()
self.text = self.text[: len(self.text) - len(chunk)]
self._redo.append(chunk)
return True
def redo(self):
if not self._redo:
return False
chunk = self._redo.pop()
self.text += chunk
self._undo.append(chunk)
return True
ed = Editor()
ed.type("Hello")
ed.type(", world")
ed.undo()
print(ed.text) # Hello
ed.redo()
print(ed.text) # Hello, world
ed.undo()
ed.type("!")
print(ed.text) # Hello!
print(ed.redo()) # FalseThe last two lines show the rule that surprises people most. After you undo and then type something new, redo is no longer possible.
Why a new action clears the redo stack
Suppose the history is "Hello", ", world", and you undo ", world". The redo stack holds ", world". If you now type "!", the document is "Hello!". Redoing ", world" would apply an action to a state it was never recorded against. Clearing the redo stack keeps the history a single straight line.
The clear() call costs O(n) in the number of redo entries in the worst case. Each entry was pushed once, so the cost averages out to O(1) per action.
Design choices
| Choice | Effect |
|---|---|
| Store the inverse of each action (a command) | Small memory use, but every action type needs its own undo logic |
| Store full snapshots of the state | Simple to write, but memory grows with document size times history length |
| Cap the undo stack at N entries | Bounded memory, but the oldest actions can no longer be undone |
Real editors usually store commands. Each command object has do() and undo() methods, and the two stacks hold command objects instead of strings.
Common errors
- Forgetting to clear the redo stack on a new action. Redo then replays stale history and corrupts the state.
- Pushing to the redo stack during a redo's own replay. Redo should move the item back to the undo stack only once.
- Popping from an empty stack. Check for emptiness, as
undoandredodo here, or the call raisesIndexError. - Storing references to mutable objects as snapshots. Later edits change the saved snapshot too. Copy the state, or store commands.
Exercise
A user types "A", "B", "C", then undoes twice, then types "D". What do the undo stack and redo stack contain, and can the user redo "B"?
Show answer
After the three typed actions the undo stack is [A, B, C]. Two undos move C then B to the redo stack, leaving undo [A] and redo [C, B]. Typing "D" pushes D onto undo, giving [A, D], and clears the redo stack to []. The user cannot redo "B", because the new action discarded the redo history.
Exercise
Why is storing the undone action on a redo stack better than recomputing it from the current text?
Show answer
The action's data was already captured when it was first done, so redo only moves it between stacks in O(1) time. Recomputing it would need extra logic and might not reproduce the same result.