text

package
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package text implements a convergent (CRDT) text document with Peritext-style marks and stable anchors, designed to live in a `bytes` entity field marked (syncplane.v1.field_behavior).text.

Ordering is Fugue (https://arxiv.org/abs/2305.00583), the tree formulation: concurrent insertions at the same position never interleave. Replication is state-based: every write ships the whole encoded document, and Merge is a pure union — idempotent, commutative and associative — which is exactly the contract the engine's opaque-field merger seam requires (RowChange always ships merged snapshots, never deltas).

The TypeScript client (client/src/text/) implements the identical model with a byte-identical canonical encoding; cross-language conformance vectors live in testdata/text/vectors.json.

Model:

  • An item is one Unicode code point with a permanent identity (peer, counter). Counters are Lamport-style: a fresh id is allocated past every counter the document has seen, so causally-later operations order after what they saw.
  • PEER UNIQUENESS is the precondition that makes those ids identities at all, and this package cannot check it — see the ID doc below.
  • Deletion sets a monotone tombstone flag; item content is immutable and tombstones keep it, so merge can verify identity and anchors keep working. Document state therefore grows with edit history until a maintenance pass compacts it (compact.go), which drops tombstones nothing can still reference and records a floor that stops replicas holding older state from putting them back.
  • Marks are operations over anchor ranges whose winner (per key, per character) is the covering op with the highest id. Removal is a mark op with a nil value, never a physical delete.

All indices in this package count Unicode code points over the visible (non-deleted) text. The TypeScript client converts UTF-16 string indices at its API boundary.

Because items are code points, the API is NOT byte-transparent: the write entry points (Insert, SetString) take text, not arbitrary bytes, and reject anything that is not valid UTF-8 rather than storing U+FFFD in its place. The TypeScript mirror rejects unpaired surrogates for the same reason, that being the one way a JS string can fail to encode.

Index

Constants

This section is empty.

Variables

View Source
var ErrCounterCeiling = errors.New("text: no counters left below the ceiling")

ErrCounterCeiling is returned by an edit that needs a counter above 2^53−1, the largest the format carries. Every edit takes a counter above every counter the document has seen, from any peer, so a document whose version vector reaches the ceiling cannot be edited again. Nothing is changed by an edit that fails with it.

View Source
var ErrFragmentUnusable = errors.New("text: fragment unusable")

ErrFragmentUnusable classifies every way a delta-state fragment can fail on the receiving side: bytes that do not decode as a fragment, and a fragment whose ids or references cannot be reconciled with the state it arrived at. The remedy is the same in all of them — the sender ships full state instead — so replication paths branch on this rather than on the message. Failures of the receiver's own base state are NOT tagged: those are not the sender's to fix.

View Source
var ErrPlainStringUnresolved = errors.New("text: unresolved plain-string value")

ErrPlainStringUnresolved classifies a write carrying a plain-string value where a document was required. The remedy is to resolve it under a writer identity — the value cannot be applied without one — never to resend the same bytes.

View Source
var ErrStateStale = errors.New("text: state predates the compaction floor")

ErrStateStale classifies a write that cannot be applied because it is built on state a compaction dropped. Unlike ErrFragmentUnusable — where the sender simply has to send more — no resend of the same bytes can succeed: the sender has to re-read the row first.

Functions

func ApplyFragmentBytes

func ApplyFragmentBytes(full, frag []byte) ([]byte, error)

ApplyFragmentBytes applies an encoded fragment to an encoded full document and re-encodes canonically. When the fragment was cut against a base the receiver already covers, the result is byte-identical to a full-state Merge with the fragment's source document.

func CouldReclaim

func CouldReclaim(data []byte, n int) (bool, error)

CouldReclaim reports whether Compact could free at least n items and mark operations from the encoded document. n <= 0 is true for anything; empty input — a field nobody has written — is false.

The answer is necessary, never sufficient: it counts every tombstone and every mark op, where Compact frees only the ones nothing can still refer to. So false is a promise that compacting falls short of n, while true has to be confirmed by compacting.

Anything that is not a well-formed stored document is an error, without the distinctions Decode draws between a fragment, an unresolved plain-string value and malformed bytes.

Cost is proportional to the document's runs where Decode's is proportional to its characters, which is what makes it worth asking first.

func DecodeVV

func DecodeVV(data []byte) (map[string]uint64, error)

DecodeVV parses an EncodeVV payload. Empty input is the empty vector — "no floor" — which is how an uncompacted field reads.

func EncodeAnchor

func EncodeAnchor(a Anchor) []byte

EncodeAnchor serializes an anchor for storage outside its document (any bytes field, a presence broadcast, an undo entry). The peer is spelled out in full — standalone anchors cannot reference a document's peer table.

byte   kind (AnchorKind)
if AnchorBefore/AnchorAfter: varint peerLen, peer bytes, varint counter

func EncodeFragment

func EncodeFragment(d, base *Doc) ([]byte, error)

EncodeFragment encodes the state d carries beyond base: items base lacks, tombstone flips (live in base, deleted in d), mark ops base lacks, and d's full version vector. A nil or empty base yields a self-contained fragment carrying the whole document.

base must be a causal ancestor of d — every item, tombstone and mark op in base present unchanged in d. Anything else means the two states diverged and no fragment of d can stand in for a merge of it.

func EncodePlainString

func EncodePlainString(s string) ([]byte, error)

EncodePlainString builds the plain-string value reading as s. It errors on invalid UTF-8, the same text the write entry points refuse (see InvalidUTF8Offset), so a value that could never be applied cannot be built.

The empty string encodes to a one-byte value rather than to nothing, so "reads as empty" stays distinct from an absent field. Store no value at all to make the two indistinguishable.

func EncodeVV

func EncodeVV(vv map[string]uint64) []byte

EncodeVV serializes a version vector for storage outside a document — the engine keeps one per compacted field as that field's floor. Peers are sorted, so the encoding is canonical like everything else here.

varint peerCount
  per peer, sorted by UTF-8 bytes: varint len, bytes, varint counter

func InvalidUTF8Offset

func InvalidUTF8Offset(s string) int

InvalidUTF8Offset reports the byte offset of the first invalid UTF-8 sequence in s, or -1 when s is text the write entry points accept.

It exists for callers that have to decide BEFORE writing: the connector checks the strings its source reported so it can skip one item and carry on, rather than discovering the problem inside a write and failing the whole sweep. Sharing this with requireWellFormed is what makes that precheck agree with the refusal by construction.

func IsFragment

func IsFragment(b []byte) bool

IsFragment reports whether b is fragment-encoded (leading byte 0x02). Empty input is not a fragment — it decodes as an empty full document.

func IsPlainString

func IsPlainString(b []byte) bool

IsPlainString reports whether b is a plain-string value. Empty input is not one: an absent bytes field is a document nobody wrote yet.

func MaxCounter added in v0.2.0

func MaxCounter(data []byte) (uint64, error)

MaxCounter reports the highest counter in an encoded document's version vector, reading only the header. For bytes Encode produced that is the highest counter the document holds or has seen; for other bytes it is the highest the header declares, which Decode raises to the items' counters. Empty input reports 0, as Decode reads it as an empty document. It fails for anything but a format-version-1 document, and for a malformed header.

func Merge

func Merge(base, incoming []byte) ([]byte, error)

Merge combines two encoded document states into one. It is the merger the engine installs for (syncplane.v1.field_behavior).text fields: a pure union of items (content immutable, tombstone flags OR-ed), mark operations and version vectors, re-encoded canonically — idempotent, commutative and associative, with no causal-delivery requirement because every shipped state is causally closed by construction.

Ids are never reused, so a same-id item that disagrees on either side — different content, or a different position in the tree — is corrupt input (two writers shared a peer) and errors rather than silently picking a side. The same holds for a same-id mark op that disagrees on anything.

The base is always a full document — stored rows never hold delta state. The incoming side may be either: a client that knows what the server already confirmed may PATCH with a fragment (fragment.go) carrying only what it holds beyond that, which applies as the same union and produces byte-identical output whenever the receiver covers the fragment's base. When it does not, the error is tagged ErrFragmentUnusable and the remedy is a full-state resend.

Neither side may be a plain-string value (plain.go): the error is tagged ErrPlainStringUnresolved, and the remedy is to resolve the value under a writer identity rather than to resend it.

func MergeFragments

func MergeFragments(a, b []byte) ([]byte, error)

MergeFragments unions two encoded fragments into one: union of items with tombstones OR-ed, union of mark ops, pointwise-max version vectors. Like Merge it is associative and commutative, so a span of per-write fragments can be folded into a single one in any order. Same-id disagreements are the same shared-peer corruption Merge rejects.

func MergeWithFloor

func MergeWithFloor(base, incoming []byte, floor map[string]uint64) ([]byte, error)

MergeWithFloor is Merge against a field that has been compacted: floor is the version vector recorded at the last compaction (empty for a field that never was, in which case this is exactly Merge).

See the package comment above for what the floor decides. The output is byte-identical to Merge's whenever the incoming side carries no purged state, which is every write from a replica that has read the row since.

func PlainString

func PlainString(data []byte) (string, error)

PlainString returns the text a plain-string value reads as. It errors when data is not one — a document included, which PlainText reads instead — and on invalid UTF-8.

func PlainText

func PlainText(data []byte) (string, error)

PlainText returns the text an encoded value reads as: a document's visible text, or a plain-string value's text (plain.go). Empty input reads as "".

It is the cheap read path for query evaluation, rendering and connectors, and the one to take when only the text is wanted: Decode accepts documents alone, and a field-history record's before-state carries the other form.

Types

type Anchor

type Anchor struct {
	Kind AnchorKind
	// Item is set for AnchorBefore/AnchorAfter.
	Item ID
}

Anchor is a stable position in a document: a spot immediately before or after a specific item (or a document end). An anchor held INSIDE a document (a mark boundary) stays resolvable for the life of the document — across remote edits, deletions of the referenced item, and undo — because Compact keeps every item a mark anchors to.

An anchor stored OUTSIDE its document (an undo entry, a presence broadcast) has no such protection: compaction can drop the item it names, and ResolveAnchor then reports it as unknown. Callers holding long-lived external anchors must treat that error as "the position is gone", not as corruption.

func DecodeAnchor

func DecodeAnchor(data []byte) (Anchor, error)

DecodeAnchor parses an EncodeAnchor payload. It reads through the document decoder's primitives, so a standalone anchor is held to the same limits as one inside a document — the varint ceiling and valid UTF-8 — and fails with the same messages as the TypeScript mirror.

type AnchorKind

type AnchorKind uint8

AnchorKind says what an anchor is attached to.

const (
	// AnchorDocStart pins to the start of the document.
	AnchorDocStart AnchorKind = 0
	// AnchorDocEnd pins to the end of the document.
	AnchorDocEnd AnchorKind = 1
	// AnchorBefore pins immediately before the referenced item.
	AnchorBefore AnchorKind = 2
	// AnchorAfter pins immediately after the referenced item.
	AnchorAfter AnchorKind = 3
)

type Delta

type Delta struct {
	Ops []DeltaOp
	// MarksChanged reports whether the mark spans an editor resolved against
	// prev may have moved, so that a binding re-reads Marks() exactly when the
	// formatting it renders could be stale.
	//
	// Spans are resolved from anchors against the current item order, not
	// stored, so they move whenever the text does: an insert inside a bold run
	// extends it, a delete can empty it. The flag is therefore set when the
	// mark-op sets differ OR when the delta changes text at all and the
	// document carries marks. That over-reports (an edit far from every mark
	// re-resolves needlessly) but is never wrong in the direction that matters,
	// and a document with no marks — the common case — never pays.
	MarksChanged bool
}

Delta describes how to transform one document's visible text into another's, plus whether the mark spans it resolved may have moved.

func Diff

func Diff(prev, next *Doc) (Delta, error)

Diff computes the delta from prev to next by comparing item graphs, not strings: an item visible in both is a retain even if equal text moved around it, so an editor applying the delta in place keeps its selection. prev must be a causal ancestor of next (every prev item exists in next), which is always true for a document evolving by local edits and merges.

type DeltaKind

type DeltaKind uint8

DeltaKind tags a DeltaOp.

const (
	// DeltaRetain keeps N code points unchanged.
	DeltaRetain DeltaKind = 0
	// DeltaInsert inserts Text at the current position.
	DeltaInsert DeltaKind = 1
	// DeltaDelete removes N code points at the current position.
	DeltaDelete DeltaKind = 2
)

type DeltaOp

type DeltaOp struct {
	Kind DeltaKind
	// N is the length for retain/delete ops.
	N int
	// Text is the inserted content for insert ops.
	Text string
}

DeltaOp is one step of a text delta, in visible code-point coordinates.

type Doc

type Doc struct {
	// contains filtered or unexported fields
}

Doc is a mutable text document. It is not safe for concurrent use.

func Decode

func Decode(data []byte, peer string) (*Doc, error)

Decode parses an encoded document. peer becomes the writer identity for subsequent edits (pass "" for read-only use). Empty input decodes to an empty document — an absent bytes field is a document nobody wrote yet.

func New

func New(peer string) *Doc

New returns an empty document owned by the given peer.

func (*Doc) AnchorAt

func (d *Doc) AnchorAt(index int, kind AnchorKind) (Anchor, error)

AnchorAt returns an anchor for the caret position index (0..Len). kind picks which neighbour the anchor sticks to: AnchorBefore attaches to the item at index (drifting left stays put when text is inserted at the position), AnchorAfter attaches to the item at index-1 (the anchor follows text inserted at the position). Document edges fall back to AnchorDocStart/AnchorDocEnd.

func (*Doc) ApplyFragment

func (d *Doc) ApplyFragment(f *Fragment) error

ApplyFragment merges f into d: the same pure union Merge performs, with f's dangling references resolved against d. Validation is complete before the first mutation — a rejected fragment leaves d untouched, which is what lets the engine answer "resend full state" without a savepoint. Every failure is tagged ErrFragmentUnusable, since that answer is the only remedy.

func (*Doc) Compact

func (d *Doc) Compact() (items, marks int)

Compact drops the mark operations that can no longer affect resolution and every tombstone the document can then no longer need, returning how many of each it removed. The version vector is left alone: it is the record of what this document has seen, and dropping entries from it would make the ids of purged items look unseen again (see issues/106).

Mark ops go FIRST, and the set of anchored items is computed after they do: an op is the only thing keeping its boundary tombstones alive, so reclaiming one is what makes them reclaimable in the same pass. The reverse order reclaims nothing on the item side until the next pass.

An item is purgeable when it is deleted, has no children, and no mark operation anchors to it. The three conditions are what keep the result a well-formed document rather than a lossy one:

  • Children keep their parent: the Fugue tree places concurrent insertions relative to the item they were typed next to, so an item somebody else typed inside deleted text pins the deleted text in place.
  • Anchored items keep marks resolvable. Dropping the item instead — and with it the mark operation, as an earlier design did — silently loses formatting whenever a mark's boundary anchor happened to point at deleted text, which an ExpandBefore/ExpandAfter mark does routinely.

Purging cascades, so a run of text that was typed and then deleted (a chain of right children) collapses entirely — the common case, and the one setString produces when a whole-value writer shortens a document. The result does not depend on visitation order, and the cost is linear in the document however deep the chain runs.

What it does NOT reclaim, and cannot: a tombstone that still has a live descendant. Deleting the middle of a typed run leaves the characters between it and the run's surviving tail in place, because they are the tree positions that tail is defined by. Re-parenting the survivors is not an option — sibling order is by id, so a child moved up to its grandparent would sort into a different place in the text. Compaction therefore bounds a document by the live text plus the tombstones that position it, not by the live text alone.

func (*Doc) Delete

func (d *Doc) Delete(index, length int) error

Delete tombstones length visible code points starting at index.

func (*Doc) Encode

func (d *Doc) Encode() []byte

Encode serializes the document canonically. An empty document (no items, no marks, no version vector) still encodes to a small non-empty header; callers that want "absent" semantics should special-case it themselves.

func (*Doc) Insert

func (d *Doc) Insert(index int, s string) error

Insert inserts s at the given visible code-point index (0..Len). s must be valid UTF-8; the API is not byte-transparent (see requireWellFormed). It fails with ErrCounterCeiling when the document has too few counters left for the code points of s.

func (*Doc) Len

func (d *Doc) Len() int

Len returns the visible (non-deleted) length in code points.

func (*Doc) Mark

func (d *Doc) Mark(start, end int, key string, value any, expand Expand) (ID, error)

Mark applies key=value over the visible range [start, end). expand decides whether text later typed at a boundary joins the mark; it is baked into the anchor sides at creation time. The returned ID identifies the operation (higher-id operations on the same key win where ranges overlap). It fails with ErrCounterCeiling when the document has no counter left.

start == end is a COLLAPSED mark: it covers no character and Marks never reports it, but MarksAt does, and with ExpandBoth the first character typed at the position falls inside it and it becomes an ordinary span. That is the pending-format state an editor needs for "press Cmd-B, then type", and with ExpandNone the zero-width annotation that attaches a note to a position rather than a span. See collapsedAnchors.

func (*Doc) Marks

func (d *Doc) Marks() ([]Span, error)

Marks resolves every mark key over the current text: for each character and key, the covering operation with the highest id wins; nil-valued winners (removals) produce no span. Spans are maximal runs of equal value, sorted by (Start, End, Key).

A mark whose anchor references an item this document does not hold is an error rather than a guess: the two implementations would otherwise paint different ranges for the same input (Go from the start of the document, TS nothing at all). Decode validates anchors and markOpAt builds them from live items, so this only fires on a document assembled in memory from foreign parts — MergeDocs with an unrelated replica, say.

Cost is O(document + covered), not O(keys × document): the two full-order passes below are shared by every key, and each key then only touches the stretches its own operations cover. That distinction is what makes the annotation pattern (one mark key per comment — see client/src/text/annotations.ts) usable, since a document with C comments has C keys that each cover a few words. Callers re-resolve on every text change, so this runs on the render path.

func (*Doc) MarksAt

func (d *Doc) MarksAt(index int) ([]PendingMark, error)

MarksAt reports what text inserted at the visible index (0..Len) would be marked with: the active formatting for a caret, and what the next character typed there comes out as.

This is a different question from Marks, which reports what is painted on characters that already exist, and neither answers the other. A collapsed mark covers nothing and never appears in Marks, but reporting it is the whole point of this call. An ordinary mark appears in both exactly when its expand policy takes in text typed at the position — so the two agree about a caret in the middle of a bold run, and disagree at its edges, which is correct in both directions.

Winners are decided the same way as in Marks (highest id per key), and a nil-valued winner reports no entry. The result is sorted by key.

func (*Doc) MergeDocs

func (d *Doc) MergeDocs(other *Doc) error

MergeDocs merges other into d in place (d grows; other is not modified).

func (*Doc) MergeEncoded

func (d *Doc) MergeEncoded(incoming []byte, floor map[string]uint64) error

MergeEncoded merges incoming — full state or a fragment — into d in place. It is the body of Merge and MergeWithFloor with the base already decoded, for callers that keep documents live across writes rather than decoding stored bytes every time (engine/server's decoded-document cache). Callers holding only bytes should use Merge or MergeWithFloor.

floor is the field's compaction floor, nil or empty for a field that was never compacted; see MergeWithFloor for what a floor decides.

An incoming plain-string value is rejected with ErrPlainStringUnresolved.

d MUST BE DISCARDED if this returns an error. The fragment path validates before it commits, but the full-state path does not, so a failed merge can leave d holding part of the incoming side. Encoding it would persist a state no replica ever produced.

func (*Doc) ObserveVersion

func (d *Doc) ObserveVersion(vv map[string]uint64)

ObserveVersion raises d's version vector to cover vv WITHOUT importing any items, so subsequent edits allocate counters past everything vv describes.

It exists for the three-way writer: one that diffs against a stale ancestor document but will merge the result into a newer state. Editing the ancestor alone would reuse counters the newer state already spent, which is exactly the id collision the ID doc warns about — observing the newer version first is what lets such a writer keep ONE peer instead of minting a fresh one per edit. The observed peers appear in the encoded peer table; that costs nothing in practice, because the state they came from is merged in right after and carries them anyway.

func (*Doc) Peer

func (d *Doc) Peer() string

Peer returns the local writer identity ("" for a read-only decode).

func (*Doc) PlainText

func (d *Doc) PlainText() string

PlainText returns the visible text.

func (*Doc) Points

func (d *Doc) Points() ([]Point, error)

Points resolves the zero-width marks over the current text — the marks Marks cannot report, because a span covering no characters is not a span.

Both kinds of collapsed mark appear here (see collapsedAnchors): a note attached to a position, which stays zero-width for good, and a pending format that has not been typed into yet, which stops being a point the moment it covers a character. The document does not distinguish them beyond their anchors, so neither does this; callers that need to tell them apart use distinct keys, which is what the annotation pattern already does (one key per comment, see client/src/text/annotations.ts).

Winners are decided per key AND position rather than per key alone: two notes on the same key at different places in the document are both real, whereas two operations on the same key at the same position are the same collision Marks resolves — highest id wins, nil-valued winner reports nothing, which is what lets an unmark at the caret cancel a point. Sorted by (Index, Key).

func (*Doc) ResolveAnchor

func (d *Doc) ResolveAnchor(a Anchor) (int, error)

ResolveAnchor maps an anchor back to a visible index (0..Len). A live item resolves exactly; a deleted item resolves to the nearest live neighbour on the anchor's side; an unknown item is an error — reachable only for an anchor kept outside the document across a compaction that purged its item.

func (*Doc) SetPeer

func (d *Doc) SetPeer(peer string)

SetPeer sets the writer identity used for subsequent edits.

func (*Doc) SetString

func (d *Doc) SetString(s string) error

SetString rewrites the document's visible text to s. The longest common prefix and suffix are kept, and the middle is patched with a minimal multi-hunk diff (Myers, over code points), so items — and the marks and anchors attached to them — survive everywhere the text did not actually change. This is the write path for whole-value writers — connectors, the admin form and the string-valued mutation APIs — so an external edit merges with concurrent client edits instead of clobbering the document.

When the two strings are further apart than maxDiffCost, the middle is replaced as a single hunk instead; edits that large rewrite most of the text anyway, and the bound keeps the diff linear in practice.

s must be valid UTF-8. The check belongs here and not only in Insert: converting to runes below already substitutes U+FFFD for an invalid byte, so by the time a hunk reaches Insert the loss has happened and the string it is handed is well-formed.

func (*Doc) Unmark

func (d *Doc) Unmark(start, end int, key string, expand Expand) (ID, error)

Unmark removes key over the visible range [start, end): it records a mark operation with a nil value and a higher id than everything seen, which wins resolution over the marks it covers. expand mirrors Mark — pass the same policy the mark was created with so boundary inserts don't resurrect it.

It is also how a collapsed mark is cancelled: an unmark at the same caret with the same expand policy resolves to the same anchors, so it outranks the mark both while they cover nothing and after text typed at the position makes them cover it. Nothing is physically removed — Compact reclaims the pair once neither can affect resolution again (see compact.go).

func (*Doc) VersionVector

func (d *Doc) VersionVector() map[string]uint64

VersionVector returns a copy of the document's version vector: the highest counter seen from each peer.

type Expand

type Expand uint8

Expand controls whether text typed at a mark's boundary joins the mark.

const (
	// ExpandNone: boundary inserts on either side stay outside the mark.
	ExpandNone Expand = 0
	// ExpandBefore: text typed immediately before the range joins it.
	ExpandBefore Expand = 1
	// ExpandAfter: text typed immediately after the range joins it.
	ExpandAfter Expand = 2
	// ExpandBoth: text typed at either boundary joins the range.
	ExpandBoth Expand = 3
)

type Fragment

type Fragment struct {
	// contains filtered or unexported fields
}

Fragment is a decoded delta-state payload. It is inert data: nothing can be read from or edited in a fragment, it can only be applied to a full document (Doc.ApplyFragment) or unioned with another fragment (MergeFragments).

func DecodeFragment

func DecodeFragment(data []byte) (*Fragment, error)

DecodeFragment parses a fragment payload. Structural validity is enforced exactly as for full documents; only reference resolution (parents, anchors) is deferred to apply time. The version vector must cover every item and mark op the fragment carries — it claims to be the writer's full knowledge, and the merged vv depends on that.

Every failure is tagged ErrFragmentUnusable: there is nothing a receiver can do about malformed delta state except ask for the full document.

func (*Fragment) Encode

func (f *Fragment) Encode() []byte

Encode serializes the fragment canonically (same sort rules as Doc.Encode).

func (*Fragment) VersionVector

func (f *Fragment) VersionVector() map[string]uint64

VersionVector returns a copy of the fragment's version vector — the full knowledge of the document it was cut from.

type ID

type ID struct {
	// Peer identifies the writer: a leased sync client identity, or a
	// server-side writer's own name. It is stored once per document in a peer
	// table, so peers are cheap but not free.
	Peer string
	// Counter is unique per peer within a document, allocated Lamport-style
	// (past every counter seen at allocation time). Never zero: the root
	// sentinel holds zero, and Decode refuses an item or mark op that does.
	Counter uint64
}

ID is the permanent identity of an item or mark operation.

Every caller that edits a document owes this package one invariant, which it has no way to verify: TWO DOCUMENTS THAT CAN DIVERGE MUST NEVER SHARE A PEER. Counters come from the document's own version vector, so two editable copies behind one peer allocate the same id for different work. Merge rejects that when the content or the tree position disagrees, permanently breaking the field for whichever writer holds the losing state; when they happen to agree it converges on a text neither writer typed.

Reuse of a peer over TIME is fine, and is how writers avoid growing a document's peer table without bound: allocating past everything the document has seen is safe as long as every state that peer writes from already includes its own earlier writes. Concretely, a writer may keep one peer across edits when it re-reads current state before each edit and its edits are serialized (see the client's leases in client/src/text/peer.ts and the connector's per-instance peer); one that diffs against a stale ancestor, or runs concurrently with itself, needs a fresh peer per edit.

type PendingMark

type PendingMark struct {
	Key   string
	Value any
}

PendingMark is one key/value that applies at a caret position.

type Point

type Point struct {
	Index int
	Key   string
	Value any
}

Point is a resolved zero-width mark: one that covers no character, reported at the visible index it sits between.

type Span

type Span struct {
	// Start and End are visible code-point indices, [Start, End).
	Start, End int
	Key        string
	// Value is the winning mark value (never nil — nil-valued winners mean
	// "unmarked" and produce no span).
	Value any
}

Span is a resolved mark range over the visible text.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL