Type a character in the middle of a huge document and a naive editor would shift and re-copy everything after it — O(n) per keystroke. Real editors use smarter structures. A piece table keeps the loaded file as a read-only original buffer, appends every newly typed character to a separate append-only add buffer, and represents the current document as an ordered list of pieces, each just (which buffer, start, length). An insert never copies text — it appends to the add buffer and splits one piece into up to three. The document is whatever you get by reading the pieces in order. (Its cousin the rope stores text as a balanced tree of chunks for the same goal.) Insert some text and watch a piece split.
edits without copying the document · original + add buffers · pieces = (buffer, start, len)
original buffer
The loaded file, read-only and never modified.
add buffer
Append-only storage for everything newly typed.
piece
A span (buffer, start, length) into one of the two buffers.
document
The concatenation of the pieces, read in order — computed, not stored.
piecetable.js — split a piece, append the text
Ready
The document starts as one piece spanning the read-only original buffer. Each insert appends the new text to the add buffer and splits a piece — the original text is never touched or copied. Insert to edit.
1
pieces
0
add buffer chars
0
chars copied
How it works
The elegance is that the two buffers only ever grow at the end and are never rewritten. The original buffer is the file as loaded, fixed forever. The add buffer is append-only: new text goes on the end and stays put. All the editing lives in the cheap piece list. Inserting text at a position finds the piece covering that position and splits it: the part before the insertion stays a piece pointing into its original buffer, a new piece points at the just-appended text in the add buffer, and the part after becomes a third piece — again pointing into the original buffer, no bytes moved. Because nothing is copied, an insert is O(1) plus the small cost of splitting the piece list, and undo is trivial: just remember the previous piece list (the buffers already hold everything). The rope achieves the same goals with a balanced tree of text chunks, giving O(log n) split and concatenate.
1
Load into a read-only original buffer
The document text as loaded lives in an immutable original buffer. Start with one piece spanning all of it.
2
Append new text to the add buffer
When the user types, append those characters to the end of a separate, append-only add buffer. Nothing existing is moved.
3
Split a piece to insert
To insert at a position, split the piece there into a "before" part, a new piece pointing at the just-added text, and an "after" part. Only the small piece list changes.
✓
Read pieces in order; undo is free
The current document is the concatenation of the pieces in order — computed on demand. Undo/redo just swap piece-list versions, since both buffers already contain every character ever typed.
Insert
no doc copy
Buffers
append-only
Undo
trivial
Rope split/concat
O(log n)
The code
# piece table insert: append to add buffer, split a piecedef insert(self, pos, text):
start = len(self.add)
self.add += text # append-only, no copy
new_piece = Piece('add', start, len(text))
offset = 0; result = []
for p in self.pieces:
if offset <= pos <= offset + p.length:
left = pos - offset
if left: result.append(Piece(p.buf, p.start, left))
result.append(new_piece) # the inserted textif left < p.length: result.append(Piece(p.buf, p.start+left, p.length-left))
else: result.append(p)
offset += p.length
self.pieces = result # document = pieces in order
Quick check
1. Where does newly typed text go in a piece table?
All new text is appended to the add buffer, which only ever grows at the end. The original buffer is read-only. This is why editing never has to shift or re-copy existing text.
2. What happens to the piece list when you insert text in the middle of a piece?
Inserting inside a piece splits it: the part before the cursor, a new piece pointing at the just-appended text in the add buffer, and the part after. Only the small piece list changes — no character data is copied.
3. Why is undo trivial in a piece table?
Since the original and add buffers are append-only and never deleted from, every character ever typed still exists. Undo/redo just swaps to a previous version of the piece list — no text needs to be recovered.
FAQ
What is a piece table?
A text-editor data structure: the loaded file sits in a read-only original buffer, new text is appended to an append-only add buffer, and the document is an ordered list of pieces (buffer, start, length) into the two buffers. Edits split/rearrange pieces without copying text, making inserts, deletes, and undo cheap.
What is a rope, and how does it compare?
A rope stores a big string as a balanced tree of small text chunks with cached subtree lengths, giving O(log n) split/concatenate and efficient edits without copying the whole string. Piece tables are simpler and pair well with append-only buffers and undo; ropes give better asymptotics for very large strings and heavy structural edits.
Why not just use a plain string or array for a document?
A contiguous string/array makes a middle insert or delete O(n) because everything after shifts — too slow for large documents and frequent edits. Piece tables and ropes never store the document contiguously; they rearrange spans or chunks, so an edit touches only a little structure.
Which editors use these structures?
Piece tables have a long editor history (the Bravo editor, Microsoft Word, and VS Code’s piece-tree — a piece table backed by a balanced tree). Ropes and gap buffers appear elsewhere (Emacs classically uses a gap buffer). All aim to edit text without copying the whole document.
The picture: the text never moves
The document hello, world! after two inserts into the original hello world. The comma and the exclamation mark sit in the add buffer (highlighted), and the document is just four (buffer, start, length) pieces that point at spans of the two buffers.
Worked example, step by step
Start with the original text hello world (11 characters) as one piece. Then insert, delete and undo, writing the add buffer and the piece list after every step. O means the original buffer, A the add buffer, and the pair is (start, length). A space is drawn as ␣.
Step
Pieces
Add buffer
Document
start
O(0,11)
(empty)
hello␣world
insert(5, ",")
O(0,5) A(0,1) O(5,6)
","
hello,␣world
insert(12, "!")
O(0,5) A(0,1) O(5,6) A(1,1)
",!"
hello,␣world!
delete(7, 5)
O(0,5) A(0,1) O(5,1) A(1,1)
",!"
hello,␣!
insert(0, ">> ")
A(2,3) O(0,5) A(0,1) O(5,1) A(1,1)
",!>> "
>>␣hello,␣!
undo
O(0,5) A(0,1) O(5,1) A(1,1)
",!>> "
hello,␣!
undo
O(0,5) A(0,1) O(5,6) A(1,1)
",!>> "
hello,␣world!
undo
O(0,5) A(0,1) O(5,6)
",!>> "
hello,␣world
Three things stand out. The add buffer only ever grows: it holds ,!>>␣ at the end even after the undos, so no character that was ever typed is lost. The delete of world did not remove any text; it trimmed the piece O(5,6) down to O(5,1), which now covers only the space, and the characters stay in the original buffer. And undo is just putting an earlier piece list back: after three undos the list is the one from the second step and the document is hello, world again, with the exclamation mark waiting in the add buffer.
Complexity and trade-offs
Case
Time
Space
Why
Piece table, piece list in an array
O(p) to find the position, plus O(len) to append the text
O(n + typed + p)
p is the number of pieces. Measured: 1,000 inserts into a 100,000-character document left 1,984 pieces, and finding each position scanned about 994 pieces on average.
Piece table, pieces in a balanced tree
O(log p) per edit
O(n + typed + p)
Same idea with an ordered tree of pieces, which removes the linear scan.
Plain string or array
O(n) per insert or delete
O(n)
Everything after the edit shifts. The same 1,000 inserts moved 50,922,689 characters.
Gap buffer
O(1) at the gap, O(distance) to move it
O(n)
Excellent when edits cluster around the cursor; poor for edits far apart.
Rope
O(log n) split and join
O(n)
A balanced tree of chunks; stronger bounds for huge strings, more machinery.
The piece count is the number to watch. Each insert adds at most two pieces, so after m inserts there are at most 2m + 1 (here at most 2,001, observed 1,984), and each delete can add one. Reading the whole document is a pass over every piece, and random access by character index needs the same walk unless you cache cumulative lengths. What you give up is simplicity of reads; what you get is that no edit ever moves existing text, and that undo and redo are cheap because the old piece lists stay valid.
Common mistakes
A strict comparison at the end of a piece
Testing offset ≤ pos < offset + length never matches the position at the very end of the document. Inserting "X" at position 3 of "abc" then leaves the text as "abc" while the add buffer grows to "X". Allow pos == offset + length for the last piece.
Computing the start offset after appending
The new piece must start where the add buffer ended before the append. Reading len(add) afterwards points the piece past its own text, so inserting "XY" into "hello" produced "hello": the inserted characters were in the buffer but the piece read an empty span.
Deleting only inside the first piece
A delete may span several pieces. A version that trims only the piece containing the start turned "hello, world!" with delete(3, 8) into "hel, world!" instead of "held!". Walk every piece that overlaps the range, trimming the first, dropping the middle ones and trimming the last.
Leaving empty pieces behind
A delete that exactly consumes a piece can leave a piece of length 0. Keeping them is harmless to the text but not to the list: after 100 rounds of insert-then-delete of one character, the list held 102 pieces instead of 2. Drop zero-length pieces as you rebuild the list.
Not checking the position
An insert beyond the end of the document matches no piece. For the 12-character "hello, world", insert(13, "!") silently did nothing to the text but appended "!" to the add buffer. Validate 0 ≤ pos ≤ length and raise an error.
Where this shows up
Text editors
Keeping the loaded file untouched and recording edits as spans means an edit costs the same however large the file is. This is the main reason the structure exists.
Undo and redo
Because buffers are append-only, every earlier piece list still points at valid text. A history is a stack of piece lists, not a stack of copies of the document.
Opening large files
The original buffer is never written to, so it can be loaded lazily or read in place, and only the typed text needs to be held in memory as the add buffer.
Collaborative and versioned documents
Piece lists are small, cheap to store per revision, and make it easy to see which spans came from the original and which were added later.
SOLVE IT YOURSELF
Solve it: edit a document without moving it
Typing one character into a 10 MB file should not copy 10 MB. A piece table never touches the loaded text at all: it keeps the original read-only, appends every keystroke to a second buffer, and stores the document as an ordered list of spans into the two. Python or TypeScript.
YOUR TASK
Implement PieceTable with insert(pos, text), delete(pos, length) and text(). The original buffer must never be modified, and the add buffer must only ever grow.
HINTS — 8 IDEAS
Two buffers: the original, loaded once and read-only forever, and the add buffer, which is append-only. Neither is ever edited in place.
The document is a list of pieces: (which buffer, start offset, length). Reading the document is just walking the list and concatenating those spans.
To insert at a position, first split the piece that straddles it into two, then drop a new piece pointing at the freshly appended text between them.
To delete a range, split at both ends and remove the pieces in between. The characters stay in their buffer — they simply stop being referenced.
That is why undo is nearly free: nothing was destroyed, so restoring an old piece list restores the old document.
Both operations cost about the piece count, not the document size. Typing into a huge file stays fast because the huge part never moves.
Splitting exactly at a piece boundary must not create an empty piece — return the boundary index instead. Empty pieces are harmless to read but they accumulate and quietly slow everything down.
This is the data structure behind VS Code's editor buffer, for exactly these reasons.