Undo and redo

Undo is the feature that separates an editor from a form, and the naive version of it, a list of old strings, breaks as soon as two things can be edited. The version that survives is a stack of commands: every change is an object that knows how to do itself and how to undo itself, and the document knows nothing about either.

Commands, not states

An undo stack of whole documents works for a plotter and not for an editor, because it stores a copy of everything for every keystroke. A command stores only what its own change needs: the text that was inserted, the text that was cut, the number of characters. The interface is two methods:

internal interface ICommand { void Do(); void Undo(); }

Two properties of the design matter more than the interface. A command must capture its state at the moment it is created, not at the moment it is undone, or a later edit changes what the undo will restore. And Do is called by the document, not by the caller, so the same command object can be used again by redo without creating a second one.

The two stacks

The document holds two stacks. A new command does itself, is pushed on the undo stack and clears the redo stack, because the future that redo remembered no longer follows from the present:

internal sealed class Editor { private readonly Stack<ICommand> _undo = new(); private readonly Stack<ICommand> _redo = new(); public string Text { get; private set; } = string.Empty; public int UndoCount => _undo.Count; public int RedoCount => _redo.Count; public void Type(string value) => Run(new AppendCommand(this, value)); public void Undo() { if (_undo.Count == 0) { return; } var command = _undo.Pop(); command.Undo(); _redo.Push(command); } public void Redo() { if (_redo.Count == 0) { return; } var command = _redo.Pop(); command.Do(); _undo.Push(command); } internal void Append(string value) => Text += value; internal void CutLast(int count) => Text = count >= Text.Length ? string.Empty : Text[..(Text.Length - count)]; private void Run(ICommand command) { command.Do(); _undo.Push(command); _redo.Clear(); } }

CutLast is where a real editor grows up: cutting more characters than the document has clears it instead of throwing, because the undo of a command whose text was shorter than expected must not fail. A command that deletes saves the text it removed and puts it back on undo; that is the whole of the two commands this lesson uses.

A form with Undo and Redo

The form has a read-only text box that shows the document, two buttons, and an Edit menu whose items carry the shortcuts. Every command runs through Change, which updates the view afterwards. Built and not run:

using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new EditorForm()); } } internal interface ICommand { void Do(); void Undo(); } internal sealed class Editor { private readonly Stack<ICommand> _undo = new(); private readonly Stack<ICommand> _redo = new(); public string Text { get; private set; } = string.Empty; public bool CanUndo => _undo.Count > 0; public bool CanRedo => _redo.Count > 0; public void Type(string value) => Run(new AppendCommand(this, value)); public void Delete(int count) { if (Text.Length > 0) { Run(new DeleteCommand(this, count)); } } public void Undo() { if (_undo.Count == 0) { return; } var command = _undo.Pop(); command.Undo(); _redo.Push(command); } public void Redo() { if (_redo.Count == 0) { return; } var command = _redo.Pop(); command.Do(); _undo.Push(command); } internal void Append(string value) => Text += value; internal void CutLast(int count) => Text = count >= Text.Length ? string.Empty : Text[..(Text.Length - count)]; private void Run(ICommand command) { command.Do(); _undo.Push(command); _redo.Clear(); } } internal sealed class AppendCommand : ICommand { private readonly Editor _editor; private readonly string _value; public AppendCommand(Editor editor, string value) { _editor = editor; _value = value; } public void Do() => _editor.Append(_value); public void Undo() => _editor.CutLast(_value.Length); } internal sealed class DeleteCommand : ICommand { private readonly Editor _editor; private readonly int _count; private string _removed = string.Empty; public DeleteCommand(Editor editor, int count) { _editor = editor; _count = count; } public void Do() { _removed = _editor.Text.Length <= _count ? _editor.Text : _editor.Text[^_count..]; _editor.CutLast(_count); } public void Undo() => _editor.Append(_removed); } internal sealed class EditorForm : Form { private readonly Editor _editor = new(); private readonly TextBox _document = new() { Dock = DockStyle.Fill, Multiline = true, ReadOnly = true }; private readonly ToolStripMenuItem _undo = new("&Undo") { ShortcutKeys = Keys.Control | Keys.Z }; private readonly ToolStripMenuItem _redo = new("&Redo") { ShortcutKeys = Keys.Control | Keys.Y }; public EditorForm() { Text = "Undo and redo"; ClientSize = new Size(420, 220); _undo.Click += (sender, e) => Change(_editor.Undo); _redo.Click += (sender, e) => Change(_editor.Redo); var menu = new MenuStrip(); var edit = new ToolStripMenuItem("&Edit"); edit.DropDownItems.Add(_undo); edit.DropDownItems.Add(_redo); menu.Items.Add(edit); MainMenuStrip = menu; var type = new Button { Text = "&Type 'abc'", Dock = DockStyle.Bottom, Height = 30 }; type.Click += (sender, e) => Change(() => _editor.Type("abc")); var back = new Button { Text = "&Backspace", Dock = DockStyle.Bottom, Height = 30 }; back.Click += (sender, e) => Change(() => _editor.Delete(1)); Controls.Add(_document); Controls.Add(back); Controls.Add(type); Controls.Add(menu); UpdateView(); } private void Change(Action change) { change(); UpdateView(); } private void UpdateView() { _document.Text = _editor.Text; _undo.Enabled = _editor.CanUndo; _redo.Enabled = _editor.CanRedo; } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. The two menu items are disabled by UpdateView when their stack is empty, which is the difference between a menu that lies and one that does not. ShortcutKeys handles Ctrl+Z and Ctrl+Y for the form without a KeyDown handler, as lesson 037 showed.

The text box is read-only because the document is the model here: typing into the control directly would change the text behind the undo stack's back. A real editor captures the edits of the text box (the TextChanged event, the selection, the clipboard) and turns each into a command; that is the part of capstone A that is hard, and the reason its editor keeps the document in a class.

A run of three edits and four undos

The document alone, with the same two commands, prints its text and both stack sizes after every step. It was built and run here:

using System; using System.Collections.Generic; Console.WriteLine("a command stack over a text document"); var editor = new Editor(); Report("start"); editor.Type("Hello"); Report("type Hello"); editor.Type(", world"); Report("type , world"); editor.Type("!"); Report("type !"); editor.Undo(); Report("undo"); editor.Undo(); Report("undo"); editor.Redo(); Report("redo"); editor.Type("?"); Report("type ?"); editor.Redo(); Report("redo after a new command"); editor.Undo(); editor.Undo(); editor.Undo(); Report("undo three times"); void Report(string step) { Console.WriteLine($"{step}: '{editor.Text}', undo {editor.UndoCount}, redo {editor.RedoCount}"); } internal interface ICommand { string Name { get; } void Do(); void Undo(); } internal sealed class Editor { private readonly Stack<ICommand> _undo = new(); private readonly Stack<ICommand> _redo = new(); public string Text { get; private set; } = string.Empty; public int UndoCount => _undo.Count; public int RedoCount => _redo.Count; public void Type(string value) => Run(new AppendCommand(this, value)); public void Delete(int count) => Run(new DeleteCommand(this, count)); public void Undo() { if (_undo.Count == 0) { return; } var command = _undo.Pop(); command.Undo(); _redo.Push(command); } public void Redo() { if (_redo.Count == 0) { return; } var command = _redo.Pop(); command.Do(); _undo.Push(command); } internal void Append(string value) => Text += value; internal void CutLast(int count) => Text = count >= Text.Length ? string.Empty : Text[..(Text.Length - count)]; private void Run(ICommand command) { command.Do(); _undo.Push(command); _redo.Clear(); } } internal sealed class AppendCommand : ICommand { private readonly Editor _editor; private readonly string _value; public AppendCommand(Editor editor, string value) { _editor = editor; _value = value; } public string Name => $"type {_value}"; public void Do() => _editor.Append(_value); public void Undo() => _editor.CutLast(_value.Length); } internal sealed class DeleteCommand : ICommand { private readonly Editor _editor; private readonly int _count; private string _removed = string.Empty; public DeleteCommand(Editor editor, int count) { _editor = editor; _count = count; } public string Name => $"delete {_count}"; public void Do() { _removed = _editor.Text.Length <= _count ? _editor.Text : _editor.Text[^_count..]; _editor.CutLast(_count); } public void Undo() => _editor.Append(_removed); }

dotnet run

a command stack over a text document
start: '', undo 0, redo 0
type Hello: 'Hello', undo 1, redo 0
type , world: 'Hello, world', undo 2, redo 0
type !: 'Hello, world!', undo 3, redo 0
undo: 'Hello, world', undo 2, redo 1
undo: 'Hello', undo 1, redo 2
redo: 'Hello, world', undo 2, redo 1
type ?: 'Hello, world?', undo 3, redo 0
redo after a new command: 'Hello, world?', undo 3, redo 0
undo three times: '', undo 0, redo 3

The output is the real run, and every step is worth reading. The first undo removed the !; the second removed , world; the redo put , world back, so the text became Hello, world without the exclamation mark. Typing ? then cleared the redo stack, because the command that would have restored the ! is no longer part of this history. The last three undos walked back to the empty document and left three commands waiting to be redone.

What TextBox.Undo does not do

A TextBox has its own undo: CanUndo, Undo, ClearUndo and the Ctrl+Z that the control handles itself. It is enough for a single field and not enough for a document. It is per control, so two text boxes have two histories and undo in one does not undo the other. It is cleared by a programmatic Text assignment, which every load and every refresh does. And it knows nothing of the rest of the document: a delete of a selected block, a list change or a formatting command are not in it.

The rule that follows: a field that holds one value can use the control's undo; a screen with a document needs a command stack in the model, and the text control becomes a view of that model. That is the design of capstone A.

Exercises

  1. Add a DeleteCommand call to the run, undo it, and check that the removed text comes back in the right place.
  2. Give the editor a limit of ten undo steps and explain which command has to be dropped when the eleventh arrives.
  3. Add a Name property to the commands and print the name of the next undo and the next redo in every Report line.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an undo command store?

    Answer

    Only what its own change needs, such as the inserted or removed text

    Storing the whole document for every keystroke is the naive version.

  2. What does a new command do to the redo stack?

    Answer

    Clears it, because the remembered future no longer follows

    The run showed redo 0 after typing ?.

  3. Who calls ICommand.Do when a command is new?

    Answer

    The document, in its Run method

    Run does the command, pushes it and clears redo.

  4. What was the text after the second undo and the redo?

    Answer

    Hello, world

    The undo removed , world and the redo restored it; the ! stayed undone.

  5. Why did the redo after typing ? do nothing?

    Answer

    The new command cleared the redo stack

    The output shows redo 0 before the call.

  6. Why does CutLast clear the text when the count is too large?

    Answer

    The undo of a command must not throw when the document is shorter

    A guard in the model is cheaper than a try in every command.

  7. What enables and disables the two menu items?

    Answer

    UpdateView, from CanUndo and CanRedo

    The form reads the model after every command.

  8. Which shortcut does the Undo item carry?

    Answer

    Ctrl+Z

    Redo carries Ctrl+Y, and ShortcutKeys handles both.

  9. Why is TextBox.Undo not enough for a document?

    Answer

    It is per control, cleared by a Text assignment and knows only its own text

    A document spans controls and other kinds of change.

  10. What is the text box in the form a view of?

    Answer

    The Editor model, whose command stack owns the history

    It is read-only, so the model stays the only source of truth.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev

Banner image