INSIDE ZED Upstream ↗ Repository ↗
ENGINE ROOM / 04 · SOURCE-PINNED INVESTIGATION

One edit.
Many layers.

A deep trace of Zed's Rust text-edit lifecycle - from the language-facing API through fragments, ropes, anchors, undo, and remote operation replay.

One edit, several representations

A Zed text edit is not a direct replacement inside one string. The inspected path crosses two buffer layers: the language-facing language::Buffer shapes and publishes the edit, while text::Buffer creates an operation and mutates the underlying fragment/text model.

THE EDIT PIPELINE
Editor / caller
   │
   ▼
language::Buffer::edit
   └─ edit_internal: offsets, no-op filtering, coalescing
         │
         ▼
text::Buffer::edit
   └─ timestamp + EditOperation + history
         │
         ▼
BufferSnapshot::apply_edit_internal
   ├─ Fragment / Locator index
   ├─ insertion index + insertion slices
   └─ RopeBuilder → visible_text + deleted_text
         │
         ▼
transaction end → reparse / BufferEvent
         │
         ▼
Project event handler → serialize + ordered message

VERIFIED FLOW This sequence is supported by the implementations linked in each section; the project/network layer is an event consumer, not part of the core text mutation function.

1. The language-facing edit API

The public entry point is language::Buffer::edit in crates/language/src/buffer.rs. It delegates to edit_internal. That method converts the supplied ranges to offsets, swaps reversed endpoints, skips an empty insertion over an empty range, and coalesces adjacent/overlapping edits when the requested mode allows it. See edit / edit_internal ↗.

When at least one edit remains, edit_internal opens a transaction, captures any pre-edit state needed for auto-indent, and calls self.text.edit(edits.iter().cloned()). It then constructs auto-indent requests where applicable, closes the transaction, and emits the edit as Operation::Buffer(edit_operation). See edit_internal body ↗.

VERIFIED - line-ending normalization occurs in the text layer's BufferSnapshot::apply_edit_internal via LineEnding::normalize_arc, even though the language API documents the LF-normalization behavior.

2. The transaction boundary is nested

The language buffer tracks its own transaction depth and delegates transaction start/end to its inner text buffer. The text buffer's edit also calls start_transaction and end_transaction. Because History::start_transaction only creates a new history entry when depth becomes one, the nested call remains inside the outer transaction rather than creating a separate undo unit. See language transaction wrapper ↗ and History::start_transaction ↗.

Outside tests, History::new initializes a 300 ms grouping interval. History::group merges trailing transactions when the next transaction starts within that interval and grouping has not been suppressed. A transaction can therefore contain multiple edit operation IDs. See History construction and grouping ↗.

3. The operation records causal context

The core text::Buffer::edit ticks its Lamport clock, calls apply_local_edit, stores the resulting operation in history, registers its timestamp for undo, observes that timestamp in the snapshot version, and closes the nested transaction. See text::Buffer::edit ↗.

EditOperation contains four fields: timestamp, version, ranges, and new_text. The range type is Range<FullOffset>. The operation's version is copied from the snapshot before the local edit is applied, so it records the causal context on which the edit was based. See Operation and EditOperation definitions ↗ and apply_edit_internal setup ↗.

ANALYSIS - the operation is a replayable description of a change plus its causal precondition, not merely a post-edit string snapshot. The remote application path uses that precondition when mapping the ranges onto another replica's fragment layout.

4. Fragments preserve insertion identity and deletion history

A Fragment stores a Locator, insertion timestamp, offset within the inserted operation text, length, visibility, deletion timestamps, and the maximum undo version observed for it. See Fragment definition ↗.

For inserted text, push_fragments_for_insertion creates one or more fragments. It splits at MAX_INSERTION_LEN while respecting UTF-8 character boundaries, assigns each fragment a locator between the previous new fragment and the next existing fragment, and records both an InsertionSlice and an insertion-index entry. The insertion slices later let undo find all fragments derived from a particular edit. See MAX_INSERTION_LEN ↗ and push_fragments_for_insertion ↗.

The production maximum is u32::MAX; tests lower it to 16 to exercise splitting. This is a bound imposed by the relative u32 insertion offsets, not an ordinary small chunk size in production.

When a local edit replaces visible text, the intersecting fragment is cloned and split to the edited interval. The edit timestamp is appended to its deletions, and visible becomes false. The text is not simply discarded: RopeBuilder rebuilds both a visible rope and a deleted-text rope, and the fragment remains indexed. The replacement logic and the final tree/rope swap are in BufferSnapshot::apply_edit_internal ↗.

ANALYSIS - the model keeps the current visible document and the text needed to reconstruct earlier/alternate visibility states. This is why deletion is represented as fragment state plus a deletion timestamp rather than just removing bytes from one string.

5. Anchors point into inserted text, not just a byte offset

An Anchor stores the insertion operation timestamp, an offset into the text inserted by that operation, a left/right bias, and a buffer ID. See Anchor fields ↗.

BufferSnapshot::anchor_at_offset finds the fragment at a visible offset, then creates an anchor from that fragment's timestamp and insertion_offset + overshoot. The insertion index maps an anchor's timestamp/offset back to a fragment locator. Anchor::cmp compares fragment order first, then insertion offset and bias. See anchor lookup and creation ↗ and Anchor ordering and validity ↗.

ANALYSIS - this is the mechanism that allows selections, diagnostics, and other ranges to track text as surrounding content is inserted or deleted. It is a logical position tied to inserted content, with bias resolving boundary behavior.

6. The edit produces a patch for observers

The core edit path publishes a Patch through text subscriptions. The language buffer closes its outer transaction; at the outermost end, did_edit checks edits_since, clears pending auto-indent state, reparses, emits BufferEvent::Edited, updates dirty state, and notifies observers. See local patch publication ↗ and transaction completion ↗ / did_edit ↗.

The language layer's send_operation emits BufferEvent::Operation { operation, is_local }. It does not itself perform network I/O. In the normal project path, the project event handler serializes the operation, optionally sends an update to a remote client, and enqueues an ordered buffer message. Channel buffers have their own listener that serializes and sends UpdateChannelBuffer. See send_operation ↗ , project operation handler ↗, and channel operation handler ↗.

7. Undo and redo are operations too

At the text layer, undo moves a history entry from the undo stack to the redo stack and calls undo_or_redo. That method increments the undo count for each edit ID in the transaction and creates a new UndoOperation. The operation receives its own Lamport timestamp and captures the current version before that timestamp is observed. See undo / redo operation creation ↗.

UndoMap::insert stores counts keyed by the original edit ID and the undo operation ID. was_undone considers only undo operations observed by the requested version and tests the maximum count's parity. A fragment is visible when its insertion has not been undone and every deletion that applies to it has itself been undone. See UndoMap ↗ and Fragment visibility predicates ↗.

apply_undo uses the insertion-slice and insertion-fragment indexes to find fragments affected by the edit IDs, recalculates each fragment's visibility, rebuilds the visible/deleted rope pair, updates the fragment tree, and publishes a patch. The language buffer's undo and redo methods then emit the resulting operation as a local buffer event. See fragment lookup and apply_undo ↗ and language Buffer undo / redo ↗.

8. Remote operations wait for their causal dependencies

text::Buffer::apply_ops inserts incoming operations into history, applies those whose base version is already observed, and defers the others. can_apply_op checks the operation's recorded version against the current global version and prevents later operations from a replica being applied while that replica has a deferred predecessor. The deferred queue is ordered by Lamport timestamp and deduplicates equal timestamps on insertion. See apply_ops / apply_op ↗ , deferred operations and causal gate ↗, and OperationQueue ↗. The queue sorts and deduplicates equal timestamps within each vector batch passed to insert; that is not a global deduplication pass over every item already in the tree.

At the language layer, language::Buffer::apply_ops separates text-buffer operations from other buffer operations. It forwards text operations to text::Buffer::apply_ops and defers non-text operations such as diagnostics or selections until their anchors can be resolved. The incoming text operations are surfaced as non-local buffer events before the text layer applies them. See language Buffer::apply_ops ↗.

Remote edits are applied by apply_remote_edit, not by calling the local edit path with current visible offsets. It traverses fragments in a version-aware dimension, preserves fragments the incoming operation did not observe, skips concurrent insertions at the range start when their Lamport timestamp is higher, and marks only observed-and-visible intersections as deleted. This is the crucial distinction between a local range and a remote range being replayed against a replica that may have concurrent content. See apply_remote_edit ↗.

VERIFIED TEST - test_concurrent_edits constructs three replicas, makes independent edits, exchanges operations, and asserts that all three visible texts converge to the same result. test_random_concurrent_edits runs randomized edit/undo/redo/network-delivery sequences and checks both invariants and equal final text. See deterministic concurrent edit test ↗ and random concurrent operation test ↗.

9. What the inspected code does - and does not - establish

  • Established: local edits produce timestamped operations with causal versions; fragment IDs and insertion offsets are retained; deletions and undo state affect fragment visibility; remote operations are gated by observed causal context.
  • Established by tests: the tested concurrent-edit scenarios converge, including randomized sequences over multiple replicas.
  • Not established by this pass: a formal convergence proof for every possible schedule, a worst-case bound for locator growth, network delivery guarantees, or performance numbers for the complete edit pipeline.

NEXT HYPOTHESES TO TEST - stress fragment splitting under repeated overlapping edits; measure locator depth under adversarial insertion patterns; test deferred operation queues under reordered multi-replica deliveries; benchmark edit latency with a large deleted-text history.

Source revision

This investigation is pinned to upstream Zed commit 2664a0aa1eae5dabf8f8273c03f88d53061ca7dc. If the upstream implementation changes, re-check the cited ranges before carrying conclusions forward. The study is independent and is not affiliated with Zed Industries.