Sub topic 6
Why a new action clears the redo stack
This chapter assumes you know what a stack is, can read basic Python classes, and can slice strings. It builds on the two-stack model from earlier chapters: an undo stack holds actions that can be reversed, and a redo stack holds actions that were reversed and can be applied again.
The rule
When the user performs a new action, the history manager must empty the redo stack. In the History class, this happens in do():
def do(self, command):
command.apply()
self._undo.append(command)
self._redo.clear()The last line is the rule. Without it, redo can bring back actions that no longer fit the document.
What goes wrong without it
Redo entries are only valid for the exact document state they were undone from. A command like Insert(doc, 5, " world") stores a position. That position makes sense only if the text before it is the same as it was originally.
Suppose the document says Hello world. The user undoes the second insert, so the text is Hello. Then the user types ! at position 5. The text is now Hello!. If the old " world" insert were still on the redo stack, redo would put it at position 5. The result would be Hello world!, which is a state the user never had. In other cases the stored position could fall outside the text, or the command could revert the wrong characters later.
The history is a straight line of states. Undo steps back along the line. Redo steps forward along the same line. A new action starts a different path, and the old forward steps no longer connect to it.
Tracing the stacks
This table follows the two stacks through the example. The top of each stack is the rightmost item.
| Step | Action | Undo stack | Redo stack | Text |
|---|---|---|---|---|
| 1 | do Insert "Hello" | Hello | (empty) | Hello |
| 2 | do Insert " world" | Hello, world | (empty) | Hello world |
| 3 | undo | Hello | world | Hello |
| 4 | do Insert "!" | Hello, ! | (empty) | Hello! |
| 5 | redo | Hello, ! | (empty) | Hello! |
At step 4 the redo stack goes from holding world to being empty. At step 5, redo() finds nothing to do and returns False. The document is unchanged.
Running it
This code uses the History class from the earlier chapter, plus the Document and Insert classes. It is complete enough to run as shown.
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 Document:
def __init__(self):
self.text = ""
class Insert:
def __init__(self, doc, position, string):
self.doc = doc
self.position = position
self.string = string
def apply(self):
t = self.doc.text
self.doc.text = t[:self.position] + self.string + t[self.position:]
def revert(self):
t = self.doc.text
end = self.position + len(self.string)
self.doc.text = t[:self.position] + t[end:]
doc = Document()
history = History()
history.do(Insert(doc, 0, "Hello"))
history.do(Insert(doc, 5, " world"))
history.undo()
print(doc.text) # Hello
history.do(Insert(doc, 5, "!"))
print(doc.text) # Hello!
print(history.redo()) # False
print(doc.text) # Hello!Common errors
- Forgetting
clear(). The program appears to work in simple tests that never mix undo with new edits. The bug shows up only when a user undoes, edits, and then redoes. - Clearing in
undo()orredo(). Those two operations must keep the other stack intact, because they move one command between stacks. Only a new action clears redo. - Clearing before the action succeeds. If
command.apply()can raise an exception, clear the redo stack after it succeeds. Thedo()method above does this, sinceapply()runs first and an exception skips the rest. - Treating a failed redo as an error. An empty redo stack is normal, so
redo()returnsFalseinstead of raising.
Exercise
Exercise
A user types "A", then "B", then "C" as three separate Insert commands. They press undo twice, then type "X" as a new Insert. How many commands are on the undo stack and on the redo stack afterwards, and what happens when they press redo?
Show answer
The undo stack holds two commands (the insert of "A" and the insert of "X"). The redo stack holds none, because do() cleared it, which discarded the undone inserts of "B" and "C". Pressing redo returns False and the text does not change.
Exercise
Why must the redo stack be cleared in do() but not in undo()?
Show answer
undo() moves a command onto the redo stack, so clearing there would destroy the command it just moved and make redo impossible. A new action in do() creates a different history. The stored redo commands no longer match the document, so they must be discarded.