Sub topic 2
Actions that know how to reverse themselves
This chapter assumes you can write Python classes, know how a stack works (push and pop), and can slice strings. It covers the idea that makes undo possible: every action must be able to undo itself. The history manager that stores these actions comes in the next chapters.
Why the history needs more than a record
A history manager can only move actions between stacks. It cannot work out what an action did or how to reverse it. That knowledge belongs to the action itself.
So each action is an object with two methods:
apply()performs the change.revert()restores the state from beforeapply()ran.
This is the command pattern. A command is an object that represents one action and carries everything needed to run it and reverse it. The history manager calls apply() and revert() and never looks inside.
A command stores what it needs
A command must keep enough data to go in both directions. Consider inserting text. To apply it, you need the document, the position, and the string. To revert it, you need the same three things: remove len(string) characters starting at position.
Here is a small document and an Insert command.
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()
cmd = Insert(doc, 0, "Hello")
cmd.apply()
print(doc.text) # Hello
cmd.revert()
print(repr(doc.text)) # ''The command does not read the document when it is created. It reads the document when it runs. This matters later, when commands are replayed in order.
The contract
revert() must undo exactly what apply() did, and apply() must work again after a revert(). Redo depends on that second part. Redo is just calling apply() on a command that was already reverted.
In short, for any state S:
- Run
apply(), thenrevert(). The document is back to S. - Run
apply(),revert(), thenapply()again. The result matches the firstapply().
Both hold for Insert, because the position and string never change.
Commands that need to remember old state
Insert is easy to reverse because the inserted text tells you what to remove. Deleting is harder. After you delete text, the text is gone, so revert() cannot put it back unless the command saved it first.
class Delete:
def __init__(self, doc, position, length):
self.doc = doc
self.position = position
self.length = length
self.removed = None
def apply(self):
t = self.doc.text
end = self.position + self.length
self.removed = t[self.position:end]
self.doc.text = t[:self.position] + t[end:]
def revert(self):
t = self.doc.text
self.doc.text = t[:self.position] + self.removed + t[self.position:]Delete captures the removed text inside apply(), at the moment it runs. It cannot do this in __init__, because the document may have changed between creating the command and running it. Capturing at apply time means the command always saves what was really there.
doc = Document()
Insert(doc, 0, "Hello world").apply()
cmd = Delete(doc, 5, 6)
cmd.apply()
print(doc.text) # Hello
cmd.revert()
print(doc.text) # Hello worldCommon errors
- Saving state too early. Capturing old data in
__init__can store stale values. Capture it inapply(). - Mismatched revert. If
revert()removes a different range thanapply()added, the document drifts further from the original with each undo. - Reverting out of order. A command assumes the document is in the state right after its own
apply(). If you revert an older command first, positions no longer line up. This is why the history uses a stack: the most recent action is always reverted first. - Hidden side effects. If
apply()changes something thatrevert()does not restore, such as a counter or a file on disk, undo leaves the program in a mixed state.
Exercises
Exercise
Why does Delete store the removed text in apply() instead of in _init_?
Show answer
The document can change between creating the command and running it. Reading the text in apply() guarantees the command saves exactly what it removes, so revert() can put back the correct text.
Exercise
Write a Replace command that swaps the text at a position and length for a new string, with apply() and revert(). What must it store?
Show answer
It must store the document, position, length, new string, and the old text it replaced (captured in apply()). apply() saves the old text and puts the new string in its place. revert() removes len(new string) characters at the position and inserts the old text back.