diff --git a/src/editor/lsp/completion.test.ts b/src/editor/lsp/completion.test.ts index 72705c2f9..ff84d109e 100644 --- a/src/editor/lsp/completion.test.ts +++ b/src/editor/lsp/completion.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { EditorState, StateEffect, type Extension } from "@codemirror/state"; +import { EditorSelection, EditorState, StateEffect, type Extension } from "@codemirror/state"; import { EditorView, runScopeHandlers } from "@codemirror/view"; import type { CompletionItem } from "@/bindings"; import { remoteChange, type EditorDocContext } from "@/editor/api"; @@ -321,6 +321,53 @@ describe("applying completions", () => { } }); + it("completes at every caret whose typed prefix matches the main caret's", () => { + const { view, req } = setup("a.cr|\nb.cr\nc.xy", "", [EditorState.allowMultipleSelections.of(true)]); + // Carets after both `cr`s (the main one first) and after `xy`. + view.dispatch({ + selection: EditorSelection.create( + [EditorSelection.cursor(4), EditorSelection.cursor(9), EditorSelection.cursor(14)], + 0, + ), + }); + applyLspCompletion(view, makeCompletion(item({ insertText: "create", kind: "property" }), req), 2, 4, "insert"); + expect(view.state.doc.toString()).toBe("a.create\nb.create\nc.xy"); + expect(view.state.selection.ranges.map((r) => r.head)).toEqual([8, 17]); + expect(view.state.selection.main.head).toBe(8); + }); + + it("inserts a snippet at several carets as text, each caret at its first stop", () => { + const { view, req } = setup("x = ma|\ny = ma", "", [EditorState.allowMultipleSelections.of(true)]); + view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(6), EditorSelection.cursor(13)], 0) }); + const snippet = item({ label: "max", kind: "function", insertText: "max(${1:a}, ${2:b})", isSnippet: true }); + applyLspCompletion(view, makeCompletion(snippet, req), 4, 6, "insert"); + expect(view.state.doc.toString()).toBe("x = max(a, b)\ny = max(a, b)"); + expect(view.state.selection.ranges.map((r) => r.head)).toEqual([8, 22]); + expect(view.state.selection.mainIndex).toBe(0); + }); + + it("repeats an item its server inserts at the other carets when the edit lands", async () => { + setInvokeRoute(() => Promise.resolve(null)); + try { + const { view, req } = setup("p.ref|\nq.ref\n", "", [ + completionExtension(), + EditorState.allowMultipleSelections.of(true), + ]); + view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) }); + view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(5), EditorSelection.cursor(11)], 0) }); + const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] }; + const kotlin = item({ label: "refreshName", labelDetail: "()", insertText: "", command }); + applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert"); + expect(view.state.selection.ranges).toHaveLength(2); + view.dispatch({ changes: { from: 5, insert: "reshName()" }, annotations: remoteChange.of(true) }); + expect(view.state.doc.toString()).toBe("p.refreshName()\nq.refreshName()\n"); + expect(view.state.selection.ranges.map((r) => r.head)).toEqual([15, 31]); + expect(view.state.selection.main.head).toBe(15); + } finally { + setInvokeRoute(null); + } + }); + it("does not register a scope when jumping outside closing brackets is off", () => { const { view, req } = setup("service.cr|"); applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert"); diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts index 496ccb6e7..4abd46a32 100644 --- a/src/editor/lsp/completion.ts +++ b/src/editor/lsp/completion.ts @@ -24,7 +24,7 @@ import { type CompletionResult, type CompletionSource, } from "@codemirror/autocomplete"; -import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state"; +import { ChangeSet, EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state"; import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view"; import { call, @@ -44,7 +44,7 @@ import { typeColumnText, withoutDuplicates, } from "./completionItems"; -import { lspSnippetToCm, snippetVariables } from "./snippet"; +import { lspSnippetToCm, lspSnippetToPlainWithCaret, snippetVariables } from "./snippet"; import { docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp"; import { offsetToPos, posToOffset, textEditsToChanges } from "./positions"; import { isEmptyMarkup, renderCode, renderMarkup } from "./markdown"; @@ -268,6 +268,13 @@ export function applyLspCompletion( .map((c) => ({ from: mapOld(c.from), to: mapOld(c.to), insert: c.insert })) .filter((c) => c.to <= start || c.from >= end); + if (applyAtCarets(view, completion, item, start, end, extra)) { + if (item === completion.lsp && !item.additionalEdits.length && item.data != null) + void applyLateEdits(view, completion, start); + runCommand(view, item); + return; + } + let insertedParens: ReturnType = null; let bareCall: number | null = null; if (item.isSnippet) { @@ -319,6 +326,70 @@ export function applyLspCompletion( runCommand(view, item); } +/** + * With several carets, the item goes in at each caret whose text around it matches the main + * caret's (the typed prefix, and what a replacing edit overwrites), as IDEA completes at all + * carets. Snippets go in as plain text with the caret at their first stop, since fields cannot + * be edited at several places at once. False with a single caret, or no other caret matches. + */ +function applyAtCarets( + view: EditorView, + completion: LspCompletion, + item: CompletionItem, + start: number, + end: number, + extra: { from: number; to: number; insert: string }[], +): boolean { + const state = view.state; + const { ranges, mainIndex } = state.selection; + if (ranges.length < 2) return false; + // The server inserts the item at the main caret; `caretAfterServerInsert` repeats it at the others. + if (serverInserts(item)) return true; + const head = state.selection.main.head; + if (head < start || head > end) return false; + const prefix = state.sliceDoc(start, head); + const suffix = state.sliceDoc(head, end); + const sites: { from: number; to: number; main: boolean }[] = []; + ranges.forEach((r, i) => { + if (i === mainIndex) return sites.push({ from: start, to: end, main: true }); + if (!r.empty) return; + const from = r.head - prefix.length; + const to = r.head + suffix.length; + if (from < 0 || to > state.doc.length) return; + if (state.sliceDoc(from, r.head) !== prefix || state.sliceDoc(r.head, to) !== suffix) return; + sites.push({ from, to, main: false }); + }); + if (sites.length < 2) return false; + sites.sort((a, b) => a.from - b.from); + for (let i = 1; i < sites.length; i++) if (sites[i]!.from < sites[i - 1]!.to) return false; + if (extra.some((c) => sites.some((site) => c.from < site.to && c.to > site.from))) return false; + + let text: string; + let caret: number; + if (item.isSnippet) { + ({ text, caret } = lspSnippetToPlainWithCaret(item.insertText, snippetVariables(completion.req.path))); + } else { + const parens = editorPrefs().completion.insertParentheses + ? callParens(item, state.doc.lineAt(start), start, end) + : null; + text = item.insertText + (parens ? "()" : ""); + caret = text.length - (parens === "inside" ? 1 : 0); + } + const changes = state.changes([...extra, ...sites.map((site) => ({ from: site.from, to: site.to, insert: text }))]); + const cursors = sites.map((site) => EditorSelection.cursor(changes.mapPos(site.from, -1) + caret)); + view.dispatch({ + changes, + selection: EditorSelection.create( + cursors, + sites.findIndex((site) => site.main), + ), + userEvent: "input.complete", + annotations: pickedCompletion.of(completion), + scrollIntoView: true, + }); + return true; +} + const CALLABLE = new Set(["function", "method", "constructor"]); /** Lines where a callable is named, not called (imports, `use` paths). */ const IMPORT_LINE = /^\s*(import|from|use|pub\s+use|export\s+\{|#include|require)\b/; @@ -382,22 +453,62 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => { const at = tr.startState.field(serverInsertAt, false); const caret = tr.startState.selection.main; if (at == null || !tr.docChanged || !tr.annotation(remoteChange) || !caret.empty || caret.head !== at) return tr; - let inserted = false; - tr.changes.iterChangedRanges((fromA, toA) => { - if (fromA <= at && toA >= at) inserted = true; + let edit: { from: number; to: number; insert: string } | null = null; + tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => { + if (!edit && fromA <= at && toA >= at) edit = { from: fromA, to: toA, insert: inserted.toString() }; }); - return inserted ? [tr, { selection: EditorSelection.cursor(tr.changes.mapPos(at, 1)), sequential: true }] : tr; + const landed = edit as { from: number; to: number; insert: string } | null; + if (!landed) return tr; + const mainAfter = tr.changes.mapPos(at, 1); + // Further carets (picked with several): the same edit around each, where the text matches. + const replaced = tr.startState.sliceDoc(landed.from, landed.to); + const before = at - landed.from; + const after = landed.to - at; + const others: { from: number; to: number }[] = []; + for (const r of tr.startState.selection.ranges) { + if (r === caret || !r.empty) continue; + const from = r.head - before; + const to = r.head + after; + if (from < 0 || to > tr.startState.doc.length || tr.startState.sliceDoc(from, to) !== replaced) continue; + if (tr.changes.touchesRange(from, to)) continue; + others.push({ from: tr.changes.mapPos(from, 1), to: tr.changes.mapPos(to, -1) }); + } + if (!others.length) return [tr, { selection: EditorSelection.cursor(mainAfter), sequential: true }]; + const mirror = ChangeSet.of( + others.map((o) => ({ from: o.from, to: o.to, insert: landed.insert })), + tr.newDoc.length, + ); + const cursors = [ + { pos: mirror.mapPos(mainAfter, 1), main: true }, + ...others.map((o) => ({ pos: mirror.mapPos(o.from, -1) + landed.insert.length, main: false })), + ].sort((a, b) => a.pos - b.pos); + return [ + tr, + { + changes: mirror, + selection: EditorSelection.create( + cursors.map((c) => EditorSelection.cursor(c.pos)), + cursors.findIndex((c) => c.main), + ), + sequential: true, + }, + ]; }); /** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */ const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]); +/** kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing goes in here. */ +function serverInserts(item: CompletionItem): boolean { + const cmd = item.command?.command; + return !!cmd && !item.insertText && !CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor."); +} + function runCommand(view: EditorView, item: CompletionItem) { const command = item.command; if (!command?.command) return; const cmd = command.command; - // kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing went in here. - const serverInserted = !item.insertText && !CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor."); + const serverInserted = serverInserts(item); if (serverInserted) view.dispatch({ effects: awaitServerInsert.of(view.state.selection.main.head) }); if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0); else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0); diff --git a/src/editor/lsp/snippet.ts b/src/editor/lsp/snippet.ts index d56ba63b8..e6f98721f 100644 --- a/src/editor/lsp/snippet.ts +++ b/src/editor/lsp/snippet.ts @@ -215,6 +215,38 @@ export function lspSnippetToPlain(snippet: string, vars: SnippetVariables = {}): return flatten(parse(snippet), vars); } +/** + * The snippet as plain text with where its caret goes: the start of the first tab stop + * (`$1`, else the lowest), else `$0`, else the end. For insertion at several carets, + * where fields cannot be edited together. + */ +export function lspSnippetToPlainWithCaret( + snippet: string, + vars: SnippetVariables = {}, +): { text: string; caret: number } { + let text = ""; + let best: { n: number; at: number } | null = null; + const visit = (nodes: Node[]) => { + for (const n of nodes) { + if (n.t === "text") text += n.v; + else if (n.t === "tab" || n.t === "choice") { + const order = n.n === 0 ? Number.MAX_SAFE_INTEGER : n.n; + if (!best || order < best.n) best = { n: order, at: text.length }; + if (n.t === "choice") text += n.options[0] ?? ""; + else if (n.children) visit(n.children); + } else { + const v = vars[n.name]; + if (v !== undefined) text += v; + else if (n.children) visit(n.children); + else text += n.name; + } + } + }; + visit(parse(snippet)); + const found = best as { n: number; at: number } | null; + return { text, caret: found ? found.at : text.length }; +} + /** Standard LSP snippet variables for a file. */ export function snippetVariables(path: string, extra: SnippetVariables = {}): SnippetVariables { const slash = path.lastIndexOf("/");