{"id":"6b093dc291bd8fbaf2a0c8e8","slug":"text-editor-undo","title":"Undo and redo in a text editor","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"medium","topics":["command"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["command","undo-redo","macro","text-editor","behavioral"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** Receiver: the edited document (ready, no changes needed). */\nclass TextDocument {\n  text = '';\n\n  insert(position: number, text: string): void {\n    this.text = this.text.slice(0, position) + text + this.text.slice(position);\n  }\n\n  /** Removes `length` characters from `position` and returns the removed text. */\n  delete(position: number, length: number): string {\n    const removed = this.text.slice(position, position + length);\n    this.text = this.text.slice(0, position) + this.text.slice(position + length);\n    return removed;\n  }\n}\n\ninterface Command {\n  execute(): void;\n  undo(): void;\n}\n\nclass InsertCommand implements Command {\n  constructor(\n    private readonly doc: TextDocument,\n    private readonly position: number,\n    private readonly text: string,\n  ) {}\n\n  execute(): void {\n    throw new Error('Not implemented');\n  }\n\n  undo(): void {\n    throw new Error('Not implemented');\n  }\n}\n\n/** Remembers the removed text during execute(), so undo() can put it back. */\nclass DeleteCommand implements Command {\n  constructor(\n    private readonly doc: TextDocument,\n    private readonly position: number,\n    private readonly length: number,\n  ) {}\n\n  execute(): void {\n    throw new Error('Not implemented');\n  }\n\n  undo(): void {\n    throw new Error('Not implemented');\n  }\n}\n\n/** Several commands as one step: executed in order, undone in reverse order. */\nclass MacroCommand implements Command {\n  constructor(private readonly commands: Command[]) {}\n\n  execute(): void {\n    throw new Error('Not implemented');\n  }\n\n  undo(): void {\n    throw new Error('Not implemented');\n  }\n}\n\n/**\n * Invoker. execute() runs the command, remembers it (at most `limit` – the oldest are dropped)\n * and clears the redo history. undo()/redo() return false when there is nothing to do.\n */\nclass History {\n  constructor(private readonly limit = 100) {}\n\n  execute(command: Command): void {\n    throw new Error('Not implemented');\n  }\n\n  undo(): boolean {\n    throw new Error('Not implemented');\n  }\n\n  redo(): boolean {\n    throw new Error('Not implemented');\n  }\n\n  canUndo(): boolean {\n    throw new Error('Not implemented');\n  }\n\n  canRedo(): boolean {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"test('commands change the document through the history', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new InsertCommand(doc, 0, 'Hello'));\n  history.execute(new InsertCommand(doc, 5, ' world'));\n  expect(doc.text).toBe('Hello world');\n  history.execute(new DeleteCommand(doc, 0, 6));\n  expect(doc.text).toBe('world');\n});\n\ntest('undo reverts commands in reverse order', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new InsertCommand(doc, 0, 'Hello'));\n  history.execute(new InsertCommand(doc, 5, ' world'));\n  history.execute(new DeleteCommand(doc, 0, 6));\n  expect(history.undo()).toBe(true);\n  expect(doc.text).toBe('Hello world');\n  expect(history.undo()).toBe(true);\n  expect(doc.text).toBe('Hello');\n  expect(history.undo()).toBe(true);\n  expect(doc.text).toBe('');\n  expect(history.undo()).toBe(false);\n});\n\ntest('DeleteCommand remembers what it removed', () => {\n  const doc = new TextDocument();\n  doc.insert(0, 'abcdef');\n  const history = new History();\n  history.execute(new DeleteCommand(doc, 1, 3));\n  expect(doc.text).toBe('aef');\n  history.undo();\n  expect(doc.text).toBe('abcdef');\n});\n\ntest('redo re-applies undone commands and the flags follow the stacks', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  expect(history.canUndo()).toBe(false);\n  expect(history.canRedo()).toBe(false);\n  history.execute(new InsertCommand(doc, 0, 'a'));\n  expect(history.canUndo()).toBe(true);\n  history.undo();\n  expect(history.canRedo()).toBe(true);\n  expect(history.redo()).toBe(true);\n  expect(doc.text).toBe('a');\n  expect(history.redo()).toBe(false);\n  expect(history.canRedo()).toBe(false);\n});\n\ntest('a new command after undo clears the redo history', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new InsertCommand(doc, 0, 'one'));\n  history.execute(new InsertCommand(doc, 3, ' two'));\n  history.undo();\n  history.execute(new InsertCommand(doc, 3, ' three'));\n  expect(doc.text).toBe('one three');\n  expect(history.canRedo()).toBe(false);\n  expect(history.redo()).toBe(false);\n  expect(doc.text).toBe('one three');\n});\n\ntest('a macro is executed and undone as one step', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new MacroCommand([\n    new InsertCommand(doc, 0, 'Dear '),\n    new InsertCommand(doc, 5, 'Ann'),\n    new InsertCommand(doc, 8, ','),\n  ]));\n  expect(doc.text).toBe('Dear Ann,');\n  history.undo();\n  expect(doc.text).toBe('');\n  expect(history.canUndo()).toBe(false);\n  history.redo();\n  expect(doc.text).toBe('Dear Ann,');\n});\n\ntest('the history keeps only the last N commands', () => {\n  const doc = new TextDocument();\n  const history = new History(2);\n  history.execute(new InsertCommand(doc, 0, 'a'));\n  history.execute(new InsertCommand(doc, 1, 'b'));\n  history.execute(new InsertCommand(doc, 2, 'c'));\n  expect(history.undo()).toBe(true);\n  expect(history.undo()).toBe(true);\n  expect(history.undo()).toBe(false);\n  expect(doc.text).toBe('a');\n});\n\ntest('any object with execute() and undo() works with the history', () => {\n  class UppercaseCommand {\n    constructor(doc) {\n      this.doc = doc;\n      this.before = '';\n    }\n    execute() {\n      this.before = this.doc.text;\n      this.doc.text = this.doc.text.toUpperCase();\n    }\n    undo() {\n      this.doc.text = this.before;\n    }\n  }\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new InsertCommand(doc, 0, 'quiet please'));\n  history.execute(new UppercaseCommand(doc));\n  expect(doc.text).toBe('QUIET PLEASE');\n  history.undo();\n  expect(doc.text).toBe('quiet please');\n  history.redo();\n  expect(doc.text).toBe('QUIET PLEASE');\n});\n"},{"lang":"javascript","runner":"browser","starter":"/** Receiver: the edited document (ready, no changes needed). */\nclass TextDocument {\n  text = '';\n\n  insert(position, text) {\n    this.text = this.text.slice(0, position) + text + this.text.slice(position);\n  }\n\n  /** Removes `length` characters from `position` and returns the removed text. */\n  delete(position, length) {\n    const removed = this.text.slice(position, position + length);\n    this.text = this.text.slice(0, position) + this.text.slice(position + length);\n    return removed;\n  }\n}\n\n// A command is any object with execute() and undo().\n\nclass InsertCommand {\n  constructor(doc, position, text) {\n    this.doc = doc;\n    this.position = position;\n    this.text = text;\n  }\n\n  execute() {\n    throw new Error('Not implemented');\n  }\n\n  undo() {\n    throw new Error('Not implemented');\n  }\n}\n\n/** Remembers the removed text during execute(), so undo() can put it back. */\nclass DeleteCommand {\n  constructor(doc, position, length) {\n    this.doc = doc;\n    this.position = position;\n    this.length = length;\n  }\n\n  execute() {\n    throw new Error('Not implemented');\n  }\n\n  undo() {\n    throw new Error('Not implemented');\n  }\n}\n\n/** Several commands as one step: executed in order, undone in reverse order. */\nclass MacroCommand {\n  constructor(commands) {\n    this.commands = commands;\n  }\n\n  execute() {\n    throw new Error('Not implemented');\n  }\n\n  undo() {\n    throw new Error('Not implemented');\n  }\n}\n\n/**\n * Invoker. execute() runs the command, remembers it (at most `limit` – the oldest are dropped)\n * and clears the redo history. undo()/redo() return false when there is nothing to do.\n */\nclass History {\n  constructor(limit = 100) {\n    this.limit = limit;\n  }\n\n  execute(command) {\n    throw new Error('Not implemented');\n  }\n\n  undo() {\n    throw new Error('Not implemented');\n  }\n\n  redo() {\n    throw new Error('Not implemented');\n  }\n\n  canUndo() {\n    throw new Error('Not implemented');\n  }\n\n  canRedo() {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"test('commands change the document through the history', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new InsertCommand(doc, 0, 'Hello'));\n  history.execute(new InsertCommand(doc, 5, ' world'));\n  expect(doc.text).toBe('Hello world');\n  history.execute(new DeleteCommand(doc, 0, 6));\n  expect(doc.text).toBe('world');\n});\n\ntest('undo reverts commands in reverse order', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new InsertCommand(doc, 0, 'Hello'));\n  history.execute(new InsertCommand(doc, 5, ' world'));\n  history.execute(new DeleteCommand(doc, 0, 6));\n  expect(history.undo()).toBe(true);\n  expect(doc.text).toBe('Hello world');\n  expect(history.undo()).toBe(true);\n  expect(doc.text).toBe('Hello');\n  expect(history.undo()).toBe(true);\n  expect(doc.text).toBe('');\n  expect(history.undo()).toBe(false);\n});\n\ntest('DeleteCommand remembers what it removed', () => {\n  const doc = new TextDocument();\n  doc.insert(0, 'abcdef');\n  const history = new History();\n  history.execute(new DeleteCommand(doc, 1, 3));\n  expect(doc.text).toBe('aef');\n  history.undo();\n  expect(doc.text).toBe('abcdef');\n});\n\ntest('redo re-applies undone commands and the flags follow the stacks', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  expect(history.canUndo()).toBe(false);\n  expect(history.canRedo()).toBe(false);\n  history.execute(new InsertCommand(doc, 0, 'a'));\n  expect(history.canUndo()).toBe(true);\n  history.undo();\n  expect(history.canRedo()).toBe(true);\n  expect(history.redo()).toBe(true);\n  expect(doc.text).toBe('a');\n  expect(history.redo()).toBe(false);\n  expect(history.canRedo()).toBe(false);\n});\n\ntest('a new command after undo clears the redo history', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new InsertCommand(doc, 0, 'one'));\n  history.execute(new InsertCommand(doc, 3, ' two'));\n  history.undo();\n  history.execute(new InsertCommand(doc, 3, ' three'));\n  expect(doc.text).toBe('one three');\n  expect(history.canRedo()).toBe(false);\n  expect(history.redo()).toBe(false);\n  expect(doc.text).toBe('one three');\n});\n\ntest('a macro is executed and undone as one step', () => {\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new MacroCommand([\n    new InsertCommand(doc, 0, 'Dear '),\n    new InsertCommand(doc, 5, 'Ann'),\n    new InsertCommand(doc, 8, ','),\n  ]));\n  expect(doc.text).toBe('Dear Ann,');\n  history.undo();\n  expect(doc.text).toBe('');\n  expect(history.canUndo()).toBe(false);\n  history.redo();\n  expect(doc.text).toBe('Dear Ann,');\n});\n\ntest('the history keeps only the last N commands', () => {\n  const doc = new TextDocument();\n  const history = new History(2);\n  history.execute(new InsertCommand(doc, 0, 'a'));\n  history.execute(new InsertCommand(doc, 1, 'b'));\n  history.execute(new InsertCommand(doc, 2, 'c'));\n  expect(history.undo()).toBe(true);\n  expect(history.undo()).toBe(true);\n  expect(history.undo()).toBe(false);\n  expect(doc.text).toBe('a');\n});\n\ntest('any object with execute() and undo() works with the history', () => {\n  class UppercaseCommand {\n    constructor(doc) {\n      this.doc = doc;\n      this.before = '';\n    }\n    execute() {\n      this.before = this.doc.text;\n      this.doc.text = this.doc.text.toUpperCase();\n    }\n    undo() {\n      this.doc.text = this.before;\n    }\n  }\n  const doc = new TextDocument();\n  const history = new History();\n  history.execute(new InsertCommand(doc, 0, 'quiet please'));\n  history.execute(new UppercaseCommand(doc));\n  expect(doc.text).toBe('QUIET PLEASE');\n  history.undo();\n  expect(doc.text).toBe('quiet please');\n  history.redo();\n  expect(doc.text).toBe('QUIET PLEASE');\n});\n"},{"lang":"python","runner":"browser","starter":"from abc import ABC, abstractmethod\n\n\nclass TextDocument:\n    \"\"\"Receiver: the edited document (ready, no changes needed).\"\"\"\n\n    def __init__(self):\n        self.text = \"\"\n\n    def insert(self, position: int, text: str) -> None:\n        self.text = self.text[:position] + text + self.text[position:]\n\n    def delete(self, position: int, length: int) -> str:\n        \"\"\"Removes `length` characters from `position` and returns the removed text.\"\"\"\n        removed = self.text[position:position + length]\n        self.text = self.text[:position] + self.text[position + length:]\n        return removed\n\n\nclass Command(ABC):\n    @abstractmethod\n    def execute(self) -> None: ...\n\n    @abstractmethod\n    def undo(self) -> None: ...\n\n\nclass InsertCommand(Command):\n    def __init__(self, doc: TextDocument, position: int, text: str):\n        self.doc, self.position, self.text = doc, position, text\n\n    def execute(self) -> None:\n        raise NotImplementedError\n\n    def undo(self) -> None:\n        raise NotImplementedError\n\n\nclass DeleteCommand(Command):\n    \"\"\"Remembers the removed text during execute(), so undo() can put it back.\"\"\"\n\n    def __init__(self, doc: TextDocument, position: int, length: int):\n        self.doc, self.position, self.length = doc, position, length\n\n    def execute(self) -> None:\n        raise NotImplementedError\n\n    def undo(self) -> None:\n        raise NotImplementedError\n\n\nclass MacroCommand(Command):\n    \"\"\"Several commands as one step: executed in order, undone in reverse order.\"\"\"\n\n    def __init__(self, commands: list[Command]):\n        self.commands = list(commands)\n\n    def execute(self) -> None:\n        raise NotImplementedError\n\n    def undo(self) -> None:\n        raise NotImplementedError\n\n\nclass History:\n    \"\"\"Invoker. execute() runs the command, remembers it (at most `limit` – the oldest are dropped)\n    and clears the redo history. undo()/redo() return False when there is nothing to do.\"\"\"\n\n    def __init__(self, limit: int = 100):\n        self.limit = limit\n\n    def execute(self, command: Command) -> None:\n        raise NotImplementedError\n\n    def undo(self) -> bool:\n        raise NotImplementedError\n\n    def redo(self) -> bool:\n        raise NotImplementedError\n\n    def can_undo(self) -> bool:\n        raise NotImplementedError\n\n    def can_redo(self) -> bool:\n        raise NotImplementedError\n","testCount":8,"tests":"def expect_text(doc, want):\n    assert doc.text == want, f\"expected {want!r}, got {doc.text!r}\"\n\n\ndef test_commands_change_the_document_through_the_history():\n    doc, history = TextDocument(), History()\n    history.execute(InsertCommand(doc, 0, \"Hello\"))\n    history.execute(InsertCommand(doc, 5, \" world\"))\n    expect_text(doc, \"Hello world\")\n    history.execute(DeleteCommand(doc, 0, 6))\n    expect_text(doc, \"world\")\n\n\ndef test_undo_reverts_commands_in_reverse_order():\n    doc, history = TextDocument(), History()\n    history.execute(InsertCommand(doc, 0, \"Hello\"))\n    history.execute(InsertCommand(doc, 5, \" world\"))\n    history.execute(DeleteCommand(doc, 0, 6))\n    assert history.undo() is True\n    expect_text(doc, \"Hello world\")\n    assert history.undo() is True\n    expect_text(doc, \"Hello\")\n    assert history.undo() is True\n    expect_text(doc, \"\")\n    assert history.undo() is False, \"nothing left to undo\"\n\n\ndef test_delete_command_remembers_what_it_removed():\n    doc, history = TextDocument(), History()\n    doc.insert(0, \"abcdef\")\n    history.execute(DeleteCommand(doc, 1, 3))\n    expect_text(doc, \"aef\")\n    history.undo()\n    expect_text(doc, \"abcdef\")\n\n\ndef test_redo_reapplies_undone_commands_and_the_flags_follow_the_stacks():\n    doc, history = TextDocument(), History()\n    assert history.can_undo() is False and history.can_redo() is False\n    history.execute(InsertCommand(doc, 0, \"a\"))\n    assert history.can_undo() is True\n    history.undo()\n    assert history.can_redo() is True\n    assert history.redo() is True\n    expect_text(doc, \"a\")\n    assert history.redo() is False\n    assert history.can_redo() is False\n\n\ndef test_a_new_command_after_undo_clears_the_redo_history():\n    doc, history = TextDocument(), History()\n    history.execute(InsertCommand(doc, 0, \"one\"))\n    history.execute(InsertCommand(doc, 3, \" two\"))\n    history.undo()\n    history.execute(InsertCommand(doc, 3, \" three\"))\n    expect_text(doc, \"one three\")\n    assert history.can_redo() is False\n    assert history.redo() is False\n    expect_text(doc, \"one three\")\n\n\ndef test_a_macro_is_executed_and_undone_as_one_step():\n    doc, history = TextDocument(), History()\n    history.execute(MacroCommand([\n        InsertCommand(doc, 0, \"Dear \"),\n        InsertCommand(doc, 5, \"Ann\"),\n        InsertCommand(doc, 8, \",\"),\n    ]))\n    expect_text(doc, \"Dear Ann,\")\n    history.undo()\n    expect_text(doc, \"\")\n    assert history.can_undo() is False\n    history.redo()\n    expect_text(doc, \"Dear Ann,\")\n\n\ndef test_the_history_keeps_only_the_last_n_commands():\n    doc, history = TextDocument(), History(limit=2)\n    history.execute(InsertCommand(doc, 0, \"a\"))\n    history.execute(InsertCommand(doc, 1, \"b\"))\n    history.execute(InsertCommand(doc, 2, \"c\"))\n    assert history.undo() is True\n    assert history.undo() is True\n    assert history.undo() is False, \"the oldest command should have been dropped\"\n    expect_text(doc, \"a\")\n\n\ndef test_any_command_subclass_works_with_the_history():\n    class UppercaseCommand(Command):\n        def __init__(self, doc):\n            self.doc, self.before = doc, \"\"\n\n        def execute(self):\n            self.before = self.doc.text\n            self.doc.text = self.doc.text.upper()\n\n        def undo(self):\n            self.doc.text = self.before\n\n    doc, history = TextDocument(), History()\n    history.execute(InsertCommand(doc, 0, \"quiet please\"))\n    history.execute(UppercaseCommand(doc))\n    expect_text(doc, \"QUIET PLEASE\")\n    history.undo()\n    expect_text(doc, \"quiet please\")\n    history.redo()\n    expect_text(doc, \"QUIET PLEASE\")\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\n\n/// <summary>Receiver: the edited document (ready, no changes needed).</summary>\npublic class TextDocument\n{\n    public string Text { get; set; } = \"\";\n\n    public void Insert(int position, string text)\n    {\n        Text = Text.Substring(0, position) + text + Text.Substring(position);\n    }\n\n    /// <summary>Removes length characters from position and returns the removed text.</summary>\n    public string Delete(int position, int length)\n    {\n        var removed = Text.Substring(position, length);\n        Text = Text.Remove(position, length);\n        return removed;\n    }\n}\n\npublic interface ICommand\n{\n    void Execute();\n    void Undo();\n}\n\npublic class InsertCommand : ICommand\n{\n    private readonly TextDocument doc;\n    private readonly int position;\n    private readonly string text;\n\n    public InsertCommand(TextDocument doc, int position, string text)\n    {\n        this.doc = doc;\n        this.position = position;\n        this.text = text;\n    }\n\n    public void Execute() { throw new NotImplementedException(); }\n    public void Undo() { throw new NotImplementedException(); }\n}\n\n/// <summary>Remembers the removed text during Execute, so Undo can put it back.</summary>\npublic class DeleteCommand : ICommand\n{\n    private readonly TextDocument doc;\n    private readonly int position;\n    private readonly int length;\n\n    public DeleteCommand(TextDocument doc, int position, int length)\n    {\n        this.doc = doc;\n        this.position = position;\n        this.length = length;\n    }\n\n    public void Execute() { throw new NotImplementedException(); }\n    public void Undo() { throw new NotImplementedException(); }\n}\n\n/// <summary>Several commands as one step: executed in order, undone in reverse order.</summary>\npublic class MacroCommand : ICommand\n{\n    private readonly List<ICommand> commands;\n\n    public MacroCommand(IEnumerable<ICommand> commands)\n    {\n        this.commands = new List<ICommand>(commands);\n    }\n\n    public void Execute() { throw new NotImplementedException(); }\n    public void Undo() { throw new NotImplementedException(); }\n}\n\n/// <summary>\n/// Invoker. Execute runs the command, remembers it (at most limit – the oldest are dropped)\n/// and clears the redo history. Undo/Redo return false when there is nothing to do.\n/// </summary>\npublic class History\n{\n    private readonly int limit;\n\n    public History(int limit = 100)\n    {\n        this.limit = limit;\n    }\n\n    public bool CanUndo { get { throw new NotImplementedException(); } }\n    public bool CanRedo { get { throw new NotImplementedException(); } }\n\n    public void Execute(ICommand command) { throw new NotImplementedException(); }\n    public bool Undo() { throw new NotImplementedException(); }\n    public bool Redo() { throw new NotImplementedException(); }\n}\n","testCount":8},{"lang":"java","runner":"judge0","starter":"import java.util.ArrayList;\nimport java.util.List;\n\n/** Receiver: the edited document (ready, no changes needed). */\nclass TextDocument {\n    private String text = \"\";\n\n    String getText() { return text; }\n    void setText(String text) { this.text = text; }\n\n    void insert(int position, String s) {\n        text = text.substring(0, position) + s + text.substring(position);\n    }\n\n    /** Removes length characters from position and returns the removed text. */\n    String delete(int position, int length) {\n        String removed = text.substring(position, position + length);\n        text = text.substring(0, position) + text.substring(position + length);\n        return removed;\n    }\n}\n\ninterface Command {\n    void execute();\n    void undo();\n}\n\nclass InsertCommand implements Command {\n    private final TextDocument doc;\n    private final int position;\n    private final String text;\n\n    InsertCommand(TextDocument doc, int position, String text) {\n        this.doc = doc;\n        this.position = position;\n        this.text = text;\n    }\n\n    @Override public void execute() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void undo() { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/** Remembers the removed text during execute(), so undo() can put it back. */\nclass DeleteCommand implements Command {\n    private final TextDocument doc;\n    private final int position;\n    private final int length;\n\n    DeleteCommand(TextDocument doc, int position, int length) {\n        this.doc = doc;\n        this.position = position;\n        this.length = length;\n    }\n\n    @Override public void execute() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void undo() { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/** Several commands as one step: executed in order, undone in reverse order. */\nclass MacroCommand implements Command {\n    private final List<Command> commands;\n\n    MacroCommand(List<Command> commands) { this.commands = new ArrayList<>(commands); }\n\n    @Override public void execute() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void undo() { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/**\n * Invoker. execute() runs the command, remembers it (at most limit – the oldest are dropped)\n * and clears the redo history. undo()/redo() return false when there is nothing to do.\n */\nclass History {\n    private final int limit;\n\n    History(int limit) { this.limit = limit; }\n    History() { this(100); }\n\n    void execute(Command command) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    boolean undo() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    boolean redo() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    boolean canUndo() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    boolean canRedo() { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n","testCount":8},{"lang":"go","runner":"judge0","starter":"package main\n\n// TextDocument is the receiver: the edited document (ready, no changes needed).\ntype TextDocument struct {\n\tText string\n}\n\n// Insert puts s at position.\nfunc (d *TextDocument) Insert(position int, s string) {\n\td.Text = d.Text[:position] + s + d.Text[position:]\n}\n\n// Delete removes length bytes from position and returns the removed text.\nfunc (d *TextDocument) Delete(position, length int) string {\n\tremoved := d.Text[position : position+length]\n\td.Text = d.Text[:position] + d.Text[position+length:]\n\treturn removed\n}\n\n// Command can be executed and undone.\ntype Command interface {\n\tExecute()\n\tUndo()\n}\n\n// InsertCommand inserts Text at Position.\ntype InsertCommand struct {\n\tdoc      *TextDocument\n\tposition int\n\ttext     string\n}\n\n// NewInsert creates an insert command.\nfunc NewInsert(doc *TextDocument, position int, text string) *InsertCommand {\n\treturn &InsertCommand{doc: doc, position: position, text: text}\n}\n\nfunc (c *InsertCommand) Execute() {} // TODO\nfunc (c *InsertCommand) Undo()    {} // TODO\n\n// DeleteCommand remembers the removed text during Execute, so Undo can put it back.\ntype DeleteCommand struct {\n\tdoc      *TextDocument\n\tposition int\n\tlength   int\n}\n\n// NewDelete creates a delete command.\nfunc NewDelete(doc *TextDocument, position, length int) *DeleteCommand {\n\treturn &DeleteCommand{doc: doc, position: position, length: length}\n}\n\nfunc (c *DeleteCommand) Execute() {} // TODO\nfunc (c *DeleteCommand) Undo()    {} // TODO\n\n// MacroCommand runs several commands as one step: executed in order, undone in reverse order.\ntype MacroCommand struct {\n\tcommands []Command\n}\n\n// NewMacro creates a macro command.\nfunc NewMacro(commands ...Command) *MacroCommand {\n\treturn &MacroCommand{commands: commands}\n}\n\nfunc (m *MacroCommand) Execute() {} // TODO\nfunc (m *MacroCommand) Undo()    {} // TODO\n\n// History is the invoker. Execute runs the command, remembers it (at most limit – the oldest are dropped)\n// and clears the redo history. Undo/Redo return false when there is nothing to do.\ntype History struct {\n\tlimit int\n}\n\n// NewHistory creates a history keeping at most limit commands.\nfunc NewHistory(limit int) *History {\n\treturn &History{limit: limit}\n}\n\nfunc (h *History) Execute(c Command) {}      // TODO\nfunc (h *History) Undo() bool        { return false } // TODO\nfunc (h *History) Redo() bool        { return false } // TODO\nfunc (h *History) CanUndo() bool     { return false } // TODO\nfunc (h *History) CanRedo() bool     { return false } // TODO\n","testCount":8}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.885Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"The product description editor in the shop's admin panel needs "},{"type":"text","text":"Undo","marks":[{"type":"bold"}]},{"type":"text","text":" and "},{"type":"text","text":"Redo","marks":[{"type":"bold"}]},{"type":"text","text":" (Ctrl+Z / Ctrl+Y). Today the buttons call the document's methods directly, so there is nothing to undo. The answer is the "},{"type":"text","text":"Command","marks":[{"type":"bold"}]},{"type":"text","text":" pattern: every change is an object with "},{"type":"text","text":"execute()","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"undo()","marks":[{"type":"code"}]},{"type":"text","text":", and the history (the invoker) keeps executed commands and can reverse them."}]},{"type":"paragraph","content":[{"type":"text","text":"The document (the receiver) is ready: "},{"type":"text","text":"TextDocument","marks":[{"type":"code"}]},{"type":"text","text":" has a "},{"type":"text","text":"text","marks":[{"type":"code"}]},{"type":"text","text":" field plus "},{"type":"text","text":"insert(position, text)","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"delete(position, length)","marks":[{"type":"code"}]},{"type":"text","text":", which returns the removed fragment."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"InsertCommand(doc, position, text)","marks":[{"type":"code"}]},{"type":"text","text":" – inserts text; "},{"type":"text","text":"undo()","marks":[{"type":"code"}]},{"type":"text","text":" removes exactly what was inserted."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"DeleteCommand(doc, position, length)","marks":[{"type":"code"}]},{"type":"text","text":" – removes a fragment and "},{"type":"text","text":"remembers it during ","marks":[{"type":"bold"}]},{"type":"text","text":"execute()","marks":[{"type":"code"}]},{"type":"text","text":", so "},{"type":"text","text":"undo()","marks":[{"type":"code"}]},{"type":"text","text":" can put it back in the same place."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"MacroCommand(commands)","marks":[{"type":"code"}]},{"type":"text","text":" – several commands as one step: executed in order, undone in "},{"type":"text","text":"reverse","marks":[{"type":"bold"}]},{"type":"text","text":" order."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"History(limit = 100)","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"execute(command)","marks":[{"type":"code"}]},{"type":"text","text":" runs the command, remembers it and "},{"type":"text","text":"clears the redo history","marks":[{"type":"bold"}]},{"type":"text","text":";"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"undo()","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"redo()","marks":[{"type":"code"}]},{"type":"text","text":" return "},{"type":"text","text":"true","marks":[{"type":"code"}]},{"type":"text","text":" when there was something to do and "},{"type":"text","text":"false","marks":[{"type":"code"}]},{"type":"text","text":" otherwise;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"canUndo()","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"canRedo()","marks":[{"type":"code"}]},{"type":"text","text":" report the state of the stacks;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"beyond the limit the oldest command drops out of the history."}]}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The tests add their own command (upper-casing) – the history must work with it without any changes. Names per language: "},{"type":"text","text":"can_undo","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"can_redo","marks":[{"type":"code"}]},{"type":"text","text":" (Python), the "},{"type":"text","text":"CanUndo","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"CanRedo","marks":[{"type":"code"}]},{"type":"text","text":" properties and the "},{"type":"text","text":"ICommand","marks":[{"type":"code"}]},{"type":"text","text":" interface (C#), "},{"type":"text","text":"NewInsert","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"NewDelete","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"NewMacro(cmds...)","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"NewHistory(limit)","marks":[{"type":"code"}]},{"type":"text","text":" (Go)."}]},{"type":"callout","attrs":{"variant":"tip","title":"Order matters"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A \"Dear \" + \"Ann\" + \",\" macro undone starting from the first command would remove the wrong fragments – positions shift after every change. That is why undo goes from the end."}]}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b08bd3080884893657cc910","slug":"command","title":"Command: a request wrapped in an object"}],"topicsInfo":[{"slug":"command","title":"Command","group":"behavioral","icon":"terminal"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:26.887Z","updatedAt":"2026-11-27T08:22:26.887Z"}