import { Option } from "effect"; import { splitsCrlf, splitsPair } from "./internal/codeUnits.js"; import type { LspPosition, LspPositionEncoding } from "./LspPositionIndex.js"; import { LspPositionIndex } from "./LspPositionIndex.js"; /** * A range in a text document, `end` exclusive: an LSP `Range`. * * @public */ export interface LspRange { /** The range's first position. */ readonly start: LspPosition; /** The position just past the range. */ readonly end: LspPosition; } /** * A replacement of one range of a document: an LSP `TextEdit`. An empty * `range` is an insertion and an empty `newText` a deletion. * * @public */ export interface LspTextEdit { /** The range of the document, as it was before the edit, that `newText` replaces. */ readonly range: LspRange; /** The text that replaces `range`. */ readonly newText: string; } /** * The edits to one text document at one version: an LSP `TextDocumentEdit` * whose `textDocument` is an `OptionalVersionedTextDocumentIdentifier`. * * @remarks * `edits` is a mutable array, as the specification's TypeScript declarations * (and `vscode-languageserver-types`) type it, so the value is assignable * where a server library expects its own `TextDocumentEdit`. * * @public */ export interface LspTextDocumentEdit { /** The document, and the version of it the edits were computed against. */ readonly textDocument: { /** The document's URI. */ readonly uri: string; /** * The version the edits were computed against, so a client whose buffer has moved on refuses * them; `null` for a document that is not open in the client. */ readonly version: number | null; }; /** The edits, every range over the document at `version`; they must not overlap. */ readonly edits: Array; } /** * A change to the workspace carried as `documentChanges`: an LSP * `WorkspaceEdit`, as a `workspace/applyEdit` request or a code action * sends it. * * @remarks * `documentChanges` is a mutable array for the reason * {@link LspTextDocumentEdit} gives. * * @public */ export interface LspWorkspaceEdit { /** One entry per document; {@link LspEdit.workspace} builds exactly one. */ readonly documentChanges: Array; } /** * Options for {@link LspEdit.replacement}. * * @public */ export interface LspEditOptions { /** The unit the edit's `character` offsets count. Defaults to `"utf-16"`. */ readonly encoding?: LspPositionEncoding; } /** * Whether a split of `text` at UTF-16 offset `offset` would cut a unit an * LSP position cannot address: a surrogate pair, or a `\r\n` line ending. */ const splitsUnit = (text: string, offset: number): boolean => splitsPair(text, offset) || splitsCrlf(text, offset); /** * Build LSP text edits from a document's text, without a server framework. * * @remarks * Pure: every function computes a plain value a server sends as it is, with * no IO and no `Effect`. * * {@link LspEdit.replacement} answers the one minimal edit between two * versions of a document: the range from the first to the last code unit * that differs, after the longest common prefix and then the longest common * suffix that does not overlap it are trimmed. Either end is widened rather * than split where a split would cut something an LSP position cannot * address: a surrogate pair (a `character` cannot point between its halves * under `"utf-8"` or `"utf-32"`, and a client applying the edit under * `"utf-16"` would leave a lone surrogate behind) or a `\r\n` line ending, * which the specification makes one line break with no position inside it. * A leading byte-order mark both texts share sits in the common prefix, so * the edit never covers it: an editor buffer that keeps its BOM never loses * or doubles it. * * Positions are over `before` as given, BOM included: a buffer that holds a * BOM counts it as the first character of line 0, as the client's own copy * of that buffer does. * * @example * ```typescript * import { Option } from "effect"; * import { LspEdit } from "@effected/lsp"; * * const before = "one\r\ntwo\r\n"; * const edit = LspEdit.replacement(before, "one\r\n2\r\n"); * console.log(Option.getOrThrow(edit)); * // => { range: { start: { line: 1, character: 0 }, end: { line: 1, character: 3 } }, newText: "2" } * const change = LspEdit.workspace("file:///a.md", 7, Option.toArray(edit)); * console.log(change.documentChanges[0]?.textDocument); * // => { uri: "file:///a.md", version: 7 } * ``` * * @public */ export class LspEdit { private constructor() {} /** * The one minimal `TextEdit` that turns `before` into `after`, or * `Option.none()` when the two are identical. * * @remarks * The range never splits a surrogate pair or a `\r\n`, and never covers * a BOM both texts share (see the class remarks). Applying the edit to * `before` under the same `encoding` gives `after` exactly. Identical * texts answer `Option.none()` rather than an empty edit at `0:0`, so a * caller offers no quick fix and sends no `workspace/applyEdit` that * would change nothing. * * @param before - The document's text as the client holds it now. * @param after - The text it should become. * @param options - The negotiated position encoding; defaults to `"utf-16"`. * @returns The edit, its range over `before`, or `Option.none()`. */ static replacement(before: string, after: string, options?: LspEditOptions): Option.Option { if (before === after) return Option.none(); const encoding = options?.encoding ?? "utf-16"; const limit = Math.min(before.length, after.length); let prefix = 0; while (prefix < limit && before.charCodeAt(prefix) === after.charCodeAt(prefix)) prefix++; // A split is checked in both texts: the shared unit before it is the same in each, but the unit after // it is not, and a split in `after` alone would leave a stray half (or a bare `\n`) in `newText`. One // step back settles it, since a pair and a `\r\n` share no code unit. The prefix settles before the // suffix is scanned, so a unit the prefix gave back can still join the suffix. if (splitsUnit(before, prefix) || splitsUnit(after, prefix)) prefix--; let suffix = 0; while ( suffix < limit - prefix && before.charCodeAt(before.length - 1 - suffix) === after.charCodeAt(after.length - 1 - suffix) ) { suffix++; } if (splitsUnit(before, before.length - suffix) || splitsUnit(after, after.length - suffix)) suffix--; const index = LspPositionIndex.make(before, encoding); return Option.some({ range: { start: index.positionAt(prefix), end: index.positionAt(before.length - suffix) }, newText: after.slice(prefix, after.length - suffix), }); } /** * `edits` as a `WorkspaceEdit` over the one document at `uri`, carried as * a single `documentChanges` entry versioned with `version`. * * @remarks * A versioned edit is the safe form for `workspace/applyEdit`: a client * whose buffer has changed since `version` refuses it instead of applying * it at stale positions. Pass `null` for a document that is not open. The * client must have advertised `workspace.workspaceEdit.documentChanges`. * `edits` is copied, never retained. * * @param uri - The document's URI, e.g. a `textDocument.uri`. * @param version - The document version the edits were computed against, or `null`. * @param edits - The edits, every range over that version; they must not overlap. * @returns The `WorkspaceEdit`. */ static workspace(uri: string, version: number | null, edits: ReadonlyArray): LspWorkspaceEdit { return { documentChanges: [{ textDocument: { uri, version }, edits: [...edits] }] }; } }