Requirements & System Scope
Functional Scope (In-Scope)
- Editing: Type a character at the caret, delete a range, and replace a range, each expressed as a
Commandobject withexecuteandundo. - Undo and Redo: Walk backwards and forwards through a history that is bounded by a maximum number of steps. The oldest step is evicted when the cap is exceeded.
- Redo Invalidation: Any new edit that follows an undo clears the redo stack, because those steps describe a future that no longer exists.
- Typing Coalescing: Consecutive single-character keystrokes merge into one undo step, so one undo removes a whole typed run instead of one letter.
- Caret Restoration: Undo puts the caret back where it was before the edit, and redo leaves it at the end of the re-applied edit.
- Change Notification: Observers receive the text and the caret after every action so a view can redraw.
- Thread Safety: One lock per editor keeps an edit and an undo from interleaving.
Explicit Boundaries (Out-of-Scope)
- No Selections or Multiple Carets: The caret is a single index. A selection would widen
CursorMementoto hold an anchor as well. - No Collaborative Editing: One user edits one document. Concurrent authors need operational transform or a CRDT, which the concurrency section points to.
- No Rich Text, Files or Persistence: The document is a plain string held in memory, and the history is not saved across sessions.
- No Unicode Normalisation: Positions index the languageβs own string units, which are UTF-16 code units in Java and TypeScript and code points in Python.
Class Diagram & Entity Relationships
The editor is a facade over three collaborators. The Document owns the text and the Cursor, the UndoRedoManager owns the two stacks of Command objects, and the observers receive a callback after each action. Every field and method below mirrors the Java blueprint, and the TypeScript and Python versions use the same names in their own casing.
- Commands carry what they need to reverse themselves:
DeleteCommandandReplaceCommandrecord the removed or replaced text insideexecute, soundoneeds no extra input and a redo can simply callexecuteagain. - The manager is text-agnostic:
UndoRedoManageronly sees theCommandinterface and theDocumentit hands to each call, so adding a new kind of edit never touches it. - Memento kept small on purpose:
CursorMementois an immutable record holding only the caret position, which is cheap to store once per step and exact to restore.
Design Patterns & SOLID Principles
- Command Pattern (InsertCommand, DeleteCommand, ReplaceCommand): Each edit becomes an object with
executeandundo, so the history is just two stacks ofCommandvalues and the manager never needs to know what an edit does. - Memento Pattern (CursorMemento):
Cursoris the originator.save()returns an immutableCursorMementothat each command keeps as itsbeforefield, andrestore()puts the caret back on undo. Only the caret is snapshotted, never the text. - Observer Pattern (EditorObserver):
TextEditoris the subject and callsonChange(text, cursor)on every registeredEditorObserveronce per action, so a view, a status bar or an autosave can react without the editor knowing they exist. - Facade Pattern (TextEditor): One class exposes
type,deleteRange,replace,moveCursor,undoandredo, and hides the document, the manager and the lock behind them. - Open-Closed Principle:
ReplaceCommandneeds no change inUndoRedoManager. A new edit type only has to implementCommand, and it opts in to coalescing by overridingtryMerge.
Algorithm: Two Stacks of Inverse Commands
Baseline: snapshot the whole text
The simplest undo copies the full text onto an undo stack before every edit and pops a copy back on undo. It is easy to get right, but each edit costs O(N) time and O(N) space, where N is the document length. With a 1,000,000 character document and a 100 step history, that is 100,000,000 characters of copies, even if every edit changed a single letter. Typing the five letters of a word would store five near-identical full copies.
Optimization: store the inverse of each edit (the aha moment)
An edit already knows exactly what it changed, so the history can keep only that. An insert is undone by deleting the text it inserted, a delete is undone by re-inserting the text it captured, and a replace is undone by replacing the new text with the captured old text. Each step costs O(k) space for k changed characters, and undoing it costs about the same as the edit itself. The two stacks then give the full behaviour.
- Executing a command runs it, clears the redo stack, and pushes it on the undo stack.
- Undo pops the undo stack, calls
undo, and pushes the command on the redo stack. - Redo pops the redo stack, calls
executeagain, and pushes the command back on the undo stack. - When the undo stack grows past
maxHistory, the oldest step at the bottom is dropped. That text stays in the document and simply cannot be undone any more.
In the driver, typing Hello, then Β world, then ! leaves three steps. One undo removes the ! and puts the caret at 11, a second removes Β world and puts the caret at 5, and a redo re-inserts Β world and leaves the caret at 11.
Coalescing typed characters
Undoing one letter at a time is unusable, so a keystroke is merged into the step on top of the undo stack when all four conditions hold. It must be a single typed character, the previous action must also have been typing, the gap since the previous keystroke must be at most coalesceWindowMs, and it must land exactly where the top step ends. The last test lives in InsertCommand.tryMerge, which compares the next position with position + text.length and then appends the character to its own text. The merged step keeps the caret memento from the first keystroke, so one undo deletes the whole run and restores the caret from before the first letter.
Any undo, redo, delete, replace or moveCursor closes the typing run, which ends it even when the next keystroke would be contiguous and quick. The driver shows this by moving the caret to 5 and typing Β world at 100 ms spacing, which still starts a new step. The window is measured between consecutive keystrokes, so a steady typist never splits a run, while a pause longer than the window does. Many editors also end a run at a space or newline, which would be one more condition inside tryMerge. The clock is injected so tests control time, and a production build would pass a monotonic clock.
When a Memento is the right tool
Snapshots are the better choice when the state is small or the edit is hard to invert. The caret is the first case, so every command stores a CursorMemento and a selection would extend it. A bulk transform such as format document or sort lines can change text in ways that are awkward to describe as a delta, so a snapshot of the affected range is simpler and obviously correct. A persistent structure such as a rope or a piece table also makes snapshots cheap, because it can copy a short list of pieces instead of the characters. That is how a Git commit can be a full snapshot of a tree while sharing every unchanged object.
Complexity
- Edit, undo and redo:
O(N)in the worst case here, because the text after the edit shifts, or is copied for immutable strings. The cost of an undo matches the edit it reverses. - History memory:
O(k)per step forkchanged characters, so at most the sum of the retained edits, againstO(H Γ N)forHsnapshots. - Eviction:
O(1)with a double-ended queue in Java and Python. The TypeScriptshift()isO(H), which is fine for smallH. - Merging a keystroke: the checks are
O(1), and appending to an immutable string copies the run, so a very long run costs quadratic time overall. A string builder or a list of chunks would make it linear.
Core Execution Workflows
1. Typing a Character
- The caller invokes
type(ch), which takes the editor lock. - The editor builds an
InsertCommandat the caret position and storescursor.save()as itsbeforememento. UndoRedoManager.executeruns the command, so the character is inserted and the caret moves to the end of it.- The redo stack is cleared.
- If the run is open, the gap is within the window, and
tryMergeaccepts the position, the character is appended to the top step. Otherwise the command is pushed as a new step and the oldest step is evicted if the cap is exceeded. - Observers are notified with the new text and caret, and the lock is released.
2. Undo
- The caller invokes
undo()and the editor takes its lock. - If the undo stack is empty the call returns false and nothing changes. This is also what happens after the oldest steps have been evicted.
- Otherwise the top command is popped and its
undoruns. An insert deletes its text, a delete re-inserts its captured text, and a replace swaps the old text back. The caret is restored from thebeforememento. - The command moves to the redo stack, the typing run is closed, and observers are notified.
3. Redo
- The caller invokes
redo(). An empty redo stack returns false, which is what a fresh edit after an undo causes. - Otherwise the top redo command is popped and
executeruns again, which re-applies the edit and sets the caret at its end. - The command moves back to the undo stack, the run is closed, and observers are notified.
4. Delete, Replace and Invalid Input
deleteRangeandreplacereject a length below one before any command is built.- The command is executed first and pushed second.
Documentvalidates the range before it mutates anything, so an out-of-range edit throws, and the stacks, the text and the observers are all untouched. The driver showsdeleteRange(40, 2)failing while the undo depth stays at 4. - A valid edit is pushed as a non-typing step, which closes any open typing run.
5. Moving the Caret
moveCursor(pos)rejects a position outside the text.- Otherwise it moves the caret, seals the typing run so the next keystroke starts a new step, and notifies observers. No command is created, so caret moves are not themselves undoable.
Concurrency & Thread Safety Strategy
An editor looks single-user, but a background autosave, a spell checker, a plugin or a UI thread plus a macro runner can all call it at once. The shared mutable state is the document text, the caret, both stacks, the typing-run flag with its timestamp, and the observer list. Every one of them is reachable only through TextEditor, and none of the inner classes is thread-safe on its own.
The races
- Edit versus undo: Thread A types a sixth character and is about to merge it into the top step while thread B pops that step and deletes its recorded five characters. The text keeps one stray character, and the step on the redo stack now claims six, so a later redo inserts six more.
- Undo versus undo: Two threads read the same top step and both call its
undo. The second one deletes text that is no longer there or removes someone elseβs characters, and the step lands on the redo stack twice. - Edit versus redo: One thread clears the redo stack because of a new edit while another thread pops from it, so a redo re-applies a step against text it was never recorded for.
- Container corruption: The text builder and the deques are not safe under concurrent mutation, so even two plain calls can corrupt them.
The guard and where it sits
In Java every public method of TextEditor is synchronized, so the editorβs monitor is the single document lock and the text, caret, stacks and flags always change together. The Python version takes a threading.RLock with a with block in every public method, reads included. Both locks are reentrant, so an observer that calls back into the editor on the same thread does not deadlock. TypeScript has no lock because it is single-threaded and every method is synchronous with no await, so one call finishes before the next starts. If an asynchronous step such as autosave is added, it must not await between building a command and executing it.
One coarse lock is enough because a document has a single human typist, so contention is negligible and correctness is easy to argue. The cost is that observers run inside the lock. A slow observer stalls typing and undo, and an observer that waits on another thread which needs the editor can deadlock. A production editor copies the text and caret under the lock and delivers the notification after releasing it, usually by posting to the UI thread.
What the blueprint does not guard
- Check-then-act across calls: Each call is atomic but a pair is not.
if (undoDepth() > 0) undo()can lose the race, and a caller that readstext()and then callsdeleteRangecan find that another thread shifted the offsets in between. A hardened API takes a document version with each edit and rejects it when the version is stale, or exposes a compound operation that runs under the lock. - Whose undo it is: With several writers on one history, undo reverts the most recent edit by anyone, so one thread can undo anotherβs typing.
- Several authors on different machines: Every command stores absolute positions, which stay valid only while the document is exactly as the command left it. A remote insert before your edit shifts those positions and invalidates your stack. Collaborative editors use operational transform, which rewrites each concurrent operation against the ones it raced with, or a sequence CRDT, which gives every character a stable identifier so operations do not depend on positions. Undo then becomes a new inverse operation of your own edit, transformed past later edits, instead of a pop from a stack. Neither is implemented here.
A test that exposes a broken guard
The Java and Python drivers run this check. Four threads each type 250 characters into a shared editor, which should end at length 1000 as one coalesced step. Then four threads each run 100 undo and redo pairs, and the driver prints whether the single step sits in exactly one stack with a text length of 0 or 1000 to match. Removing synchronized or the with block should eventually show up as an exception, a wrong depth sum or a text that disagrees with the stacks, though a race may need many runs to fire.
Complete Clean Code Blueprint
Below is a runnable Java, TypeScript and Python blueprint of the same design. Each driver types and coalesces a word, undoes and redoes it, shows the redo stack being dropped, replaces and deletes text under a history capped at four steps, and rejects an invalid edit. The Java and Python drivers also run the thread stress check, while TypeScript runs the same final consistency check sequentially because its event loop already serialises calls.
// βββ JAVA BLUEPRINT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
// Memento: an immutable snapshot of the caret, taken before every edit.
record CursorMemento(int position) {}
class Cursor {
private int position = 0;
public int position() { return position; }
public void moveTo(int position) { this.position = position; }
public CursorMemento save() { return new CursorMemento(position); }
public void restore(CursorMemento memento) { this.position = memento.position(); }
}
class Document {
private final StringBuilder text = new StringBuilder();
private final Cursor cursor = new Cursor();
public String text() { return text.toString(); }
public int length() { return text.length(); }
public Cursor cursor() { return cursor; }
public void insert(int position, String s) {
checkPosition(position);
text.insert(position, s);
}
public String delete(int position, int length) {
checkRange(position, length);
String removed = text.substring(position, position + length);
text.delete(position, position + length);
return removed;
}
public String replace(int position, int length, String s) {
checkRange(position, length);
String old = text.substring(position, position + length);
text.replace(position, position + length, s);
return old;
}
private void checkPosition(int position) {
if (position < 0 || position > text.length()) {
throw new IllegalArgumentException("Position " + position + " is outside 0.." + text.length());
}
}
private void checkRange(int position, int length) {
if (position < 0 || length < 0 || position + length > text.length()) {
throw new IllegalArgumentException("Range " + position + "+" + length + " is outside 0.." + text.length());
}
}
}
interface Command {
void execute(Document doc);
void undo(Document doc);
String describe();
default boolean tryMerge(Command next) { return false; }
}
class InsertCommand implements Command {
private final int position;
private String text;
private final CursorMemento before;
public InsertCommand(int position, String text, CursorMemento before) {
this.position = position;
this.text = text;
this.before = before;
}
public void execute(Document doc) {
doc.insert(position, text);
doc.cursor().moveTo(position + text.length());
}
public void undo(Document doc) {
doc.delete(position, text.length());
doc.cursor().restore(before);
}
// Typing coalesces only when the next character lands exactly where this run ends.
public boolean tryMerge(Command next) {
if (!(next instanceof InsertCommand other)) return false;
if (other.position != position + text.length()) return false;
text += other.text;
return true;
}
public String describe() { return "Insert('" + text + "' @" + position + ")"; }
}
class DeleteCommand implements Command {
private final int position;
private final int length;
private final CursorMemento before;
private String removed;
public DeleteCommand(int position, int length, CursorMemento before) {
this.position = position;
this.length = length;
this.before = before;
}
public void execute(Document doc) {
removed = doc.delete(position, length);
doc.cursor().moveTo(position);
}
public void undo(Document doc) {
doc.insert(position, removed);
doc.cursor().restore(before);
}
public String describe() { return "Delete('" + removed + "' @" + position + ")"; }
}
class ReplaceCommand implements Command {
private final int position;
private final int length;
private final String replacement;
private final CursorMemento before;
private String replaced;
public ReplaceCommand(int position, int length, String replacement, CursorMemento before) {
this.position = position;
this.length = length;
this.replacement = replacement;
this.before = before;
}
public void execute(Document doc) {
replaced = doc.replace(position, length, replacement);
doc.cursor().moveTo(position + replacement.length());
}
public void undo(Document doc) {
doc.replace(position, replacement.length(), replaced);
doc.cursor().restore(before);
}
public String describe() { return "Replace('" + replaced + "' -> '" + replacement + "' @" + position + ")"; }
}
class UndoRedoManager {
private final int maxHistory;
private final long coalesceWindowMs;
private final Deque<Command> undoStack = new ArrayDeque<>();
private final Deque<Command> redoStack = new ArrayDeque<>();
private boolean typingRunOpen = false;
private long lastTypedAt = 0;
public UndoRedoManager(int maxHistory, long coalesceWindowMs) {
if (maxHistory < 1) throw new IllegalArgumentException("maxHistory must be at least 1");
this.maxHistory = maxHistory;
this.coalesceWindowMs = coalesceWindowMs;
}
public void execute(Command command, Document doc, boolean typing, long nowMs) {
command.execute(doc); // throws before any stack changes if the edit is invalid
redoStack.clear(); // a new edit abandons the undone future
boolean merged = typing
&& typingRunOpen
&& nowMs - lastTypedAt <= coalesceWindowMs
&& !undoStack.isEmpty()
&& undoStack.peekLast().tryMerge(command);
if (!merged) {
undoStack.addLast(command);
if (undoStack.size() > maxHistory) undoStack.pollFirst(); // evict the oldest step
}
typingRunOpen = typing;
lastTypedAt = nowMs;
}
public boolean undo(Document doc) {
Command command = undoStack.pollLast();
if (command == null) return false;
command.undo(doc);
redoStack.addLast(command);
typingRunOpen = false;
return true;
}
public boolean redo(Document doc) {
Command command = redoStack.pollLast();
if (command == null) return false;
command.execute(doc);
undoStack.addLast(command);
typingRunOpen = false;
return true;
}
// Any non-typing action ends the current typing run, so the next keystroke starts a new step.
public void seal() { typingRunOpen = false; }
public int undoDepth() { return undoStack.size(); }
public int redoDepth() { return redoStack.size(); }
public List<String> labels() {
List<String> labels = new ArrayList<>();
for (Command command : undoStack) labels.add(command.describe());
return labels;
}
}
interface EditorObserver {
void onChange(String text, int cursor);
}
class TextEditor {
private final Document doc = new Document();
private final UndoRedoManager history;
private final LongSupplier clock;
private final List<EditorObserver> observers = new ArrayList<>();
public TextEditor(int maxHistory, long coalesceWindowMs, LongSupplier clock) {
this.history = new UndoRedoManager(maxHistory, coalesceWindowMs);
this.clock = clock;
}
// Every public method takes the editor's monitor: one lock guards text, caret and both stacks.
public synchronized void addObserver(EditorObserver observer) { observers.add(observer); }
public synchronized void type(char ch) {
Command command = new InsertCommand(doc.cursor().position(), String.valueOf(ch), doc.cursor().save());
history.execute(command, doc, true, clock.getAsLong());
notifyObservers();
}
public synchronized void deleteRange(int position, int length) {
if (length < 1) throw new IllegalArgumentException("Length must be positive");
history.execute(new DeleteCommand(position, length, doc.cursor().save()), doc, false, clock.getAsLong());
notifyObservers();
}
public synchronized void replace(int position, int length, String replacement) {
if (length < 1) throw new IllegalArgumentException("Length must be positive");
history.execute(new ReplaceCommand(position, length, replacement, doc.cursor().save()), doc, false, clock.getAsLong());
notifyObservers();
}
public synchronized void moveCursor(int position) {
if (position < 0 || position > doc.length()) throw new IllegalArgumentException("Cursor " + position + " is outside the text");
doc.cursor().moveTo(position);
history.seal();
notifyObservers();
}
public synchronized boolean undo() {
boolean changed = history.undo(doc);
if (changed) notifyObservers();
return changed;
}
public synchronized boolean redo() {
boolean changed = history.redo(doc);
if (changed) notifyObservers();
return changed;
}
public synchronized String text() { return doc.text(); }
public synchronized int cursor() { return doc.cursor().position(); }
public synchronized int undoDepth() { return history.undoDepth(); }
public synchronized int redoDepth() { return history.redoDepth(); }
public synchronized List<String> historyLabels() { return history.labels(); }
private void notifyObservers() {
String text = doc.text();
int cursor = doc.cursor().position();
for (EditorObserver observer : observers) observer.onChange(text, cursor);
}
}
// Stand-in for a UI: counts refreshes and remembers what it last drew, with | as the caret.
class StatusBar implements EditorObserver {
int refreshes = 0;
String lastView = "";
public void onChange(String text, int cursor) {
refreshes++;
lastView = text.substring(0, cursor) + "|" + text.substring(cursor);
}
}
public class Main {
private static void show(TextEditor editor, String label) {
System.out.println(label + " -> text='" + editor.text() + "' cursor=" + editor.cursor()
+ " undo=" + editor.undoDepth() + " redo=" + editor.redoDepth());
}
public static void main(String[] args) throws Exception {
AtomicLong now = new AtomicLong(0);
TextEditor editor = new TextEditor(4, 500, now::get);
StatusBar bar = new StatusBar();
editor.addObserver(bar);
System.out.println("--- Typing and coalescing ---");
for (char ch : "Hello".toCharArray()) { editor.type(ch); now.addAndGet(100); }
show(editor, "typed Hello (5 keystrokes, one step)");
editor.moveCursor(5);
for (char ch : " world".toCharArray()) { editor.type(ch); now.addAndGet(100); }
show(editor, "cursor move sealed the run, typed ' world'");
now.addAndGet(2000);
editor.type('!');
show(editor, "paused past the 500ms window, typed '!'");
System.out.println("--- Undo, redo and the redo stack ---");
editor.undo();
show(editor, "undo");
editor.undo();
show(editor, "undo");
editor.redo();
show(editor, "redo");
editor.type('?');
show(editor, "typed '?' after an undo, redo history dropped");
System.out.println("redo available: " + editor.redo());
System.out.println("--- Replace, delete and bounded history (max 4) ---");
editor.replace(0, 5, "Howdy");
show(editor, "replace Hello with Howdy");
editor.deleteRange(11, 1);
show(editor, "delete the '?'");
System.out.println("history: " + editor.historyLabels());
try {
editor.deleteRange(40, 2);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage() + ", undo depth still " + editor.undoDepth());
}
System.out.println("--- Undo until the history is exhausted ---");
int steps = 0;
while (editor.undo()) { steps++; show(editor, "undo #" + steps); }
System.out.println("steps undone: " + steps + ", the evicted first step stays: '" + editor.text() + "'");
System.out.println("observer refreshes: " + bar.refreshes + ", last view: " + bar.lastView);
System.out.println("--- Concurrency: 4 typists, then 4 threads racing undo and redo ---");
TextEditor shared = new TextEditor(100, 1_000, () -> 0L);
Thread[] typists = new Thread[4];
for (int i = 0; i < typists.length; i++) {
typists[i] = new Thread(() -> { for (int j = 0; j < 250; j++) shared.type('a'); });
typists[i].start();
}
for (Thread t : typists) t.join();
System.out.println("typed length=" + shared.text().length() + " undoDepth=" + shared.undoDepth());
Thread[] racers = new Thread[4];
for (int i = 0; i < racers.length; i++) {
racers[i] = new Thread(() -> { for (int j = 0; j < 100; j++) { shared.undo(); shared.redo(); } });
racers[i].start();
}
for (Thread t : racers) t.join();
int length = shared.text().length();
boolean consistent = shared.undoDepth() + shared.redoDepth() == 1
&& length == (shared.redoDepth() == 1 ? 0 : 1000);
System.out.println("after the race: step is in exactly one stack and text matches it: " + consistent);
}
}
Review
How helpful was this walkthrough?
Click a star to rate. We actively use this feedback to refine and update our system design content.
Discussion
Share your thoughts, ask questions, or help others.