Sub topic 8
Putting it together: a small text editor
This chapter combines the pieces from earlier chapters into one working program. It assumes you can read Python classes, use lists as stacks with append and pop, and slice strings. It also assumes you know the two-stack model: an undo stack and a redo stack.
The parts
The editor has three kinds of part:
- A
Documentholds the text. - Commands such as
InsertandDeleteeach change the document. Each has anapply()method and arevert()method that undoes it exactly. - A
Historyruns commands and moves them between the two stacks.
The commands know how to change the document. The history knows nothing about text. It only calls apply() and revert(). This split lets you add a new kind of edit without touching the history code.
The full program
This script runs as shown. Delete is new in this chapter. Its apply() saves the text it removes, because revert() needs that text to put it back.
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:]
doc = Document()
history = History()
history.do(Insert(doc, 0, "Hello"))
history.do(Insert(doc, 5, " world"))
print(repr(doc.text)) # 'Hello world'
history.do(Delete(doc, 5, 6))
print(repr(doc.text)) # 'Hello'
history.undo()
print(repr(doc.text)) # 'Hello world'
history.undo()
print(repr(doc.text)) # 'Hello'
history.redo()
print(repr(doc.text)) # 'Hello world'
history.undo()
history.do(Insert(doc, 5, "!"))
print(repr(doc.text)) # 'Hello!'
print(history.redo()) # False
print(history.undo()) # True
print(repr(doc.text)) # 'Hello'Tracing the stacks
After the first three do() calls, the undo stack holds the two inserts and the delete, with the delete on top. The redo stack is empty.
The first undo() pops the delete, reverts it, and pushes it onto the redo stack. The second undo() does the same for the second insert. Now the redo stack holds the delete (bottom) and the second insert (top). The text is Hello.
redo() pops the second insert from the redo stack, applies it again, and pushes it back onto the undo stack. The text is Hello world.
The next undo() moves that insert to the redo stack again. Then do(Insert(doc, 5, "!")) runs. It clears the redo stack, which discards the old delete and insert. If it did not, a later redo() would apply the delete's recorded range to text that no longer matches it. The final redo() therefore returns False, and nothing changes.
Common errors
- Reverting in the wrong order. Each
revert()assumes the document is in the state right after its ownapply(). The stack order guarantees this. If you reorder commands, the positions stop making sense. - Forgetting to clear redo. Without
self._redo.clear()indo(), redo can apply a command to the wrong text. - Storing too little in a command. A
Deletethat does not keep the removed text cannot be reverted. - Ignoring the return value.
undo()andredo()returnFalseon an empty stack. Your user interface can use this to gray out a menu item.
Exercise
Add a Replace(doc, position, old, new) command that swaps old for new at position. Which two things must revert() do, and does it need to record anything while apply() runs?
Show answer
revert() must remove new from position and put old back. The command already has both strings from its constructor, so it records nothing at apply time. For example, apply() can be t[:position] + new + t[position + len(old):], and revert() can be t[:position] + old + t[position + len(new):].