Undo and Redo with the Command Pattern

medium
Unit 16 · Strings IV0/3 to milestone

Build a tiny text editor with full undo and redo.

Implement a class Editor with:

  • text: the current text (starts empty)
  • insert(pos, s): insert s at index pos
  • delete(pos, n): delete n characters starting at pos (clipped to the end of the text)
  • undo() and redo(): return False if there's nothing to undo or redo, True otherwise. Any new edit clears the redo stack.
  • begin_group() / end_group(): edits between them undo and redo as a single step (for example, a find-and-replace across the document)

Store each edit as a command object that knows how to reverse itself. Don't store copies of the whole text.

#design-patterns#stacks#classes2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Undo and Redo with the Command Pattern · TechGradify