Sub topic 11
Treating several edits as one undo step
This chapter assumes you have read the earlier chapters on the two-stack history. You should know the History class with do, undo and redo, and the idea that a command has apply() and revert() methods. You should also be comfortable with Python classes and string slicing.
The problem: one action, many commands
Many user actions change a document in several small ways. Replacing a word is a delete followed by an insert. Find-and-replace may touch dozens of places. If each small change is its own entry on the undo stack, one press of Ctrl+Z undoes only half of the replacement. The user sees a document that never existed before.
The fix is to make the history record one entry per user action, not one entry per low-level change. The history manager stays the same. You wrap the small commands in a command that contains them.
The composite command
A composite command is a command that holds a list of other commands. It has the same apply() and revert() interface, so History cannot tell it apart from a single Insert.
Two rules make it correct:
apply()runs the children in order.revert()runs the children in reverse order.
The reverse order matters because each child assumed the document looked a certain way after the previous child ran. To undo, you must peel the changes off from the newest to the oldest, the same last-in, first-out order the stacks use.
The code below is self-contained. It repeats History from earlier so you can run it as is. It adds a Delete command, which remembers the text it removed so it can put it back, and a Composite command.
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:]
class Delete:
def __init__(self, doc, position, length):
self.doc = doc
self.position = position
self.length = length
self.removed = ""
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:]
class Composite:
def __init__(self, commands):
self.commands = list(commands)
def apply(self):
done = []
try:
for command in self.commands:
command.apply()
done.append(command)
except Exception:
for command in reversed(done):
command.revert()
raise
def revert(self):
for command in reversed(self.commands):
command.revert()
doc = Document()
history = History()
history.do(Insert(doc, 0, "Hello world"))
history.do(Composite([Delete(doc, 6, 5), Insert(doc, 6, "there")]))
print(doc.text) # Hello there
history.undo()
print(doc.text) # Hello world
history.redo()
print(doc.text) # Hello there
history.undo()
history.undo()
print(repr(doc.text)) # ''
print(history.undo()) # FalseThe replacement is stored as one entry. A single undo() brings back "world", and a single redo() brings back "there".
How the group is undone
Reverting in forward order would give a wrong result here. Reverting the Delete first would put "world" back at position 6. Reverting the Insert would then remove five characters from position 6, and those characters would be "world", not "there". The text would end up as "Hello there" minus the wrong word.
Failure in the middle of a group
If the third child of a group fails, the first two have already changed the document. The try block in Composite.apply() handles this. It reverts the children that finished, in reverse order, and then re-raises the error.
Because History.do() calls apply() before touching either stack, a failed group is never pushed. The document and both stacks are left as they were. This all-or-nothing behavior is why grouping is safer than pushing the small commands one at a time.
Building groups in practice
Passing a ready-made list works when the code knows the whole action up front. Editors often build groups differently. They collect commands while the user types, then close the group after a pause or on a keystroke such as Enter. You can add that by keeping a list of pending commands in a small helper. When the group closes, wrap the list in a Composite and pass it to history.do().
Keep these points in mind:
- Do not create a
Compositewith no children. It would add an undo step that does nothing visible. - A group of one command can be pushed as that command directly.
- Positions inside a group are relative to the document as it stands after the earlier children ran, not the original document.
Exercise
A group contains Insert A, then Insert B, then Delete C. In what order are the children reverted when the user presses undo, and why not in the order they were applied?
Show answer
They are reverted as Delete C, then Insert B, then Insert A. Each child assumed the document state left by the one before it, so the newest change must be removed first. Reverting in forward order would act on text that is no longer where the command expects it.