Polski

Undo and redo in a text editor

Editor operations as commands with execute() and undo(), a history with undo and redo, macros undone in one step and a limit on remembered changes.

medium · typescript · javascript · python · csharp · java · go · 20 XP

The product description editor in the shop's admin panel needs Undo and Redo (Ctrl+Z / Ctrl+Y). Today the buttons call the document's methods directly, so there is nothing to undo. The answer is the Command pattern: every change is an object with execute() and undo(), and the history (the invoker) keeps executed commands and can reverse them.

The document (the receiver) is ready: TextDocument has a text field plus insert(position, text) and delete(position, length), which returns the removed fragment.

Task

  1. InsertCommand(doc, position, text) – inserts text; undo() removes exactly what was inserted.
  2. DeleteCommand(doc, position, length) – removes a fragment and remembers it during execute(), so undo() can put it back in the same place.
  3. MacroCommand(commands) – several commands as one step: executed in order, undone in reverse order.
  4. History(limit = 100):

    • execute(command) runs the command, remembers it and clears the redo history;
    • undo() and redo() return true when there was something to do and false otherwise;
    • canUndo() and canRedo() report the state of the stacks;
    • beyond the limit the oldest command drops out of the history.

The tests add their own command (upper-casing) – the history must work with it without any changes. Names per language: can_undo/can_redo (Python), the CanUndo/CanRedo properties and the ICommand interface (C#), NewInsert, NewDelete, NewMacro(cmds...) and NewHistory(limit) (Go).

Topics: Command

Related articles

  • Command: a request wrapped in an object

    The Command pattern through a waiter's terminal in a pierogi place: every action on the ticket is an object with execute and undo, so it can be undone, redone, kept in a history and sent to a queue. Code in five languages.