↓ Skip to main content

Building a tiny text editor in Go, part 3: choosing a text buffer

·2018 words·10 mins
Table of Contents

Part 1 built the core of ted. Part 2 implemented undo by copying every line before every edit. It was a useful first approach but didn’t scale well. This post explores alternatives and then implements a piece table.

What an editor asks of text
#

An editor repeatedly reads visible lines, inserts and deletes at the cursor, maps between line/column positions and offsets, and retains old states for undo. No representation wins every operation.

StructureLocal insertRandom insertFind a lineUndoImplementation
One stringO(n)O(n)O(n)copy texttiny
Array of linesO(line length)O(number of lines) when splittingO(1)copy lineseasy
Gap bufferamortized O(1)O(n) to move gapO(n) without indexlog edits/copymoderate
Piece table (slice)O(p), given an offsetO(p), given an offsetO(n) to rebuild the line cache after an edit (ted)copy piecesmoderate
Balanced ropeO(log n)O(log n)O(log n) with countsstructural sharinghard

Here n is text size and p is the number of pieces. Big-O notation omits constant factors and locality: an array of lines often beats a tree on ordinary files because contiguous runs of memory are friendly to CPUs.

The piece table’s O(p) edit cost assumes the buffer already has a text offset. This implementation finds that offset by walking its lines, then rebuilds them after the edit so it can redraw, so a keypress that changes text here costs O(n + p).

Gap buffers
#

A gap buffer keeps unused capacity at the cursor. Typing fills the gap in O(1) amortized time; editing far away copies text to relocate it. This exploits the fact that editing is usually local. A line index is normally added because rendering should not scan from the beginning on every frame.

Ropes
#

A rope is a balanced tree of text chunks. Internal nodes cache lengths and, often, newline counts. Splitting, concatenating, inserting, and deleting are logarithmic. Ropes offer dependable performance for huge documents, at the cost of balancing code, allocations, and pointer chasing. They are excellent engineering and too much machinery for tiny ted.

Where these structures appear in real editors
#

These are not merely textbook options. All three have appeared in widely used editors, although production implementations usually add indexes, trees, and caches around the basic idea.

Gap buffers: Emacs and Scintilla
#

GNU Emacs is the classic example, and it still uses a gap buffer today. Its manual describes an invisible gap that grows when text is deleted, shrinks when text is inserted, and moves only when an edit happens elsewhere. That last detail explains why the first edit in a distant part of a very large Emacs buffer can occasionally take a little longer. See the GNU Emacs Lisp manual’s description of the buffer gap.

Scintilla, the editing component behind SciTE and applications such as Notepad++, also stores text around a movable gap. Its public API even exposes the gap position, and asking for one continuous pointer to the document may move the gap first. See Scintilla’s direct access documentation.

Piece tables: Visual Studio Code
#

Visual Studio Code is the best-known current piece-table example. VS Code originally represented a document as an array of lines, then replaced that model to reduce the cost of opening and editing large files. Its implementation is a piece tree: a piece table whose pieces are organized in a red-black tree and carry extra line information for fast lookup. The VS Code team describes both the trade-offs and the resulting design in Text Buffer Reimplementation.

This is worth emphasizing because “uses a piece table” does not mean “uses the small flat list we are about to write.” VS Code starts from the same idea of references into stored text, but keeps a list of buffers rather than just two, with a tree and cached information to make it practical at its scale.

Ropes: Xi and Helix
#

Xi, an experimental editor developed by Raph Levien and collaborators, used an immutable balanced rope as a central part of its design. Xi is no longer under active development, but its ropes are still instructive: they share unchanged branches, so copies are cheap. Its unusually detailed engine documentation explains how Xi handles asynchronous plugin edits and undo by tracking revisions and retaining deleted text.

Helix is a current editor built on the same broad family of ideas. Its Rust source uses the Ropey library for document text; Helix’s core library re-exports Ropey’s Rope and RopeSlice types. Ropey uses a balanced tree of text chunks and keeps line-break information in the tree, which gives Helix efficient access by both character and line.

The boundaries are not always neat. Editors change implementations over time, and terms such as piece tree, split buffer, and rope describe families of designs rather than one mandatory layout. The base data structure is just a starting point. Extra indexes and caches shape the costs an editor chooses to live with.

The piece table
#

A piece table keeps two stores:

  • original is the file as opened and never changes;
  • add is append-only and receives every insertion.

The current document is a list of pieces. Each piece says “read this range from original” or “read this range from add.” Opening hello world creates one piece. Inserting a comma after hello appends it to add and splits the original piece:

original: "hello world"    add: ","
pieces:   original[0:5], add[0:1], original[5:11]

Deletion removes or trims references; it does not erase either store. Adjacent pieces that reference consecutive regions of the same store are coalesced.

Step through some edits below, then try your own.

A piece table in pseudocode
#

We can describe the data structure with two character stores and a list of small records. A piece contains no text of its own; it only identifies a range in one of the stores:

state:
    original = text read from the file
    add = ""
    pieces = [
        { source: original, start: 0, length: length(original) }
    ]

To read the document, walk through the pieces in order and retrieve the range named by each one:

function documentText():
    result = ""

    for each piece in pieces:
        store = original if piece.source is original else add
        result += store[piece.start : piece.start + piece.length]

    return result

Insertion does not modify either existing store. We append the new text to the add store, find the piece at the edit position, and replace it with up to three pieces: the text before the cursor, the insertion, and the text after the cursor.

function insert(documentPosition, newText):
    save pieces and cursor for undo; clear redo

    addStart = length(add)
    append newText to add
    newPiece = { source: add,
                 start: addStart,
                 length: length(newText) }

    oldPiece, positionInsidePiece = findPiece(documentPosition)

    before = the part of oldPiece before positionInsidePiece
    after  = the part of oldPiece after positionInsidePiece

    replace oldPiece in pieces with:
        before, newPiece, after

    remove any zero-length pieces
    merge neighboring pieces that name consecutive ranges in one store

For example, inserting , tiny at position 5 in hello world produces:

original: "hello world"
add:      ", tiny"

pieces:
    original[0:5]     → "hello"
    add[0:6]          → ", tiny"
    original[5:11]    → " world"

ted itself inserts one character per keypress, but its insertAt accepts a slice of runes, so the same steps handle longer text like this.

Deletion works by changing the list rather than erasing characters. We keep pieces outside the deleted range, trim pieces that partly overlap it, and omit pieces that fall entirely inside it:

function delete(deleteStart, deleteEnd):    // deleteEnd is excluded
    save pieces and cursor for undo; clear redo
    replacement = []

    for each piece and its position in the document:
        if piece is completely outside the deleted range:
            append piece to replacement

        else:
            if part of piece comes before deleteStart:
                append that part to replacement

            if part of piece comes at or after deleteEnd:
                append that part to replacement

    pieces = replacement
    merge neighboring pieces where possible

The text removed from the document remains in original or add, but no current piece points to it. This is useful for undo. Restoring an earlier copy of the piece list makes that text part of the document again without copying the character data:

function undo():
    save current pieces and cursor for redo
    pieces = previous saved piece list
    restore the previous cursor position

This pseudocode skips boundary checks and the conversion between row/column positions and single document positions. Those details matter in the program, but the central idea remains small: text is stable; the list of references is what changes.

Our implementation uses a flat slice. Finding and splitting a piece is O(p). A production implementation can place pieces in a balanced tree and cache subtree lengths and newline counts, but the two-store idea remains the same.

Why history gets cheaper
#

Neither character store is mutated. An undo snapshot therefore copies only the piece descriptors plus the cursor. The append-only add store may retain text that no current piece references; that is the price of simple, durable history. Compared with copying every rune of a large document on each key, piece lists are usually much smaller. Typing 200 characters in one place in the 10 MB file from part 2 keeps roughly 14 KB of piece records, against 8 GB of copied runes.

There is an important catch here: cheap is not free. Edits scattered across the document create many descriptors, and every snapshot copies the current list. Typing in one place is cheaper: each typed character lands right after the previous one in add, so coalescing merges a run of typing into one piece. A tree with persistent nodes or an operation log can improve history further, but that’s out of scope for this simple editor.

A deliberately simple line cache
#

A piece table is good at changing text, but much of our editor thinks in lines. Drawing the screen, moving the cursor, and converting a row and column into an offset all need to know where lines begin and end. A list of pieces does not tell us.

The obvious answer is to reconstruct the document from its pieces and split it into lines whenever someone asks. That is O(n), and ted can ask several times for one keypress. In a 10 MB test file on an Apple M5, one arrow key took over 100 ms this way. Part 2’s array of lines responded effectively instantly.

So ted keeps the lines until the text changes:

function lines():
    if cache is empty:
        text = documentText()
        cache = one slice of text for each line
    return cache

after insert, delete, undo, or redo:
    empty the cache

Cursor movement and redrawing now reuse the cache, making arrow keys as quick as they were in part 2. The pieces still define the document; the cache can be thrown away and rebuilt from them at any time.

The first read after an edit still takes O(n), so we also keep that rebuild cheap. Each cached line is a slice of one reconstructed copy of the text, rather than a separate copy of its own. Typing a character in the 10 MB file takes about 5 ms, close to part 2’s 4 ms.

The price is memory for one extra copy of the text. That is one copy in total, not one per undo step, so history stays small. A further optimization would remember where each line starts and update that information around an edit, without rebuilding the whole document.

Run the focused tests with go test ./.... They cover split insertion, deletion, newline insertion, undo/redo, rune offsets, and keeping the line cache up to date.

At the end of part 3, we have the editor we previously built, but now with an “interesting” data structure for storing text, all for about 125 additional lines of Go! The editor now weighs in at about 640 lines of Go, excluding tests.

In part 4 — the final part — we’ll leave storage alone and turn to presentation: lexing Go, JavaScript, and Markdown with Chroma, then mapping token classes to terminal colors.

The code for this part is here.

Related