Sub topic 4
Undoing an action
This chapter covers what undo() does inside a two-stack history manager. It assumes you know Python classes, the push and pop operations of a stack, and basic list handling. Earlier chapters introduced the two stacks and the idea that each action can apply and revert itself. Here the focus is the undo step itself.
What undo has to do
Undo takes the most recent action that is still in effect and reverses it. It must also remember that action, so that redo can bring it back. That gives undo three jobs:
- Remove the newest command from the undo stack.
- Call that command's
revert()method. - Push the same command onto the redo stack.
The newest command is the one on top of the undo stack. Because a stack is last-in, first-out, popping gives you the most recent action first. That is the order a user expects: the last thing done is the first thing undone.
The undo method
Here is the History class from the plan. This chapter concentrates on undo().
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 TrueRead undo() line by line:
if not self._undo: return Falseis the guard for an empty stack. Nothing happens, and the caller learns that nothing happened.self._undo.pop()removes and returns the last item of the list, which is the top of the stack.command.revert()changes the document back to the state before the command ran.self._redo.append(command)keeps the command so it can be reapplied later.return Truetells the caller that an undo took place.
Following one undo step
Take a history with two commands applied: Insert "Hello" and then Insert " world". The stacks look like this before and after one call to undo().
After the call, the undo stack holds only Insert "Hello", and the redo stack holds Insert " world". The command object was not copied or rebuilt. The same object moved from one list to the other.
A runnable example
This example uses an Insert command. Its revert() removes exactly the characters that apply() added, because it remembers the position and the string.
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:]
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
doc = Document()
history = History()
history.do(Insert(doc, 0, "Hello"))
history.do(Insert(doc, 5, " world"))
print(repr(doc.text)) # 'Hello world'
print(history.undo()) # True
print(repr(doc.text)) # 'Hello'
print(history.undo()) # True
print(repr(doc.text)) # ''
print(history.undo()) # False
print(repr(doc.text)) # ''The third call returns False and leaves the text unchanged. Undoing past the start of the history is a normal case, not an error, so the method reports it with a return value instead of raising an exception.
Common errors
- Forgetting to push onto the redo stack. The document reverts correctly, but redo has nothing to restore. The bug only shows when someone tries to redo.
- Reverting before popping. If you call
self._undo[-1].revert()and the revert raises an exception, the stacks and the document can disagree. Popping first and then reverting is simple, but it has the same weakness: ifrevert()raises, the command is lost from both stacks. If your commands can fail, catch the error and push the command back onto the undo stack. - A
revert()that is not the exact inverse ofapply(). Undo relies on the document being in the state the command left it in. Ifrevert()uses a position that has since changed, it removes the wrong text. Undo order guarantees this does not happen as long as each command restores exactly what it changed. - Ignoring the return value. The user interface should use the
TrueorFalseresult to enable or disable an Undo button, or to skip refreshing the screen when nothing changed.
Check your understanding
Exercise
A history contains three applied commands, A, B and C, in that order. You call undo() twice. Which commands are on each stack afterward, and in what order would redo() restore them?
Show answer
The undo stack holds only A. The redo stack holds C and B, with B on top, because C was undone first and B was undone second. The first redo() reapplies B, and the second reapplies C, which restores the original order A, B, C.
Exercise
Why does undo() return False instead of raising an exception when the undo stack is empty?
Show answer
Having nothing to undo is a normal situation, such as when the user presses Undo at the start of a session. Returning False lets the caller handle it, for example by disabling a button, without needing a try/except block.