Skip to content

buffer 实验性 ​

实验性

本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。

go
import "github.com/tangoui/tango/ui/editor/buffer"

本页由 site/tools/apigen 从源码注释生成(按 darwin 构建标签选文件),请勿手改。

Package buffer is the immutable text model behind the code editor.

A Snapshot is a persistent rope: every edit returns a new Snapshot that shares all untouched text with the old one, so snapshots are cheap to keep (undo, background tokenizing, diffing) and safe to read from any goroutine. Offsets are UTF-8 byte offsets into the LF-normalised text; UTF16Col and ByteCol convert to the UTF-16 columns used by LSP and Monaco.

Indexing methods (Line, LineStart, LineOf, Slice) panic on out-of-range arguments, like Go slice indexing. Coordinate conversions (PosOf, OffsetOf, UTF16Col, ByteCol) clamp instead, since their inputs often come from outside (a language server, a stale cursor).

Contracts:

  • Snapshot.Version is monotonic only within one Buffer; it does not identify a document across Buffers.
  • An Anchor follows the text through edits, undo and redo of its own Buffer by Monaco's marker rule (see Buffer.Resolve). Resolve replays every edit since the anchor was made, so its cost is linear in that number; long-lived anchors (breakpoints, diagnostics, bookmarks) should be re-anchored at their resolved offset as the history grows.

Experimental: this package's API may change in any 0.x release (see docs/release.md, "API 稳定性").

变量 ​

go
var (
	ErrEditRange = errors.New("buffer: edit out of range")
	ErrEditOrder = errors.New("buffer: edits not sorted or overlapping")
	ErrSplitRune = errors.New("buffer: edit boundary splits a UTF-8 character")
)

Errors returned by Snapshot.Apply. They are wrapped with details; test with errors.Is.

类型 ​

Anchor ​

go
type Anchor struct {
	// contains filtered or unexported fields
}

Anchor is a position that follows the text through edits, undo and redo. It records an offset and the point in its Buffer's edit log where the offset was valid; Buffer.Resolve replays the later edits to find the current offset. Anchors are small values and need no registration or cleanup.

A range is two anchors, and the bias of each end expresses Monaco's TrackedRangeStickiness:

AlwaysGrowsWhenTypingAtEdges  start Left,  end Right
NeverGrowsWhenTypingAtEdges   start Right, end Left
GrowsOnlyWhenTypingBefore     start Left,  end Left
GrowsOnlyWhenTypingAfter      start Right, end Right

An anchor belongs to the Buffer that created it; resolving it against another Buffer gives meaningless results.

func (Anchor) Bias ​

go
func (a Anchor) Bias() Bias

Bias returns the anchor's bias.

Bias ​

go
type Bias int

Bias says which way an Anchor moves when text is inserted exactly at it.

go
const (
	// Left keeps the anchor before text inserted at its offset (it sticks
	// to the character on its left).
	Left Bias = iota
	// Right moves the anchor after text inserted at its offset (it sticks
	// to the character on its right).
	Right
)

func (Bias) String ​

go
func (b Bias) String() string

Buffer ​

go
type Buffer struct {
	// Now is the clock used to group typing into undo steps. It defaults to
	// time.Now; tests inject a fake clock.
	Now func() time.Time
	// contains filtered or unexported fields
}

Buffer is the mutable handle on a document: it owns the current Snapshot, the undo/redo history and the edit log used to resolve Anchors.

A Buffer is not safe for concurrent use; drive it from one goroutine (the UI thread). The Snapshots it hands out are immutable and may be passed to any goroutine.

func New ​

go
func New(text string) *Buffer

New returns a Buffer holding text as version 1 (see NewSnapshot).

func (*Buffer) AltVersion ​

go
func (b *Buffer) AltVersion() uint64

AltVersion returns Monaco's alternativeVersionId: it equals Snapshot().Version() after an edit, but undo and redo set it back to the value the restored state had, so "is the document back to its saved state" is a simple comparison even though Version keeps increasing.

func (*Buffer) Anchor ​

go
func (b *Buffer) Anchor(off int, bias Bias) Anchor

Anchor returns an anchor at byte offset off of the current snapshot, clamped to [0, Len()].

func (*Buffer) Edit ​

go
func (b *Buffer) Edit(edits []Edit, cursorsBefore, cursorsAfter []Selection) (Snapshot, error)

Edit applies edits (as Snapshot.Apply) and records them for undo. cursorsBefore and cursorsAfter are the selections before and after the edit; Undo and Redo hand them back. Both slices are copied.

Grouping into undo steps:

  • PushUndoStop always ends the current step. Edits made between two PushUndoStop calls form a single step regardless of timing.
  • Without an explicit stop, an edit merges into the previous step when it comes within 300 ms of the previous edit (by b.Now) and cursorsBefore equals the previous cursorsAfter (and is not empty), i.e. continuous typing.

On error, or when edits change nothing, the buffer is left unchanged and the current snapshot is returned.

func (*Buffer) LastChange ​

go
func (b *Buffer) LastChange() (old Snapshot, edits []Edit)

LastChange describes the most recent successful Edit, Undo or Redo: old is the snapshot it started from, and edits (sorted, non-overlapping, in old's coordinates, with EOL-normalised text) turn old into the current snapshot, i.e. old.Apply(edits) has the current text. It is what an incremental consumer such as a highlighter needs after Undo and Redo, which return only the resulting snapshot. The edits of a multi-edit undo step are composed into one batch: nearby or overlapping edits merge, edits far apart stay separate. Composition is linear in the step's spans per span (quadratic in the worst case), which is fine for typing-sized steps; a single-batch step (the usual replace-all) is passed through as is.

Before any change it returns the current snapshot and no edits. Edits that cancel out within a step (typing then deleting a character) yield no edit.

func (*Buffer) PushUndoStop ​

go
func (b *Buffer) PushUndoStop()

PushUndoStop ends the current undo step: the next edit starts a new one, which then collects every edit until the next PushUndoStop.

func (*Buffer) Redo ​

go
func (b *Buffer) Redo() (Snapshot, []Selection, bool)

Redo re-applies the most recently undone step, returning the new snapshot, the selections from after the step, and false when there is nothing to redo.

func (*Buffer) Resolve ​

go
func (b *Buffer) Resolve(a Anchor) int

Resolve returns a's offset in the current snapshot. Each edit since the anchor was made moves it by Monaco's rule for decoration markers (intervalTree.ts nodeAcceptEdit, without forceMoveMarkers). For an edit replacing bytes [start, start+del) with ins bytes and an anchor at off:

  • off < start: unchanged;
  • off == start: a replace or delete (del > 0) keeps it at start; a pure insertion keeps a Left anchor and moves a Right one after the text;
  • inside the replaced range, offsets in the overlapping prefix off < start+min(del, ins) keep their offset; at off == start+min(del, ins) the anchor stays when the range shrinks (del > ins), otherwise Left stays and Right moves on;
  • any other offset up to and including the end of the range moves to start+ins (the end of the new text);
  • off > start+del: shifted by ins-del.

So a whole-document replace (LSP formatting, reload from disk) keeps anchors at their offsets, clamped to the new length, rather than collapsing them to 0. Offsets are bytes where Monaco counts UTF-16 units; a kept offset that falls inside a multi-byte character of the new text is snapped to the character's start (Left) or end (Right).

The cost is linear in the number of edits since the anchor was made; to keep a long-lived anchor cheap, re-anchor it at the resolved offset (for example whenever the history has grown by many edits).

func (*Buffer) SetEOL ​

go
func (b *Buffer) SetEOL(eol string, cursors []Selection) (Snapshot, bool)

SetEOL changes the document's line ending to eol ("\n" or "\r\n") as an undo step of its own; the text (always stored LF-normalised) does not change, only EOL and TextWithEOL do. cursors are recorded as the selections before and after the step. It returns the new snapshot and false when eol is invalid or already the document's line ending (nothing changes then). LastChange afterwards reports no edits.

func (*Buffer) Snapshot ​

go
func (b *Buffer) Snapshot() Snapshot

Snapshot returns the current version of the document.

func (*Buffer) Undo ​

go
func (b *Buffer) Undo() (Snapshot, []Selection, bool)

Undo reverts the most recent undo step and ends the current step, so the next edit starts a new one. It returns the new snapshot (with a new, higher Version but the text of the state before the step), the selections from before the step, and false when there is nothing to undo.

Edit ​

go
type Edit struct {
	Start, End int
	Text       string
}

Edit replaces bytes [Start, End) of a snapshot with Text.

Pos ​

go
type Pos struct{ Line, Col int }

Pos is a zero-based line/column position. Col counts UTF-8 bytes from the start of the line; use UTF16Col/ByteCol to convert to and from the UTF-16 columns used by LSP and Monaco.

Selection ​

go
type Selection struct{ Anchor, Head int }

Selection is a selection or caret as byte offsets: Anchor is where it started, Head is where the caret is. A caret has Anchor == Head.

Snapshot ​

go
type Snapshot struct {
	// contains filtered or unexported fields
}

Snapshot is an immutable version of a document. It is a small value type; copying it is free and it may be shared across goroutines. The zero value is an empty document.

func NewSnapshot ​

go
func NewSnapshot(text string) Snapshot

NewSnapshot loads text as version 1 of a document. Like Monaco, "\r\n", a lone "\r" and "\n" are all line breaks, and the internal text stores each of them as "\n". The document's EOL is "\r\n" when CRLF breaks outnumber the other two kinds combined, otherwise "\n".

func (Snapshot) Apply ​

go
func (s Snapshot) Apply(edits []Edit) (Snapshot, error)

Apply returns a new snapshot with edits applied. Offsets refer to s; edits must be sorted by Start and must not overlap (an edit may start where the previous one ends, so several inserts at one offset apply in order). Every boundary must fall on a UTF-8 character boundary. On error s is returned unchanged.

Inserted text is normalised like NewSnapshot: "\r\n" and lone "\r" become "\n", so the inserted length can be shorter than len(Edit.Text). Offsets of all edits in one call still refer to s, so this never shifts the other edits; callers placing a cursor after an edit should measure the normalised text (or use the new snapshot) rather than len(Edit.Text).

func (Snapshot) ByteCol ​

go
func (s Snapshot) ByteCol(line, utf16Col int) int

ByteCol converts UTF-16 column utf16Col on line to a byte column. Columns past the end clamp to the line length; a column that falls between the two halves of a surrogate pair snaps back to the start of that character.

func (Snapshot) EOL ​

go
func (s Snapshot) EOL() string

EOL returns the document's line ending, "\n" or "\r\n".

func (Snapshot) Len ​

go
func (s Snapshot) Len() int

Len returns the length in bytes of the LF-normalised text.

func (Snapshot) Line ​

go
func (s Snapshot) Line(i int) string

Line returns line i without its line break. It panics if i is out of range.

func (Snapshot) LineCount ​

go
func (s Snapshot) LineCount() int

LineCount returns the number of lines; it is the number of '\n' plus one, so empty text has one line and text ending in '\n' ends with an empty line.

func (Snapshot) LineOf ​

go
func (s Snapshot) LineOf(off int) int

LineOf returns the line containing byte offset off; off == Len() is on the last line. It panics if off is outside [0, Len()].

func (Snapshot) LineStart ​

go
func (s Snapshot) LineStart(i int) int

LineStart returns the byte offset of the first byte of line i (0-based). It panics if i is out of range.

func (Snapshot) OffsetOf ​

go
func (s Snapshot) OffsetOf(p Pos) int

OffsetOf returns the byte offset of p. The line is clamped to [0, LineCount()-1] and the column to [0, line length], so stale positions (for example from a language server) still map into the document. A column that falls inside a multi-byte character snaps back to the start of that character, so the result is always a valid edit boundary.

func (Snapshot) PosOf ​

go
func (s Snapshot) PosOf(off int) Pos

PosOf returns the position of byte offset off. Out-of-range offsets are clamped to [0, Len()].

func (Snapshot) Slice ​

go
func (s Snapshot) Slice(start, end int) string

Slice returns bytes [start, end) of the LF-normalised text. It panics if the range is invalid.

func (Snapshot) String ​

go
func (s Snapshot) String() string

String returns the whole LF-normalised text.

func (Snapshot) TextWithEOL ​

go
func (s Snapshot) TextWithEOL() string

TextWithEOL returns the whole text with every line break written as EOL(), i.e. the form to save back to disk.

func (Snapshot) UTF16Col ​

go
func (s Snapshot) UTF16Col(line, byteCol int) int

UTF16Col converts byte column byteCol on line to a UTF-16 code-unit column. byteCol is clamped to the line; a column inside a multi-byte character counts only the characters that end at or before it. Invalid UTF-8 bytes count as one unit each.

func (Snapshot) Version ​

go
func (s Snapshot) Version() uint64

Version returns the snapshot's version: 1 for NewSnapshot, and one more than its parent for each successful Apply. Versions count edits along one history; two snapshots derived from the same parent share a version.

Version is monotonic only within one Buffer (whose undo/redo also produce new, higher versions). It is not a document identity: snapshots of different Buffers, or of two Applys on the same parent, can have equal versions with different text, so do not compare versions across Buffers.

Tracker ​

go
type Tracker struct {
	// contains filtered or unexported fields
}

Tracker maps offsets through one set of edits by the rule Resolve uses (Monaco's tracked ranges, nodeAcceptEdit), without a Buffer: an editor command computes where its selections land before it applies the edits (the selections after an edit are recorded with it for redo). The edits are as Snapshot.Apply takes them: sorted, non-overlapping, in the coordinates of the text they apply to.

Map costs O(log n) plus the edits touching the offset, so mapping the selections of many cursors through the edits of many cursors stays O((cursors + edits) log edits).

func NewTracker ​

go
func NewTracker(edits []Edit) *Tracker

NewTracker returns a Tracker for edits (no-op edits are ignored; inserted lengths are measured after EOL normalisation, as Apply stores them).

func (*Tracker) Map ​

go
func (t *Tracker) Map(off int, bias Bias) int

Map returns where off, an offset in the text before the edits, lands in the text after them: an anchor of the given bias resolved through the edits (see Resolve; it is not clamped or snapped to a character).

以 MIT 许可发布