lspedit

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package lspedit turns language-server edit descriptions into text and filesystem changes that either fully apply or not at all.

Three layers, bottom to top:

  • Text layer (this file): Position / Range / TextEdit plus ApplyEdits, which resolves LSP UTF-16 coordinates to byte offsets, rejects invalid or overlapping ranges, and applies every edit against the ORIGINAL text so a list of server edits cannot drift.
  • Completion layer (this file): ResolveCompletion turns one completion item into the edits that accepting it performs — the server's textEdit when present, otherwise a plain insertion over the identifier prefix at the caret — carrying additionalTextEdits (the auto-import lines) along instead of dropping them, and handing snippet bodies back as a template for a snippet engine rather than inserting "${1:x}" literally.
  • Transaction layer (workspace.go, preview.go): a Transaction collects per-file edits and resource operations, preflights all of them, computes the resulting content in memory, and only then writes — restoring the already-written files when a later write fails.

The package deliberately defines its own wire-free structs and imports no other silk package: the host adapts its LSP client types at the boundary, and everything here stays unit-testable without a language server.

Coordinates follow LSP: zero-based lines, and Character is a UTF-16 code unit offset within the line (not a byte and not a rune index). Unlike a lenient applier, a position outside the document is an error instead of being clamped to the nearest valid offset — a transaction that cannot be resolved exactly must not be applied at all.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidRange is a position or range that does not resolve against the
	// document: line out of bounds, character past end of line, character
	// splitting a surrogate pair, or an inverted range.
	ErrInvalidRange = errors.New("lspedit: invalid range")
	// ErrOverlap is two edits of the same document whose byte spans intersect.
	// LSP forbids it; applying them anyway silently corrupts the file.
	ErrOverlap = errors.New("lspedit: overlapping edits")
	// ErrStaleVersion is an edit computed against a document version that is
	// no longer current.
	ErrStaleVersion = errors.New("lspedit: stale document version")
	// ErrNotFound is an edit or resource operation on a path that does not
	// exist.
	ErrNotFound = errors.New("lspedit: file not found")
	// ErrExists is a create/rename whose destination is already there and that
	// did not ask to overwrite.
	ErrExists = errors.New("lspedit: file already exists")
	// ErrBadPath is an empty path, a non-regular file, or a missing parent
	// directory.
	ErrBadPath = errors.New("lspedit: invalid path")
	// ErrEmptyItem is a completion item carrying neither label, insertText nor
	// textEdit — there is nothing to insert.
	ErrEmptyItem = errors.New("lspedit: completion item has no text")
)

Sentinel errors. Every error this package returns wraps one of these (or an *ApplyError / os error), so callers can classify with errors.Is instead of matching strings.

Functions

func ApplyEdits

func ApplyEdits(text string, edits []TextEdit) (string, error)

ApplyEdits applies edits to text and returns the result.

All coordinates are interpreted against the ORIGINAL text — the edits are resolved to byte spans first and applied in one pass, so their order in the slice does not matter and earlier edits cannot shift later ones. Overlapping spans, inverted ranges and out-of-document positions are errors: no partial text is ever returned. edits is not modified.

func ValidateEdits

func ValidateEdits(text string, edits []TextEdit) error

ValidateEdits reports whether edits resolve cleanly against text, without building the result. Used by the transaction preflight to fail before anything is computed or written.

Types

type Action

type Action int

Action is what a transaction does to one file.

const (
	ActionModify Action = iota
	ActionCreate
	ActionDelete
)

The actions a previewed file can carry.

func (Action) Marker

func (a Action) Marker() string

Marker is the single-letter form used in compact listings: M, A or D.

func (Action) String

func (a Action) String() string

String implements fmt.Stringer.

type Application

type Application struct {
	// Primary is the main edit: the range the completion replaces and the text
	// replacing it.
	//
	// When Snippet is true, Primary.NewText is the raw snippet template with
	// its tab stops intact (the same string as SnippetBody). A caller with a
	// snippet engine expands SnippetBody into Primary.Range; a caller without
	// one may insert Primary.NewText verbatim.
	Primary TextEdit
	// Additional carries the item's additionalTextEdits unchanged. Their
	// coordinates refer to the original buffer, which is why they must be
	// applied together with Primary and never one after the other.
	Additional []TextEdit
	// Snippet reports that Primary.NewText is a template, not literal text.
	Snippet bool
	// SnippetBody is the template handed to the snippet engine. Empty unless
	// Snippet.
	SnippetBody string
}

Application is the resolved effect of accepting a CompletionItem: every edit to make, all resolved against the same original buffer.

func ResolveCompletion

func ResolveCompletion(text string, cursor Position, item CompletionItem) (Application, error)

ResolveCompletion computes what accepting item does to text with the caret at cursor.

Precedence, in order:

  1. item.TextEdit — the server said exactly which range to replace, so it wins unconditionally and InsertText/Label are ignored (LSP requires this, and gopls relies on it for prefix-aware replacements).
  2. item.InsertText — inserted over the identifier prefix immediately left of the caret, so typing "fmt.Pr" and accepting "Println" yields "fmt.Println" rather than "fmt.PrPrintln".
  3. item.Label — used when InsertText is empty.

item.AdditionalTextEdits are carried into the result and validated together with the primary edit; an additional edit that overlaps the primary one is rejected instead of silently corrupting the buffer. Every range is resolved against text as given — nothing is written and text is not modified.

func (Application) Apply

func (a Application) Apply(text string) (string, error)

Apply returns text with every edit of the application applied at once.

For a snippet item this inserts the template verbatim; hosts that support tab stops expand SnippetBody instead of calling this.

func (Application) Edits

func (a Application) Edits() []TextEdit

Edits returns the primary edit followed by the additional ones, ready for ApplyEdits or for a FileEdit in a Transaction. The result is a fresh slice.

type ApplyError

type ApplyError struct {
	Path         string
	Err          error
	RollbackErrs []error
}

ApplyError reports a failed Apply. Err is the underlying filesystem error and Path the file it happened on. RollbackErrs is empty when every already touched file was restored, so an ApplyError with no RollbackErrs means the working tree is exactly as it was before Apply.

func (*ApplyError) Error

func (e *ApplyError) Error() string

Error implements error.

func (*ApplyError) Unwrap

func (e *ApplyError) Unwrap() error

Unwrap exposes the filesystem error to errors.Is / errors.As.

type CompletionItem

type CompletionItem struct {
	Label               string
	InsertText          string
	TextEdit            *TextEdit  // wins over InsertText/Label when non-nil
	AdditionalTextEdits []TextEdit // e.g. the auto-import edit; same original coordinates
	IsSnippet           bool       // NewText is a snippet template, not literal text
}

CompletionItem is the provider-agnostic subset of an LSP CompletionItem that decides what accepting the item does to the buffer.

The fields that matter and that a label/insert-only conversion throws away: TextEdit (the server's own replace range, which knows how much of the typed prefix to consume), AdditionalTextEdits (the import line gopls adds elsewhere in the file so the completed symbol resolves), and IsSnippet (whether NewText is a template with tab stops).

type FileEdit

type FileEdit struct {
	Path    string
	Edits   []TextEdit
	Version int
}

FileEdit is the edit list for one file.

Version guards against applying edits computed from a document the user has since changed: when it is positive, the transaction asks its version source (SetVersions) for the file's current version and refuses to apply unless the two match. Zero or negative means unversioned.

type FilePreview

type FilePreview struct {
	Path   string
	Action Action
	Before string
	After  string
}

FilePreview is one file's before/after text. Before is empty for a created file and After is empty for a deleted one.

func (FilePreview) LineDelta

func (f FilePreview) LineDelta() int

LineDelta is the change in line count the file undergoes, useful for a summary column without diffing the text.

type OpKind

type OpKind int

OpKind is the kind of a resource operation.

const (
	OpCreate OpKind = iota + 1
	OpRename
	OpDelete
)

Resource operation kinds, mirroring the LSP create/rename/delete file operations.

func (OpKind) String

func (k OpKind) String() string

String implements fmt.Stringer.

type Plan

type Plan struct {
	Label string
	Files []PlannedFile
}

Plan is the result of a preflight: every file the transaction changes, in the order the steps first touched them. Files whose content ends up identical to what is on disk are left out — the plan holds real changes only. Holding a Plan means nothing has been written yet.

type PlannedFile

type PlannedFile struct {
	Path    string // absolute, cleaned
	Before  string // content on disk before the transaction; empty when !Existed
	After   string // content to write; empty when Deleted
	Existed bool   // the path was a regular file on disk before the transaction
	Deleted bool   // the transaction removes the path
	Mode    fs.FileMode
}

PlannedFile is one file's fully resolved before/after state.

func (PlannedFile) Created

func (p PlannedFile) Created() bool

Created reports that the transaction brings this path into existence.

type Position

type Position struct {
	Line      int
	Character int
}

Position is a zero-based LSP text position. Character counts UTF-16 code units from the start of the line, so an emoji before it advances Character by 2 while advancing the byte offset by 4.

type Preview

type Preview struct {
	Label string
	Files []FilePreview
}

Preview is the full set of changes a transaction would make.

func (Preview) Empty

func (p Preview) Empty() bool

Empty reports that the transaction changes nothing.

func (Preview) Paths

func (p Preview) Paths() []string

Paths lists the affected files in plan order.

func (Preview) String

func (p Preview) String() string

String renders a compact `M path` / `A path` / `D path` listing under the transaction label — enough for a confirmation dialog or a log line.

type Range

type Range struct {
	Start Position
	End   Position
}

Range is the half-open LSP interval [Start, End). Start == End is an insertion point.

type ResourceOp

type ResourceOp struct {
	Kind    OpKind
	Path    string
	NewPath string
	Content string // create: the initial content
	// Overwrite allows a create or rename to replace an existing destination.
	Overwrite bool
	// IgnoreIfExists skips a create whose destination is already there
	// (checked before Overwrite).
	IgnoreIfExists bool
	// IgnoreIfNotExists skips a rename or delete whose source is missing
	// instead of failing the transaction.
	IgnoreIfNotExists bool
}

ResourceOp creates, renames or deletes a file as part of the transaction.

Path is the target for create and delete and the source for rename; NewPath is the rename destination. A rename is planned as a delete of Path plus a create of NewPath carrying its content, so it participates in the same all-or-nothing write as the text edits. Directories are not operated on: the parent directory of a created or renamed-to path must already exist.

type Result

type Result struct {
	Label   string
	Written []string
	Deleted []string
}

Result reports what a successful Apply did.

type TextEdit

type TextEdit struct {
	Range   Range
	NewText string
}

TextEdit replaces Range with NewText. An empty Range inserts; an empty NewText deletes.

type Transaction

type Transaction struct {
	// Label names the change for previews and error messages, e.g.
	// `rename "Foo" to "Bar"`.
	Label string
	// contains filtered or unexported fields
}

Transaction is an ordered set of file edits and resource operations applied as a unit. Build it with NewTransaction, add steps, then Preview or Apply. A Transaction is not safe for concurrent use.

func NewTransaction

func NewTransaction(label string) *Transaction

NewTransaction returns an empty transaction labelled label.

func (*Transaction) AddEdit

func (t *Transaction) AddEdit(fe FileEdit)

AddEdit appends an edit step.

func (*Transaction) AddOp

func (t *Transaction) AddOp(op ResourceOp)

AddOp appends a resource operation step.

func (*Transaction) Apply

func (t *Transaction) Apply() (Result, error)

Apply preflights the transaction and then writes it. Either every planned file ends up in its new state, or — when a write or removal fails — every file already touched is restored and an *ApplyError is returned. A preflight failure returns before any write, so the error is the preflight one.

func (*Transaction) Preflight

func (t *Transaction) Preflight() (*Plan, error)

Preflight validates every step and computes the resulting content of every file, without writing anything. The returned error wraps one of the package sentinels (ErrNotFound, ErrStaleVersion, ErrInvalidRange, ErrOverlap, ErrExists, ErrBadPath) and names the offending path.

func (*Transaction) Preview

func (t *Transaction) Preview() (Preview, error)

Preview preflights the transaction and returns the resulting per-file before/after text. It touches no file: a preflight failure is reported as an error exactly as Apply would report it, so a host can validate and show a change in one step and only then decide to write.

func (*Transaction) SetVersions

func (t *Transaction) SetVersions(fn func(path string) (version int, ok bool))

SetVersions installs the document version source consulted for every FileEdit with a positive Version. fn receives the path exactly as it was given in the FileEdit and reports the current version plus whether the document is known at all. Without it, a versioned FileEdit fails preflight.

func (*Transaction) Steps

func (t *Transaction) Steps() int

Steps is the number of steps added so far.

Jump to

Keyboard shortcuts

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