Sub topic 3
The two stacks: undo and redo
This chapter assumes you know what a stack is (push, pop, last in, first out). It also assumes you can read Python classes. Earlier chapters showed why a stack suits undo and how an action can reverse itself. This chapter combines those ideas into one history model.
Why one stack is not enough
A single stack of actions supports undo. You pop the newest action and revert it. But once you pop it, the action is gone, so you cannot redo it.
Redo needs somewhere to keep actions that were undone. The simplest answer is a second stack. The history is split by one question: is this action currently applied or not?
- The undo stack holds actions that are applied to the current state. The top is the most recent one.
- The redo stack holds actions that were undone and could be applied again. The top is the one that was undone most recently.
Together the two stacks describe a timeline with a "now" marker between them. Everything in the undo stack is in the past. Everything in the redo stack is in the future.
How actions move
Three operations move actions around. Each one touches the stacks in a fixed way.
do(command)applies the command, pushes it on the undo stack, and clears the redo stack.undo()pops the top of the undo stack, reverts it, and pushes it on the redo stack.redo()pops the top of the redo stack, applies it, and pushes it on the undo stack.
The later chapters cover undo, redo, and the clearing rule in detail. Here the point is the shape of the model: an action is always in exactly one stack, and it only moves between them.
The History class
This is the whole model in code. A command is any object with apply() and revert() methods. The Counter and Add classes below exist only so you can run the example.
class History:
def __init__(self):
self._undo = []
self._redo = []
def do(self, command):
command.apply()
self._undo.append(command)
self._redo.clear()
def undo(self):
if not self._undo:
return False
command = self._undo.pop()
command.revert()
self._redo.append(command)
return True
def redo(self):
if not self._redo:
return False
command = self._redo.pop()
command.apply()
self._undo.append(command)
return True
class Counter:
def __init__(self):
self.value = 0
class Add:
def __init__(self, counter, amount):
self.counter = counter
self.amount = amount
def apply(self):
self.counter.value += self.amount
def revert(self):
self.counter.value -= self.amount
counter = Counter()
history = History()
history.do(Add(counter, 5))
history.do(Add(counter, 3))
print(counter.value, len(history._undo), len(history._redo)) # 8 2 0
history.undo()
print(counter.value, len(history._undo), len(history._redo)) # 5 1 1
history.redo()
print(counter.value, len(history._undo), len(history._redo)) # 8 2 0The demo reads the private lists only to show the sizes. Code outside the class should not touch them.
Properties of the model
Three facts hold after every operation. They are also the facts you check when you debug a history manager.
- The current state equals the initial state with every command in the undo stack applied, in order from bottom to top.
- The commands in the redo stack are not applied. Their order is reversed, so the next one to redo sits on top.
- The total number of commands in both stacks changes only through
do()(adds one, and discards the whole redo stack) and through any size limit you add later.
Each operation moves one command and does constant work for the stack itself. The cost of apply() and revert() is whatever the command costs.
Common mistakes
- Forgetting to clear the redo stack in
do(). The old future then stays attached to a changed present, and a later redo applies a command to a state it was never written for. - Pushing before applying. If
apply()raises an error, the command is already in the history even though it never took effect. Applying first keeps the stack honest. - Reverting out of order. Commands must be reverted newest first. A stack gives you that order, and a plain list that you pop from the front does not.
Exercise
A history has the commands A, B and C in its undo stack (C on top) and nothing in the redo stack. You call undo() twice, then do(D). Which commands are in each stack afterwards, and what happened to B and C?
Show answer
The undo stack holds A and D (D on top). The redo stack is empty. The two undo() calls moved C and then B to the redo stack. Calling do(D) cleared the redo stack, so B and C are discarded and can no longer be redone.