A rich-text editor asks two questions all the time: which block contains position N, and where does this block start? Selection, formatting, rendering, comments and collaboration all go through them, often several times per keystroke.

Most editors answer both with a loop over the list of blocks. That is fine for a short document and slow for a long one. This article looks at how that loop works, what an index for it has to do, and how an order-statistic B+ tree answers both questions in O(log n) without becoming a second source of truth.

The examples use Quill’s Parchment, because its source is short and easy to read. Nothing here is specific to Quill: the same idea works for any editor that stores a document as a list of blocks.

This is part one of two. Part two is about virtualization, where an index like this becomes a requirement.

How editors find a position today

The way an editor maps an index to a block decides how much every positional read costs. This section looks at how Parchment does it.

Parchment stores a document as a tree of blots. The root is a Scroll, and its children are lines: a Block for a paragraph, heading or list item, a BlockEmbed for a table or an image, a Container for nested structures. Each child knows its length(), and blocks cache it.

The children live in a doubly linked list. To find the block that contains an index, Parchment starts at the head and subtracts lengths until the remainder fits:

// parchment/src/collection/linked-list.ts (trimmed)
public find(index: number): [T | null, number] {
  let cur = this.head;
  while (cur) {
    const length = cur.length();
    if (index < length) return [cur, index];
    index -= length;
    cur = cur.next;
  }
  return [null, 0];
}
remaining index on arrivalP · 18300@0P · 42282@18H · 9240@60L · 85231@69P · 260146 < 260 ✓@154T · 1@414P · 640@415P · 310@1055P · 5@1365
Figure 1. find(300) over nine blocks (P paragraph, H heading, L list, T table). The numbers above are the remaining index on arrival, the numbers below are where each block starts. It takes five steps to reach P · 260.

The reverse question, where a block starts, is the same walk. A blot asks its parent for its offset among its siblings and adds the parent’s own offset:

// parchment/src/blot/abstract/shadow.ts
public offset(root: Blot = this.parent): number {
  if (this.parent == null || this === root) return 0;
  return this.parent.children.offset(this) + this.parent.offset(root);
}

Editors with an array-based model have the same problem: scanning an array of sizes is still linear, just friendlier to the CPU cache. ProseMirror, for example, keeps a small cache of recently resolved positions to soften it.

Let’s write this down more precisely. Say the document is a sequence of blocks u1,…,unu_1, \dots, u_n with lengths w1,…,wnw_1, \dots, w_n, and WjW_j is the sum of the first jj lengths:

Wj=∑t=1jwtW0=0W_j = \sum_{t=1}^{j} w_t \qquad W_0 = 0

Then the two questions are:

select⁡(i)=min⁡{ j:Wj>i }rank⁡(uj)=Wj−1\operatorname{select}(i) = \min\{\, j : W_j > i \,\} \qquad \operatorname{rank}(u_j) = W_{j-1}

A linked list answers both by walking from the head, so the cost grows with jj. If every character is equally likely to be queried, block jj is hit with probability wj/Wnw_j / W_n, and the average walk is about half of the document:

E[Tlist]=∑j=1nj⋅wjWn  ≈  n+12when lengths are similar\mathbb{E}\left[T_{\text{list}}\right] = \sum_{j=1}^{n} j \cdot \frac{w_j}{W_n} \;\approx\; \frac{n+1}{2} \quad \text{when lengths are similar}

On a document with 10,000 blocks that is about 5,000 steps per read. A single keystroke usually does several reads: the selection is clamped to the document length, converted from a DOM range to an index, converted back for rendering, and asked for its formats. If one keystroke does rr reads:

Ckeystroke≈r⋅n2r=4, n=104  ⇒  2×104 stepsC_{\text{keystroke}} \approx r \cdot \frac{n}{2} \qquad r = 4,\ n = 10^4 \;\Rightarrow\; 2 \times 10^4 \ \text{steps}

That is 20,000 steps before the browser can paint, and each step touches an object the CPU has not seen since the previous keystroke.

What an index has to do

Before choosing a data structure, it helps to write down exactly what it must support. Without the editor around it, this is a well-known problem called dynamic partial sums. We need five operations over a sequence of blocks with lengths:

  • select(i): the block that contains index i, and where it starts.
  • rank(block): where a block starts.
  • update(block, delta): a block’s length changes. This is typing.
  • insert and delete: Enter, Backspace across a line break, paste.

Research on this problem shows that Θ(log⁡n)\Theta(\log n) per operation is the best any structure can do. So the goal is not to beat the logarithm. The goal is to get small constants and to make the index safe to run inside an editor, which adds a few requirements of its own:

  1. No keys. A block’s position is the sum of the lengths before it, so it cannot be stored as a key.
  2. Lookups from a block. The editor holds a block object and asks where it starts.
  3. Inserts anywhere. Inserting in the middle of the document is the normal case.
  4. Cheap length updates. Typing changes one block’s length per keystroke.
  5. More than one aggregate. Length today; line counts, block ids and pixel heights later.
  6. Only a cache. The editor’s own list stays the source of truth. The index can be thrown away and rebuilt at any time.

The last requirement rules out a rope or a piece table. Both are better document models, but adopting one means rewriting the editor. Here we want an index next to the existing model.

Choosing the data structure

Several classic structures can answer positional queries. The table compares them against the requirements above.

Candidateselect / rankinsert in the middleVerdict
Prefix-sum arrayO(log n)O(n)Every insert rewrites the rest of the array.
Fenwick treeO(log n)O(n)Great for updates, but positions are fixed, so an insert shifts everything after it.
Balanced binary tree (red-black, treap) with subtree sumsO(log n)O(log n)Correct and well known. One node per block, about 14 levels at 10,000 blocks, and rotations must repair the sums.
Skip list with widthsO(log n) expectedO(log n) expectedWorks, but uses more pointers and randomness, and a second aggregate is awkward.
Finger treeO(log n)O(log n)Elegant and persistent, but allocates a lot in mutable JavaScript.
B+ tree with subtree sumsO(B logB n)O(B logB n)Shallow, arrays inside nodes, blocks in document order, local splits.

A B+ tree that stores sums instead of keys is sometimes called a counted B-tree. The same idea is used in xi-editor’s rope, a B-tree with metrics, and VS Code’s piece tree uses a red-black tree where each node stores the length and line count of its left subtree.

How tall the tree is

A B+ tree with fanout BB holds up to BB entries per node. When every node is full, the height is:

hmin⁡=⌈log⁡Bn⌉h_{\min} = \left\lceil \log_B n \right\rceil

After splits, nodes are only guaranteed to be half full, and the root can have just two children. So the realistic bound uses B/2B/2:

n≥2(B2)h−1⟹hmax⁡≤1+⌊log⁡B/2n2⌋n \ge 2\left(\tfrac{B}{2}\right)^{h-1} \quad\Longrightarrow\quad h_{\max} \le 1 + \left\lfloor \log_{B/2} \tfrac{n}{2} \right\rfloor

For B=32B = 32 even a large document needs only a few levels:

BlocksLinked list, average stepsHeight, full nodesHeight, half-full nodesBinary tree height
10050227
1,0005002310
10,0005,0003414
100,00050,0004417
1,000,000500,0004520

Why fanout 32

Each level of the tree costs one jump to a new node plus a scan of up to BB entries inside it. A bigger BB means fewer levels but longer scans. If a jump costs chopc_{\text{hop}} and one scan step costs cscanc_{\text{scan}}, a lookup costs:

C(B)=(chop+B cscan)log⁡Bn=chop+B cscanln⁡B ln⁡nC(B) = \left(c_{\text{hop}} + B\,c_{\text{scan}}\right)\log_B n = \frac{c_{\text{hop}} + B\,c_{\text{scan}}}{\ln B}\,\ln n

The ln⁡n\ln n part does not depend on BB, so only the fraction matters. Its minimum is where the derivative is zero:

ddB chop+B cscanln⁡B=0⟹B(ln⁡B−1)=chopcscan\frac{d}{dB}\,\frac{c_{\text{hop}} + B\,c_{\text{scan}}}{\ln B} = 0 \quad\Longrightarrow\quad B\left(\ln B - 1\right) = \frac{c_{\text{hop}}}{c_{\text{scan}}}

Jumping to a node the CPU has not touched recently is much more expensive than scanning a few numbers it just loaded. If a jump costs about 80 scan steps, the optimum lands on 32. The curve is flat around it, so anything from 16 to 64 works, and 32 is a good default.

101001k10k100k1101001k10k100kunits in the document (n)units visited / comparisonscrossover ≈ 128 unitsn = 10,000≈ 5,000 hops≤ 96 comparisonslinked list, expected n/2B+ tree, B = 32, worst case B·h
Figure 2. Average blocks visited by the linked-list loop (n/2n/2) against the worst case for a fanout-32 tree (B⋅⌈log⁡Bn⌉B \cdot \lceil \log_B n \rceil). Below about 128 blocks the loop is cheaper, so small documents should not use the tree. At 10,000 blocks it is 5,000 steps against at most 96 comparisons.

The data structure

The main idea is simple: every node stores the sum of its subtree, and nothing stores a key. Leaves hold blocks in document order, internal nodes hold child nodes, and a block’s position is whatever the sums to its left add up to.

interface Summary { length: number; units: number; }

interface Leaf {
  kind: 'leaf';
  parent: Internal | null;
  units: Unit[];           // at most B blocks, in document order
  lengths: number[];       // the length of each block, same order
  sum: Summary;
}

interface Internal {
  kind: 'internal';
  parent: Internal | null;
  children: Node[];        // at most B child nodes
  sum: Summary;            // the sum of the children's sums
}

// The editor owns the blocks, so a WeakMap never keeps a deleted block alive.
const leafOf = new WeakMap<Unit, Leaf>();

Finding a block by index

select works like the linked-list loop, but it skips whole subtrees instead of single blocks. Here is the same document as Figure 1, under a tree small enough to draw:

rootlength 1370 · units 9leaf Alength 154 · units 4leaf Blength 1216 · units 5P · 18@0P · 42@18H · 9@60L · 85@69P · 260@154T · 1@414P · 640@415P · 310@1055P · 5@1365300 ≥ 154: skip A, 146 left146 < 260 → P · 260, starts at 154
Figure 3. select(300). At the root, 300 is not below A's length of 154, so the whole of A is skipped and 146 is left. In leaf B, 146 is below the first block's 260, so the answer is P · 260, starting at 154. Three comparisons instead of five steps.
function select(root: Node, index: number): { unit: Unit; start: number } | null {
  if (index < 0 || index >= root.sum.length) return null;
  let node = root;
  let remaining = index;

  while (node.kind === 'internal') {
    let c = 0;
    while (remaining >= node.children[c].sum.length) {
      remaining -= node.children[c].sum.length; // skip the whole subtree
      c++;
    }
    node = node.children[c];
  }

  let u = 0;
  while (remaining >= node.lengths[u]) remaining -= node.lengths[u++];
  return { unit: node.units[u], start: index - remaining };
}

Each level scans at most BB entries, so:

Cselect≤B⋅hn=104:  32⋅3=96  vs.  E[Tlist]≈5,000C_{\text{select}} \le B \cdot h \qquad n = 10^4:\ \ 32 \cdot 3 = 96 \ \ \text{vs.} \ \ \mathbb{E}\left[T_{\text{list}}\right] \approx 5{,}000

Finding where a block starts

rank goes the other way. It finds the block’s leaf through leafOf, then walks up to the root and adds everything to the left on each level:

rank⁡(u)=∑ℓ=0h−1 ∑s ∈ left⁡ℓ(u)length⁡(s)\operatorname{rank}(u) = \sum_{\ell=0}^{h-1}\ \sum_{s \,\in\, \operatorname{left}_\ell(u)} \operatorname{length}(s)
rootlength 1370 · units 9leaf Alength 154 · units 4leaf Blength 1216 · units 5P · 18@0P · 42@18H · 9@60L · 85@69P · 260@154T · 1@414P · 640@415P · 310@1055P · 5@1365+ 261P · 260 + T · 1+ 154 from Arank = 415
Figure 4. rank(P · 640). Inside leaf B, the two blocks to its left add 261. At the root, leaf A adds 154. The block starts at 415, the same answer the linked list gets after walking past six blocks.
function rank(unit: Unit): number | null {
  const leaf = leafOf.get(unit);
  if (!leaf) return null;

  let start = 0;
  const at = leaf.units.indexOf(unit);
  for (let i = 0; i < at; i++) start += leaf.lengths[i];

  let child: Node = leaf;
  for (let parent = leaf.parent; parent; child = parent, parent = parent.parent) {
    for (const sibling of parent.children) {
      if (sibling === child) break;
      start += sibling.sum.length;  // everything left of us on this level
    }
  }
  return start;
}

Updating a length

With sums in the nodes, typing is the cheapest operation. A length change walks up the parent chain and adds the delta to each sum on the way:

function update(unit: Unit, delta: number): void {
  const leaf = leafOf.get(unit)!;
  leaf.lengths[leaf.units.indexOf(unit)] += delta;
  for (let node: Node | null = leaf; node; node = node.parent) {
    node.sum.length += delta;   // no re-summing, just carry the delta up
  }
}

A node could also store prefix sums of its children instead of plain sums. That makes select a binary search inside each node, but every update then has to shift all the later entries. The table shows the trade-off:

Node storesselect, per levelupdate, per level
Child sumslinear scan of up to B entriesadd the delta to one entry
Child prefix sumsbinary searchshift every later entry

With prefix sums the binary search takes log⁡2B⋅log⁡Bn=log⁡2n\log_2 B \cdot \log_B n = \log_2 n comparisons, the same as a binary tree, but with far fewer jumps. A keystroke is one update and rr reads, so the cost per keystroke is:

Csums≈r h(chop+B cscan)+h chopCprefix≈r h(chop+ccmplog⁡2B)+h(chop+B cscan)\begin{aligned} C_{\text{sums}} &\approx r\,h\left(c_{\text{hop}} + B\,c_{\text{scan}}\right) + h\,c_{\text{hop}} \\ C_{\text{prefix}} &\approx r\,h\left(c_{\text{hop}} + c_{\text{cmp}}\log_2 B\right) + h\left(c_{\text{hop}} + B\,c_{\text{scan}}\right) \end{aligned}

On paper prefix sums win when a keystroke does two or more reads. In practice a linear scan over 32 numbers is fast and predictable, and both options are small next to the jump between nodes. I’d start with plain sums, because the update path stays trivial, and switch only after profiling.

Storing more than length

Length is only the first thing an editor wants to look up. The same tree can answer other positional questions, as long as each value can be added up from children to parents.

Formally, the summary has to be a monoid (M,⊕,e)(M, \oplus, e): it combines associatively and has an empty value. A node’s summary is then the combination of its children:

sum⁡(node)=sum⁡(c1)⊕sum⁡(c2)⊕⋯⊕sum⁡(ck)\operatorname{sum}(\text{node}) = \operatorname{sum}(c_1) \oplus \operatorname{sum}(c_2) \oplus \cdots \oplus \operatorname{sum}(c_k)

In practice it means a node can carry several values at once, and each of them gets its own select for free. Selecting by pixel height, for example, answers “which block is at y = 48,000 px?” without asking the DOM. That matters a lot once part of the document is not rendered at all.

interface Summary {
  length: number;          // characters
  lines: number;           // a table counts as several lines
  height: number | null;   // null: some block below hasn't been laid out yet
}

const EMPTY: Summary = { length: 0, lines: 0, height: 0 };

function combine(a: Summary, b: Summary): Summary {
  return {
    length: a.length + b.length,
    lines: a.lines + b.lines,
    // An unknown height makes the whole sum unknown instead of silently wrong.
    height: a.height === null || b.height === null ? null : a.height + b.height,
  };
}

The null case matters. Some heights are unknown until a block has been laid out. Counting them as zero would give a confident but wrong pixel offset and scroll the reader to the wrong paragraph. In monoid terms, null is an absorbing element ⊥\bot:

x⊕⊥=⊥⊕x=⊥x⊕y=x+yfor x,y∈R≥0x \oplus \bot = \bot \oplus x = \bot \qquad x \oplus y = x + y \quad \text{for } x, y \in \mathbb{R}_{\ge 0}

The sum stays associative and 0 is still the empty value. If the root height is ⊥\bot, the query returns “unknown” and the caller falls back to another way.

Lookup by a stable block id is not a sum, so it lives in a separate map from id to block. It has one rule: when a line splits, an id can move from one block to another in the same batch of changes. If one block’s old ids are released after another block claimed them, the map loses the entry. So release all old ids first, then claim the new ones:

for (const change of batch) {
  for (const id of change.oldIds) if (idMap.get(id) === change.unit) idMap.delete(id);
}
for (const change of batch) {
  for (const id of change.newIds) idMap.set(id, change.unit);
}

Keeping the index in sync

An index is only useful if it stays in sync with the document. This section covers how the tree learns about changes: lazily for lengths, immediately for structure.

Lazy length updates

update above assumes we know the delta. Editors often don’t: a mutation resets a block’s cached length without saying by how much. Measuring a block after every mutation would give back much of what the faster reads won.

So the tree is lazy. A mutation only puts the block into a dirty set. The next read measures each dirty block once and fixes the sums on its path:

const dirty = new Set<Unit>();

// Called from the editor's mutation hooks: cheap, no measuring.
function markDirty(unit: Unit): void {
  dirty.add(unit);
}

// Called at the start of every indexed read.
function flush(): void {
  for (const unit of dirty) {
    const leaf = leafOf.get(unit);
    if (!leaf) continue;  // removed since it was marked
    const delta = unit.length() - leaf.lengths[leaf.units.indexOf(unit)];
    if (delta !== 0) update(unit, delta);
  }
  dirty.clear();
}

If mm mutations touch kk different blocks between two reads, the two approaches cost:

Ceager=m(cmeasure+h chop)Clazy=m cmark+k(cmeasure+h chop),k≤mC_{\text{eager}} = m\left(c_{\text{measure}} + h\,c_{\text{hop}}\right) \qquad C_{\text{lazy}} = m\,c_{\text{mark}} + k\left(c_{\text{measure}} + h\,c_{\text{hop}}\right), \quad k \le m

Typing is the best case for this. A transaction that inserts, formats and normalizes the same line touches it many times, so mm is large and k=1k = 1.

rootlength 1370 → 1373 · units 9leaf Alength 154 · units 4leaf Blength 1216 → 1219 · units 5P · 18P · 42H · 9L · 85P · 263T · 1P · 640P · 310P · 5dirty set: { P · 263 }+3+3
Figure 5. Typing "abc" into P · 260 only adds it to the dirty set. The next read measures it once and adds +3 to every sum on its path.

Where to hook in

Most editors normalize their tree after a transaction: they merge adjacent text nodes, fix containers and so on. It is tempting to sync the index when normalization finishes, but that is too late. Normalization is usually deferred while a batch of changes is open, and the editor still reads its own length between the operations of that batch. Hook the index to mutations instead:

transactiondocument rootblockindexbegin batchloop · every opinsert / delete / formatread own length:must be right heremutate the blockmark unit dirtynormalize() deferred,batch is openend batch, then normalize()
Figure 6. Inside a batch, normalization doesn't run, but positions are still read. An index that syncs only after normalization is stale exactly when it is used.

Inserts and splits

Structural changes are applied right away. A new block goes into its neighbour’s leaf. If the leaf now has more than B blocks, it splits in two and its parent gets one more child. If the parent overflows, it splits the same way, up to the root.

function insertAfter(prev: Unit, unit: Unit): void {
  const leaf = leafOf.get(prev)!;
  const at = leaf.units.indexOf(prev) + 1;
  leaf.units.splice(at, 0, unit);
  leaf.lengths.splice(at, 0, unit.length());
  leafOf.set(unit, leaf);
  addToPath(leaf, unit.length());          // the same walk up as update()
  if (leaf.units.length > B) split(leaf);  // may climb to the root
}
before: one more unit lands in a full leaf33 > 32parentgains one childafter: split in two16 units17 units
Figure 7. A full leaf takes one more block and splits into 16 and 17. The parent gets one more child, and nothing else in the tree moves.

Deletes and rebuilding

Textbook B-trees rebalance on delete by borrowing from a sibling or merging with it. I’d skip that. Empty nodes are removed, and underfull nodes simply stay underfull. A sparse node costs a few extra comparisons, while borrow-and-merge code is where index bugs usually live.

Sparse nodes still add up over time, so the tree is rebuilt from the editor’s list once the number of live blocks drops below half of n0n_0, the size at the last rebuild. A rebuild is linear, but at least n0/2n_0/2 deletes happened before it, so its cost per delete is constant:

Crebuild#deletions≤c n0/2n0/2=O(1) amortized per deletion\frac{C_{\text{rebuild}}}{\#\text{deletions}} \le \frac{c\,n_0/2}{n_0/2} = O(1) \ \text{amortized per deletion}

A rebuilt tree packs every node full and has the minimal height again.

function onDelete(): void {
  liveUnits--;
  if (liveUnits < sizeAtLastRebuild / 2) {
    rebuildFrom(scroll.children);  // O(n), paid for by n/2 deletes
    sizeAtLastRebuild = liveUnits;
  }
}

Errors are handled the same way. If measuring a block throws, or a structural update hits a state that should be impossible, the tree empties itself and refuses queries until the next rebuild. The mutation that caused it never sees the exception. A bug in the index turns into no index, never into a broken editor.

Checking the index against the list

An index under an editor cannot be “mostly right”. Fortunately, the editor already has a perfect reference: the slow loop. It is simple, it has worked for years, and it answers the same questions. So we run both and compare.

The checks come in two levels. Cheap checks, like total length and block count, run after every change. A full check compares select and rank at the start and end of the document, at the caret and at random positions, plus every block id. It is expensive, so it runs on a random fraction pp of changes:

E[Cverify]=Ccheap+p⋅Cfull\mathbb{E}\left[C_{\text{verify}}\right] = C_{\text{cheap}} + p \cdot C_{\text{full}}

This turns pp into a budget instead of a guess. To keep verification under a fraction ε\varepsilon of an average operation:

p≤ε Cop−CcheapCfulle.g.  ε=5%,  Cfull=5 Cop,  Ccheap≈0  ⇒  p≤1%p \le \frac{\varepsilon\, C_{\text{op}} - C_{\text{cheap}}}{C_{\text{full}}} \qquad \text{e.g.}\ \ \varepsilon = 5\%,\ \ C_{\text{full}} = 5\,C_{\text{op}},\ \ C_{\text{cheap}} \approx 0 \;\Rightarrow\; p \le 1\%
const FULL_CHECK_RATE = 0.01;
const MAX_REBUILDS = 3;

function verify(): void {
  if (tree.sum.length !== scroll.length() || tree.sum.units !== scroll.children.length) {
    return recover('aggregate');
  }
  if (Math.random() < FULL_CHECK_RATE && !fullCheckPasses()) recover('full');
}

function recover(reason: string): void {
  report('index-divergence', { reason });  // never throw
  if (++rebuilds > MAX_REBUILDS) return retire();  // back to the loop for this session
  rebuildFrom(scroll.children);
}

A natural question is how long a bug can hide with only 1% of changes checked. If the tree goes wrong and stays wrong, each change has an independent chance pp to run the full check, so the bug survives tt changes with probability:

Pmiss(t)=(1−p)t≈e−ptp=0.01:  Pmiss(100)≈0.37,  Pmiss(460)≈0.01P_{\text{miss}}(t) = (1 - p)^t \approx e^{-pt} \qquad p = 0.01:\ \ P_{\text{miss}}(100) \approx 0.37,\ \ P_{\text{miss}}(460) \approx 0.01

A bug that breaks the total length is caught on the next change by the cheap check.

05001000150020000.000.250.500.751.00changes since the divergence (t)P(still undetected)p = 1%: below 1% after ≈ 460p = 0.1%: still ≈ 0.14 at 2,000sampling rate p = 1%sampling rate p = 0.1%
Figure 8. The chance that a persistent bug is still undetected after tt changes. With a 1% check rate, a few hundred keystrokes are enough to find it.

When a check fails, the index records it, rebuilds from the list and continues. The number of rebuilds per session is capped at RR. A mismatch that survives several rebuilds is a real bug, and rebuilding on every keystroke would cost more than the loop it replaces. So the worst case is bounded by O(R⋅n)O(R \cdot n), after which the index retires and all reads go back to the loop.

That fallback is part of the design. Every indexed read keeps the original loop as its else branch:

function lineAt(index: number): Line | null {
  const tree = usableIndex();            // null while batching, after a failure or after retiring
  const hit = tree?.select(index);
  if (hit) return lineInside(hit.unit, index - hit.start);
  return walkFromHead(index);            // the original loop, unchanged
}

An index that says “I don’t know” costs speed, never correctness.

What not to index

Some reads should not go through the tree even when they could:

  • Reads inside a batch. If each read flushes the dirty set and a batch reads once per operation, every operation re-measures what the previous one changed. Let the batch use the loop, and flush once at the end.
  • Iterating the whole document. There is nothing to look up, so the tree only adds work.
  • APIs with a different consistency model. If an API answers from a snapshot taken after the last transaction while the tree reads live blocks, the two legitimately disagree in the middle of a transaction. Serving that API from the tree would quietly change its answers.

Where this is going

The real reason for the tree is virtualization. A virtualized editor renders real blocks only around the viewport and replaces the rest with placeholders. With n=10,000n = 10{,}000 blocks and a window of about a hundred, only 1% of the document is in the DOM and rendering costs O(window)O(\text{window}) instead of O(n)O(n), but every positional query still has to be right about the other 99%.

For the tree, a placeholder is just another unit whose summary is the sum of the blocks it stands for:

sum⁡(g)=⨁u ∈ run⁡(g)sum⁡(u)\operatorname{sum}(g) = \bigoplus_{u \,\in\, \operatorname{run}(g)} \operatorname{sum}(u)

The id map can point to blocks that were never rendered, so a link to the last paragraph finds the placeholder that holds it, and the editor renders exactly that part. The height summary answers “what is at this y?” from estimates until real measurements replace them. Swapping real blocks for a placeholder has to happen in one batch, with no flush in between, or one query will count those blocks twice. This is the subject of part two.

Conclusion

In conclusion, positional reads in a block editor are a dynamic partial-sums problem, and a linked-list walk answers them in linear time. A B+ tree that stores subtree sums instead of keys answers the same questions in a few comparisons, carries several aggregates at once, and stays a cache next to the editor’s own list. Lazy length updates keep typing cheap, rebuilding replaces delete rebalancing, and sampled checks against the original loop catch mistakes early. The loop itself doesn’t go away: it becomes the fallback, so the worst case is the editor working exactly as it did before.